From 3c165c6f01e66aeeb4b0e04d50958fa16efc9a2a Mon Sep 17 00:00:00 2001 From: Ivailo Monev Date: Thu, 13 Nov 2014 03:32:20 +0200 Subject: [PATCH] removed nepomuk support --- CMakeLists.txt | 22 - cmake/modules/FindKNepomuk.cmake | 39 - cmake/modules/FindNepomuk.cmake | 96 -- cmake/modules/FindSoprano.cmake | 245 --- cmake/modules/NepomukAddOntologyClasses.cmake | 115 -- cmake/modules/NepomukMacros.cmake | 67 - config-nepomuk.h.cmake | 1 - includes/CMakeLists.txt | 71 - includes/Nepomuk/File | 1 - includes/Nepomuk/KRatingPainter | 1 - includes/Nepomuk/KRatingWidget | 1 - includes/Nepomuk/MassUpdateJob | 1 - includes/Nepomuk/Query/AndTerm | 1 - includes/Nepomuk/Query/ComparisonTerm | 1 - includes/Nepomuk/Query/FileQuery | 1 - includes/Nepomuk/Query/GroupTerm | 1 - includes/Nepomuk/Query/LiteralTerm | 1 - includes/Nepomuk/Query/NegationTerm | 1 - includes/Nepomuk/Query/OptionalTerm | 1 - includes/Nepomuk/Query/OrTerm | 1 - includes/Nepomuk/Query/Query | 1 - includes/Nepomuk/Query/QueryParser | 1 - includes/Nepomuk/Query/QueryServiceClient | 1 - includes/Nepomuk/Query/ResourceTerm | 1 - includes/Nepomuk/Query/ResourceTypeTerm | 1 - includes/Nepomuk/Query/Result | 1 - includes/Nepomuk/Query/SimpleTerm | 1 - includes/Nepomuk/Query/StandardQuery | 1 - includes/Nepomuk/Query/Term | 1 - includes/Nepomuk/Resource | 1 - includes/Nepomuk/ResourceManager | 1 - includes/Nepomuk/Service | 1 - includes/Nepomuk/Tag | 1 - includes/Nepomuk/TagWidget | 1 - includes/Nepomuk/Thing | 1 - includes/Nepomuk/Types/Class | 1 - includes/Nepomuk/Types/Literal | 1 - includes/Nepomuk/Types/Ontology | 1 - includes/Nepomuk/Types/Property | 1 - includes/Nepomuk/Utils/DynamicResourceFacet | 1 - includes/Nepomuk/Utils/Facet | 1 - includes/Nepomuk/Utils/FacetWidget | 1 - includes/Nepomuk/Utils/ProxyFacet | 1 - includes/Nepomuk/Utils/ResourceModel | 1 - includes/Nepomuk/Utils/SearchWidget | 1 - includes/Nepomuk/Utils/SimpleFacet | 1 - includes/Nepomuk/Utils/SimpleResourceModel | 1 - includes/Nepomuk/Variant | 1 - includes/Nepomuk/Vocabulary/NCAL | 1 - includes/Nepomuk/Vocabulary/NCO | 1 - includes/Nepomuk/Vocabulary/NDO | 1 - includes/Nepomuk/Vocabulary/NEXIF | 1 - includes/Nepomuk/Vocabulary/NFO | 1 - includes/Nepomuk/Vocabulary/NIE | 1 - includes/Nepomuk/Vocabulary/NMM | 1 - includes/Nepomuk/Vocabulary/NMO | 1 - includes/Nepomuk/Vocabulary/NUAO | 1 - includes/Nepomuk/Vocabulary/PIMO | 1 - includes/Nepomuk/Vocabulary/TMO | 1 - kdecore/io/kdebug.h | 2 - kfile/CMakeLists.txt | 3 - kio/CMakeLists.txt | 47 - kio/kfile/kcommentwidget.cpp | 150 -- kio/kfile/kcommentwidget_p.h | 69 - .../kfilemetadataconfigurationwidget.cpp | 41 - kio/kfile/kfilemetadataprovider.cpp | 559 ------- kio/kfile/kfilemetadataprovider_p.h | 145 -- kio/kfile/kfilemetadatareader.cpp | 146 -- kio/kfile/kfilemetadatareader_p.h | 92 - kio/kfile/kfilemetadatareaderprocess.cpp | 257 --- kio/kfile/kfilemetadatawidget.cpp | 156 -- kio/kfile/knfotranslator.cpp | 8 - kio/kio/kfileitem.cpp | 16 - kio/kio/kfilemetainfoitem.cpp | 10 +- kio/kio/kfilemetainfoitem_p.h | 6 - kparts/CMakeLists.txt | 10 - kparts/browserrun_p.h | 12 - nepomuk/.emacs-dirvars | 14 - nepomuk/CMakeLists.txt | 209 --- nepomuk/Mainpage.dox | 647 -------- nepomuk/core/dbusconnectionpool.cpp | 59 - nepomuk/core/dbusconnectionpool.h | 39 - nepomuk/core/dbustypes.cpp | 136 -- nepomuk/core/dbustypes.h | 59 - nepomuk/core/file.cpp | 65 - nepomuk/core/file.h | 89 - nepomuk/core/nepomukmainmodel.cpp | 265 --- nepomuk/core/nepomukmainmodel.h | 126 -- nepomuk/core/nepomukservice.cpp | 62 - nepomuk/core/nepomukservice.h | 145 -- .../core/org.kde.nepomuk.ResourceWatcher.xml | 14 - ....kde.nepomuk.ResourceWatcherConnection.xml | 65 - nepomuk/core/resource.cpp | 1020 ------------ nepomuk/core/resource.h | 810 --------- nepomuk/core/resourcedata.cpp | 858 ---------- nepomuk/core/resourcedata.h | 220 --- nepomuk/core/resourcemanager.cpp | 562 ------- nepomuk/core/resourcemanager.h | 289 ---- nepomuk/core/resourcemanager_p.h | 131 -- nepomuk/core/resourcewatcher.cpp | 307 ---- nepomuk/core/resourcewatcher.h | 342 ---- nepomuk/core/tag.cpp | 131 -- nepomuk/core/tag.h | 148 -- nepomuk/core/thing.cpp | 127 -- nepomuk/core/thing.h | 188 --- nepomuk/core/tools.cpp | 94 -- nepomuk/core/tools.h | 123 -- nepomuk/core/variant.cpp | 1475 ----------------- nepomuk/core/variant.h | 405 ----- nepomuk/nepomuk_export.h | 39 - nepomuk/query/CMakeLists.txt | 88 - nepomuk/query/andterm.cpp | 107 -- nepomuk/query/andterm.h | 85 - nepomuk/query/andterm_p.h | 60 - nepomuk/query/comparisonterm.cpp | 555 ------- nepomuk/query/comparisonterm.h | 419 ----- nepomuk/query/comparisonterm_p.h | 79 - nepomuk/query/dateparser.cpp | 357 ---- nepomuk/query/dateparser_p.h | 87 - nepomuk/query/dbusoperators.cpp | 171 -- nepomuk/query/dbusoperators_p.h | 55 - nepomuk/query/filequery.cpp | 123 -- nepomuk/query/filequery.h | 197 --- nepomuk/query/groupterm.cpp | 112 -- nepomuk/query/groupterm.h | 87 - nepomuk/query/groupterm_p.h | 40 - nepomuk/query/literalterm.cpp | 271 --- nepomuk/query/literalterm.h | 128 -- nepomuk/query/literalterm_p.h | 49 - nepomuk/query/negationterm.cpp | 111 -- nepomuk/query/negationterm.h | 81 - nepomuk/query/negationterm_p.h | 43 - nepomuk/query/nepomukquery_export.h | 43 - nepomuk/query/optionalterm.cpp | 69 - nepomuk/query/optionalterm.h | 81 - nepomuk/query/optionalterm_p.h | 43 - nepomuk/query/org.kde.nepomuk.Query.xml | 26 - .../query/org.kde.nepomuk.QueryService.xml | 20 - nepomuk/query/orterm.cpp | 89 - nepomuk/query/orterm.h | 85 - nepomuk/query/orterm_p.h | 43 - nepomuk/query/query.cpp | 730 -------- nepomuk/query/query.h | 608 ------- nepomuk/query/query_p.h | 81 - nepomuk/query/querybuilderdata_p.h | 297 ---- nepomuk/query/queryparser.cpp | 815 --------- nepomuk/query/queryparser.h | 205 --- nepomuk/query/queryserializer.cpp | 493 ------ nepomuk/query/queryserializer.h | 39 - nepomuk/query/queryserviceclient.cpp | 449 ----- nepomuk/query/queryserviceclient.h | 343 ---- nepomuk/query/queryserviceclient_p.h | 49 - nepomuk/query/resourceterm.cpp | 115 -- nepomuk/query/resourceterm.h | 94 -- nepomuk/query/resourceterm_p.h | 50 - nepomuk/query/resourcetypeterm.cpp | 110 -- nepomuk/query/resourcetypeterm.h | 90 - nepomuk/query/resourcetypeterm_p.h | 51 - nepomuk/query/result.cpp | 176 -- nepomuk/query/result.h | 221 --- nepomuk/query/simpleterm.cpp | 63 - nepomuk/query/simpleterm.h | 72 - nepomuk/query/simpleterm_p.h | 41 - nepomuk/query/standardqueries.cpp | 150 -- nepomuk/query/standardqueries.h | 142 -- nepomuk/query/term.cpp | 527 ------ nepomuk/query/term.h | 593 ------- nepomuk/query/term_p.h | 57 - nepomuk/query/util.h | 52 - nepomuk/rcgen/CMakeLists.txt | 28 - nepomuk/rcgen/abstractcode.h | 151 -- nepomuk/rcgen/codegenerator.cpp | 510 ------ nepomuk/rcgen/codegenerator.h | 71 - nepomuk/rcgen/fastcode.cpp | 142 -- nepomuk/rcgen/fastcode.h | 63 - nepomuk/rcgen/ontologyparser.cpp | 246 --- nepomuk/rcgen/ontologyparser.h | 37 - nepomuk/rcgen/property.cpp | 229 --- nepomuk/rcgen/property.h | 173 -- nepomuk/rcgen/rcgen.cpp | 201 --- nepomuk/rcgen/resourceclass.cpp | 138 -- nepomuk/rcgen/resourceclass.h | 136 -- nepomuk/rcgen/safecode.cpp | 210 --- nepomuk/rcgen/safecode.h | 64 - nepomuk/rcgen/templates.qrc | 12 - .../templates/dummyresource_header_fast.tpl | 46 - .../templates/dummyresource_source_fast.tpl | 66 - nepomuk/rcgen/templates/gpl.tpl | 15 - nepomuk/rcgen/templates/header_fast.tpl | 33 - nepomuk/rcgen/templates/header_safe.tpl | 66 - nepomuk/rcgen/templates/source_fast.tpl | 22 - nepomuk/rcgen/templates/source_safe.tpl | 93 -- nepomuk/test/CMakeLists.txt | 108 -- nepomuk/test/dynamicresourcefacettest.cpp | 416 ----- nepomuk/test/dynamicresourcefacettest.h | 68 - nepomuk/test/facetmodeltest.cpp | 215 --- nepomuk/test/facetmodeltest.h | 37 - nepomuk/test/proxyfacettest.cpp | 151 -- nepomuk/test/proxyfacettest.h | 38 - nepomuk/test/qtest_querytostring.h | 48 - nepomuk/test/queryparsertest.cpp | 212 --- nepomuk/test/queryparsertest.h | 51 - nepomuk/test/queryserializertest.cpp | 292 ---- nepomuk/test/queryserializertest.h | 38 - nepomuk/test/querytest.cpp | 664 -------- nepomuk/test/querytest.h | 45 - nepomuk/test/ratingpaintertestapp.cpp | 14 - nepomuk/test/ratingpaintertestwidget.cpp | 138 -- nepomuk/test/ratingpaintertestwidget.h | 39 - nepomuk/test/simplefacettest.cpp | 281 ---- nepomuk/test/simplefacettest.h | 39 - nepomuk/test/tagwidgetapp.cpp | 14 - nepomuk/test/tagwidgettest.cpp | 95 -- nepomuk/test/tagwidgettest.h | 30 - nepomuk/test/typefacettest.cpp | 104 -- nepomuk/test/typefacettest.h | 39 - nepomuk/types/class.cpp | 665 -------- nepomuk/types/class.h | 400 ----- nepomuk/types/class_p.h | 85 - nepomuk/types/desktopontologyloader.cpp | 114 -- nepomuk/types/desktopontologyloader.h | 62 - nepomuk/types/entity.cpp | 406 ----- nepomuk/types/entity.h | 309 ---- nepomuk/types/entity_p.h | 92 - nepomuk/types/entitymanager.cpp | 87 - nepomuk/types/entitymanager.h | 64 - nepomuk/types/fileontologyloader.cpp | 108 -- nepomuk/types/fileontologyloader.h | 89 - nepomuk/types/global.cpp | 38 - nepomuk/types/global.h | 32 - nepomuk/types/literal.cpp | 184 -- nepomuk/types/literal.h | 125 -- nepomuk/types/literal_p.h | 53 - nepomuk/types/nepomukontologyloader.cpp | 65 - nepomuk/types/nepomukontologyloader.h | 45 - nepomuk/types/ontology.cpp | 363 ---- nepomuk/types/ontology.h | 238 --- nepomuk/types/ontology_p.h | 77 - nepomuk/types/ontologyloader.cpp | 35 - nepomuk/types/ontologyloader.h | 60 - nepomuk/types/ontologymanager.cpp | 343 ---- nepomuk/types/ontologymanager.h | 99 -- nepomuk/types/property.cpp | 565 ------- nepomuk/types/property.h | 428 ----- nepomuk/types/property_p.h | 95 -- nepomuk/ui/kblocklayout.cpp | 272 --- nepomuk/ui/kblocklayout.h | 76 - nepomuk/ui/kedittagsdialog.cpp | 280 ---- nepomuk/ui/kedittagsdialog_p.h | 79 - nepomuk/ui/kmetadatatagcloud.cpp | 109 -- nepomuk/ui/kmetadatatagcloud.h | 91 - nepomuk/ui/kmetadatatagwidget.h | 2 - nepomuk/ui/ktagcloudwidget.cpp | 179 -- nepomuk/ui/ktagcloudwidget.h | 84 - nepomuk/ui/ktagdisplaywidget.cpp | 119 -- nepomuk/ui/ktagdisplaywidget.h | 70 - nepomuk/ui/nepomukmassupdatejob.cpp | 164 -- nepomuk/ui/nepomukmassupdatejob.h | 103 -- nepomuk/ui/tagcheckbox.cpp | 167 -- nepomuk/ui/tagcheckbox.h | 76 - nepomuk/ui/tagwidget.cpp | 409 ----- nepomuk/ui/tagwidget.h | 242 --- nepomuk/ui/tagwidget_p.h | 73 - nepomuk/utils/CMakeLists.txt | 64 - nepomuk/utils/datefacet.cpp | 420 ----- nepomuk/utils/datefacet.h | 228 --- nepomuk/utils/daterange.cpp | 264 --- nepomuk/utils/daterange.h | 214 --- nepomuk/utils/daterangeselectionwidget.cpp | 337 ---- nepomuk/utils/daterangeselectionwidget.h | 91 - nepomuk/utils/daterangeselectionwidget.ui | 123 -- nepomuk/utils/dynamicresourcefacet.cpp | 422 ----- nepomuk/utils/dynamicresourcefacet.h | 271 --- nepomuk/utils/dynamicresourcefacet_p.h | 92 - nepomuk/utils/facet.cpp | 199 --- nepomuk/utils/facet.h | 318 ---- nepomuk/utils/facetdelegate.cpp | 85 - nepomuk/utils/facetdelegate.h | 47 - nepomuk/utils/facetfiltermodel.cpp | 45 - nepomuk/utils/facetfiltermodel.h | 56 - nepomuk/utils/facetmodel.cpp | 410 ----- nepomuk/utils/facetmodel.h | 231 --- nepomuk/utils/facetwidget.cpp | 131 -- nepomuk/utils/facetwidget.h | 136 -- nepomuk/utils/nepomukutils_export.h | 40 - nepomuk/utils/proxyfacet.cpp | 213 --- nepomuk/utils/proxyfacet.h | 160 -- nepomuk/utils/resourcemodel.cpp | 230 --- nepomuk/utils/resourcemodel.h | 177 -- nepomuk/utils/searchlineedit.cpp | 157 -- nepomuk/utils/searchlineedit.h | 97 -- nepomuk/utils/searchwidget.cpp | 316 ---- nepomuk/utils/searchwidget.h | 214 --- nepomuk/utils/searchwidget_p.h | 82 - nepomuk/utils/simplefacet.cpp | 266 --- nepomuk/utils/simplefacet.h | 152 -- nepomuk/utils/simpleresourcemodel.cpp | 170 -- nepomuk/utils/simpleresourcemodel.h | 144 -- nepomuk/utils/typefacet.cpp | 417 ----- nepomuk/utils/typefacet.h | 56 - nepomuk/utils/utils.cpp | 217 --- nepomuk/utils/utils.h | 109 -- .../backends/udisks2/udisksdevicebackend.h | 2 +- 303 files changed, 2 insertions(+), 43466 deletions(-) delete mode 100644 cmake/modules/FindKNepomuk.cmake delete mode 100644 cmake/modules/FindNepomuk.cmake delete mode 100644 cmake/modules/FindSoprano.cmake delete mode 100644 cmake/modules/NepomukAddOntologyClasses.cmake delete mode 100644 cmake/modules/NepomukMacros.cmake delete mode 100644 config-nepomuk.h.cmake delete mode 100644 includes/Nepomuk/File delete mode 100644 includes/Nepomuk/KRatingPainter delete mode 100644 includes/Nepomuk/KRatingWidget delete mode 100644 includes/Nepomuk/MassUpdateJob delete mode 100644 includes/Nepomuk/Query/AndTerm delete mode 100644 includes/Nepomuk/Query/ComparisonTerm delete mode 100644 includes/Nepomuk/Query/FileQuery delete mode 100644 includes/Nepomuk/Query/GroupTerm delete mode 100644 includes/Nepomuk/Query/LiteralTerm delete mode 100644 includes/Nepomuk/Query/NegationTerm delete mode 100644 includes/Nepomuk/Query/OptionalTerm delete mode 100644 includes/Nepomuk/Query/OrTerm delete mode 100644 includes/Nepomuk/Query/Query delete mode 100644 includes/Nepomuk/Query/QueryParser delete mode 100644 includes/Nepomuk/Query/QueryServiceClient delete mode 100644 includes/Nepomuk/Query/ResourceTerm delete mode 100644 includes/Nepomuk/Query/ResourceTypeTerm delete mode 100644 includes/Nepomuk/Query/Result delete mode 100644 includes/Nepomuk/Query/SimpleTerm delete mode 100644 includes/Nepomuk/Query/StandardQuery delete mode 100644 includes/Nepomuk/Query/Term delete mode 100644 includes/Nepomuk/Resource delete mode 100644 includes/Nepomuk/ResourceManager delete mode 100644 includes/Nepomuk/Service delete mode 100644 includes/Nepomuk/Tag delete mode 100644 includes/Nepomuk/TagWidget delete mode 100644 includes/Nepomuk/Thing delete mode 100644 includes/Nepomuk/Types/Class delete mode 100644 includes/Nepomuk/Types/Literal delete mode 100644 includes/Nepomuk/Types/Ontology delete mode 100644 includes/Nepomuk/Types/Property delete mode 100644 includes/Nepomuk/Utils/DynamicResourceFacet delete mode 100644 includes/Nepomuk/Utils/Facet delete mode 100644 includes/Nepomuk/Utils/FacetWidget delete mode 100644 includes/Nepomuk/Utils/ProxyFacet delete mode 100644 includes/Nepomuk/Utils/ResourceModel delete mode 100644 includes/Nepomuk/Utils/SearchWidget delete mode 100644 includes/Nepomuk/Utils/SimpleFacet delete mode 100644 includes/Nepomuk/Utils/SimpleResourceModel delete mode 100644 includes/Nepomuk/Variant delete mode 100644 includes/Nepomuk/Vocabulary/NCAL delete mode 100644 includes/Nepomuk/Vocabulary/NCO delete mode 100644 includes/Nepomuk/Vocabulary/NDO delete mode 100644 includes/Nepomuk/Vocabulary/NEXIF delete mode 100644 includes/Nepomuk/Vocabulary/NFO delete mode 100644 includes/Nepomuk/Vocabulary/NIE delete mode 100644 includes/Nepomuk/Vocabulary/NMM delete mode 100644 includes/Nepomuk/Vocabulary/NMO delete mode 100644 includes/Nepomuk/Vocabulary/NUAO delete mode 100644 includes/Nepomuk/Vocabulary/PIMO delete mode 100644 includes/Nepomuk/Vocabulary/TMO delete mode 100644 kio/kfile/kcommentwidget.cpp delete mode 100644 kio/kfile/kcommentwidget_p.h delete mode 100644 kio/kfile/kfilemetadataprovider.cpp delete mode 100644 kio/kfile/kfilemetadataprovider_p.h delete mode 100644 kio/kfile/kfilemetadatareader.cpp delete mode 100644 kio/kfile/kfilemetadatareader_p.h delete mode 100644 kio/kfile/kfilemetadatareaderprocess.cpp delete mode 100644 nepomuk/.emacs-dirvars delete mode 100644 nepomuk/CMakeLists.txt delete mode 100644 nepomuk/Mainpage.dox delete mode 100644 nepomuk/core/dbusconnectionpool.cpp delete mode 100644 nepomuk/core/dbusconnectionpool.h delete mode 100644 nepomuk/core/dbustypes.cpp delete mode 100644 nepomuk/core/dbustypes.h delete mode 100644 nepomuk/core/file.cpp delete mode 100644 nepomuk/core/file.h delete mode 100644 nepomuk/core/nepomukmainmodel.cpp delete mode 100644 nepomuk/core/nepomukmainmodel.h delete mode 100644 nepomuk/core/nepomukservice.cpp delete mode 100644 nepomuk/core/nepomukservice.h delete mode 100644 nepomuk/core/org.kde.nepomuk.ResourceWatcher.xml delete mode 100644 nepomuk/core/org.kde.nepomuk.ResourceWatcherConnection.xml delete mode 100644 nepomuk/core/resource.cpp delete mode 100644 nepomuk/core/resource.h delete mode 100644 nepomuk/core/resourcedata.cpp delete mode 100644 nepomuk/core/resourcedata.h delete mode 100644 nepomuk/core/resourcemanager.cpp delete mode 100644 nepomuk/core/resourcemanager.h delete mode 100644 nepomuk/core/resourcemanager_p.h delete mode 100644 nepomuk/core/resourcewatcher.cpp delete mode 100644 nepomuk/core/resourcewatcher.h delete mode 100644 nepomuk/core/tag.cpp delete mode 100644 nepomuk/core/tag.h delete mode 100644 nepomuk/core/thing.cpp delete mode 100644 nepomuk/core/thing.h delete mode 100644 nepomuk/core/tools.cpp delete mode 100644 nepomuk/core/tools.h delete mode 100644 nepomuk/core/variant.cpp delete mode 100644 nepomuk/core/variant.h delete mode 100644 nepomuk/nepomuk_export.h delete mode 100644 nepomuk/query/CMakeLists.txt delete mode 100644 nepomuk/query/andterm.cpp delete mode 100644 nepomuk/query/andterm.h delete mode 100644 nepomuk/query/andterm_p.h delete mode 100644 nepomuk/query/comparisonterm.cpp delete mode 100644 nepomuk/query/comparisonterm.h delete mode 100644 nepomuk/query/comparisonterm_p.h delete mode 100644 nepomuk/query/dateparser.cpp delete mode 100644 nepomuk/query/dateparser_p.h delete mode 100644 nepomuk/query/dbusoperators.cpp delete mode 100644 nepomuk/query/dbusoperators_p.h delete mode 100644 nepomuk/query/filequery.cpp delete mode 100644 nepomuk/query/filequery.h delete mode 100644 nepomuk/query/groupterm.cpp delete mode 100644 nepomuk/query/groupterm.h delete mode 100644 nepomuk/query/groupterm_p.h delete mode 100644 nepomuk/query/literalterm.cpp delete mode 100644 nepomuk/query/literalterm.h delete mode 100644 nepomuk/query/literalterm_p.h delete mode 100644 nepomuk/query/negationterm.cpp delete mode 100644 nepomuk/query/negationterm.h delete mode 100644 nepomuk/query/negationterm_p.h delete mode 100644 nepomuk/query/nepomukquery_export.h delete mode 100644 nepomuk/query/optionalterm.cpp delete mode 100644 nepomuk/query/optionalterm.h delete mode 100644 nepomuk/query/optionalterm_p.h delete mode 100644 nepomuk/query/org.kde.nepomuk.Query.xml delete mode 100644 nepomuk/query/org.kde.nepomuk.QueryService.xml delete mode 100644 nepomuk/query/orterm.cpp delete mode 100644 nepomuk/query/orterm.h delete mode 100644 nepomuk/query/orterm_p.h delete mode 100644 nepomuk/query/query.cpp delete mode 100644 nepomuk/query/query.h delete mode 100644 nepomuk/query/query_p.h delete mode 100644 nepomuk/query/querybuilderdata_p.h delete mode 100644 nepomuk/query/queryparser.cpp delete mode 100644 nepomuk/query/queryparser.h delete mode 100644 nepomuk/query/queryserializer.cpp delete mode 100644 nepomuk/query/queryserializer.h delete mode 100644 nepomuk/query/queryserviceclient.cpp delete mode 100644 nepomuk/query/queryserviceclient.h delete mode 100644 nepomuk/query/queryserviceclient_p.h delete mode 100644 nepomuk/query/resourceterm.cpp delete mode 100644 nepomuk/query/resourceterm.h delete mode 100644 nepomuk/query/resourceterm_p.h delete mode 100644 nepomuk/query/resourcetypeterm.cpp delete mode 100644 nepomuk/query/resourcetypeterm.h delete mode 100644 nepomuk/query/resourcetypeterm_p.h delete mode 100644 nepomuk/query/result.cpp delete mode 100644 nepomuk/query/result.h delete mode 100644 nepomuk/query/simpleterm.cpp delete mode 100644 nepomuk/query/simpleterm.h delete mode 100644 nepomuk/query/simpleterm_p.h delete mode 100644 nepomuk/query/standardqueries.cpp delete mode 100644 nepomuk/query/standardqueries.h delete mode 100644 nepomuk/query/term.cpp delete mode 100644 nepomuk/query/term.h delete mode 100644 nepomuk/query/term_p.h delete mode 100644 nepomuk/query/util.h delete mode 100644 nepomuk/rcgen/CMakeLists.txt delete mode 100644 nepomuk/rcgen/abstractcode.h delete mode 100644 nepomuk/rcgen/codegenerator.cpp delete mode 100644 nepomuk/rcgen/codegenerator.h delete mode 100644 nepomuk/rcgen/fastcode.cpp delete mode 100644 nepomuk/rcgen/fastcode.h delete mode 100644 nepomuk/rcgen/ontologyparser.cpp delete mode 100644 nepomuk/rcgen/ontologyparser.h delete mode 100644 nepomuk/rcgen/property.cpp delete mode 100644 nepomuk/rcgen/property.h delete mode 100644 nepomuk/rcgen/rcgen.cpp delete mode 100644 nepomuk/rcgen/resourceclass.cpp delete mode 100644 nepomuk/rcgen/resourceclass.h delete mode 100644 nepomuk/rcgen/safecode.cpp delete mode 100644 nepomuk/rcgen/safecode.h delete mode 100644 nepomuk/rcgen/templates.qrc delete mode 100644 nepomuk/rcgen/templates/dummyresource_header_fast.tpl delete mode 100644 nepomuk/rcgen/templates/dummyresource_source_fast.tpl delete mode 100644 nepomuk/rcgen/templates/gpl.tpl delete mode 100644 nepomuk/rcgen/templates/header_fast.tpl delete mode 100644 nepomuk/rcgen/templates/header_safe.tpl delete mode 100644 nepomuk/rcgen/templates/source_fast.tpl delete mode 100644 nepomuk/rcgen/templates/source_safe.tpl delete mode 100644 nepomuk/test/CMakeLists.txt delete mode 100644 nepomuk/test/dynamicresourcefacettest.cpp delete mode 100644 nepomuk/test/dynamicresourcefacettest.h delete mode 100644 nepomuk/test/facetmodeltest.cpp delete mode 100644 nepomuk/test/facetmodeltest.h delete mode 100644 nepomuk/test/proxyfacettest.cpp delete mode 100644 nepomuk/test/proxyfacettest.h delete mode 100644 nepomuk/test/qtest_querytostring.h delete mode 100644 nepomuk/test/queryparsertest.cpp delete mode 100644 nepomuk/test/queryparsertest.h delete mode 100644 nepomuk/test/queryserializertest.cpp delete mode 100644 nepomuk/test/queryserializertest.h delete mode 100644 nepomuk/test/querytest.cpp delete mode 100644 nepomuk/test/querytest.h delete mode 100644 nepomuk/test/ratingpaintertestapp.cpp delete mode 100644 nepomuk/test/ratingpaintertestwidget.cpp delete mode 100644 nepomuk/test/ratingpaintertestwidget.h delete mode 100644 nepomuk/test/simplefacettest.cpp delete mode 100644 nepomuk/test/simplefacettest.h delete mode 100644 nepomuk/test/tagwidgetapp.cpp delete mode 100644 nepomuk/test/tagwidgettest.cpp delete mode 100644 nepomuk/test/tagwidgettest.h delete mode 100644 nepomuk/test/typefacettest.cpp delete mode 100644 nepomuk/test/typefacettest.h delete mode 100644 nepomuk/types/class.cpp delete mode 100644 nepomuk/types/class.h delete mode 100644 nepomuk/types/class_p.h delete mode 100644 nepomuk/types/desktopontologyloader.cpp delete mode 100644 nepomuk/types/desktopontologyloader.h delete mode 100644 nepomuk/types/entity.cpp delete mode 100644 nepomuk/types/entity.h delete mode 100644 nepomuk/types/entity_p.h delete mode 100644 nepomuk/types/entitymanager.cpp delete mode 100644 nepomuk/types/entitymanager.h delete mode 100644 nepomuk/types/fileontologyloader.cpp delete mode 100644 nepomuk/types/fileontologyloader.h delete mode 100644 nepomuk/types/global.cpp delete mode 100644 nepomuk/types/global.h delete mode 100644 nepomuk/types/literal.cpp delete mode 100644 nepomuk/types/literal.h delete mode 100644 nepomuk/types/literal_p.h delete mode 100644 nepomuk/types/nepomukontologyloader.cpp delete mode 100644 nepomuk/types/nepomukontologyloader.h delete mode 100644 nepomuk/types/ontology.cpp delete mode 100644 nepomuk/types/ontology.h delete mode 100644 nepomuk/types/ontology_p.h delete mode 100644 nepomuk/types/ontologyloader.cpp delete mode 100644 nepomuk/types/ontologyloader.h delete mode 100644 nepomuk/types/ontologymanager.cpp delete mode 100644 nepomuk/types/ontologymanager.h delete mode 100644 nepomuk/types/property.cpp delete mode 100644 nepomuk/types/property.h delete mode 100644 nepomuk/types/property_p.h delete mode 100644 nepomuk/ui/kblocklayout.cpp delete mode 100644 nepomuk/ui/kblocklayout.h delete mode 100644 nepomuk/ui/kedittagsdialog.cpp delete mode 100644 nepomuk/ui/kedittagsdialog_p.h delete mode 100644 nepomuk/ui/kmetadatatagcloud.cpp delete mode 100644 nepomuk/ui/kmetadatatagcloud.h delete mode 100644 nepomuk/ui/kmetadatatagwidget.h delete mode 100644 nepomuk/ui/ktagcloudwidget.cpp delete mode 100644 nepomuk/ui/ktagcloudwidget.h delete mode 100644 nepomuk/ui/ktagdisplaywidget.cpp delete mode 100644 nepomuk/ui/ktagdisplaywidget.h delete mode 100644 nepomuk/ui/nepomukmassupdatejob.cpp delete mode 100644 nepomuk/ui/nepomukmassupdatejob.h delete mode 100644 nepomuk/ui/tagcheckbox.cpp delete mode 100644 nepomuk/ui/tagcheckbox.h delete mode 100644 nepomuk/ui/tagwidget.cpp delete mode 100644 nepomuk/ui/tagwidget.h delete mode 100644 nepomuk/ui/tagwidget_p.h delete mode 100644 nepomuk/utils/CMakeLists.txt delete mode 100644 nepomuk/utils/datefacet.cpp delete mode 100644 nepomuk/utils/datefacet.h delete mode 100644 nepomuk/utils/daterange.cpp delete mode 100644 nepomuk/utils/daterange.h delete mode 100644 nepomuk/utils/daterangeselectionwidget.cpp delete mode 100644 nepomuk/utils/daterangeselectionwidget.h delete mode 100644 nepomuk/utils/daterangeselectionwidget.ui delete mode 100644 nepomuk/utils/dynamicresourcefacet.cpp delete mode 100644 nepomuk/utils/dynamicresourcefacet.h delete mode 100644 nepomuk/utils/dynamicresourcefacet_p.h delete mode 100644 nepomuk/utils/facet.cpp delete mode 100644 nepomuk/utils/facet.h delete mode 100644 nepomuk/utils/facetdelegate.cpp delete mode 100644 nepomuk/utils/facetdelegate.h delete mode 100644 nepomuk/utils/facetfiltermodel.cpp delete mode 100644 nepomuk/utils/facetfiltermodel.h delete mode 100644 nepomuk/utils/facetmodel.cpp delete mode 100644 nepomuk/utils/facetmodel.h delete mode 100644 nepomuk/utils/facetwidget.cpp delete mode 100644 nepomuk/utils/facetwidget.h delete mode 100644 nepomuk/utils/nepomukutils_export.h delete mode 100644 nepomuk/utils/proxyfacet.cpp delete mode 100644 nepomuk/utils/proxyfacet.h delete mode 100644 nepomuk/utils/resourcemodel.cpp delete mode 100644 nepomuk/utils/resourcemodel.h delete mode 100644 nepomuk/utils/searchlineedit.cpp delete mode 100644 nepomuk/utils/searchlineedit.h delete mode 100644 nepomuk/utils/searchwidget.cpp delete mode 100644 nepomuk/utils/searchwidget.h delete mode 100644 nepomuk/utils/searchwidget_p.h delete mode 100644 nepomuk/utils/simplefacet.cpp delete mode 100644 nepomuk/utils/simplefacet.h delete mode 100644 nepomuk/utils/simpleresourcemodel.cpp delete mode 100644 nepomuk/utils/simpleresourcemodel.h delete mode 100644 nepomuk/utils/typefacet.cpp delete mode 100644 nepomuk/utils/typefacet.h delete mode 100644 nepomuk/utils/utils.cpp delete mode 100644 nepomuk/utils/utils.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 9acbf782..8348cf2c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -128,18 +128,6 @@ set_package_properties(Libintl PROPERTIES DESCRIPTION "Support for multiple lang PURPOSE "Enables KDE to be available in many different languages" ) -macro_optional_find_package(Soprano 2.7.56 COMPONENTS PLUGIN_RAPTORPARSER PLUGIN_REDLANDBACKEND) -set_package_properties(Soprano PROPERTIES DESCRIPTION "Support for the Nepomuk semantic desktop system" - URL "http://soprano.sourceforge.net" - TYPE OPTIONAL - ) - -macro_optional_find_package(SharedDesktopOntologies 0.10) -set_package_properties(SharedDesktopOntologies PROPERTIES DESCRIPTION "Support for the Nepomuk semantic desktop system" - URL "http://oscaf.sourceforge.net" - TYPE OPTIONAL - ) - macro_optional_find_package(QCA2 2.0.0) set_package_properties(QCA2 PROPERTIES DESCRIPTION "Support for remote plasma widgets" URL "http://delta.affinix.com/qca" @@ -284,20 +272,11 @@ configure_file(config-acl.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-acl.h ) include(ConfigureChecks.cmake) -# Actually nepomuk is not optional, without it other KDE modules don't build, -# so this must be fixed. Alex -if(Soprano_FOUND AND SHAREDDESKTOPONTOLOGIES_FOUND) - set(HAVE_NEPOMUK true) - include(SopranoAddOntology) - add_subdirectory(nepomuk) -endif(Soprano_FOUND AND SHAREDDESKTOPONTOLOGIES_FOUND) - # now create config headers configure_file(config.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config.h ) configure_file(config-prefix.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-prefix.h ) configure_file(config-compiler.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-compiler.h ) configure_file(config-pty.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-pty.h ) -configure_file(config-nepomuk.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-nepomuk.h ) configure_file(kdemacros.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/kdemacros.h ) # these two calls here should go somewhere else, Alex @@ -367,7 +346,6 @@ include(CreateKDELibsDependenciesFile.cmake) ################# install files ################# install( FILES ${CMAKE_CURRENT_BINARY_DIR}/kdemacros.h DESTINATION ${INCLUDE_INSTALL_DIR} ) -install( FILES ${CMAKE_CURRENT_BINARY_DIR}/config-nepomuk.h DESTINATION ${INCLUDE_INSTALL_DIR} ) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/KDELibsDependencies.cmake DESTINATION ${DATA_INSTALL_DIR}/cmake/modules) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/KDEPlatformProfile.cmake DESTINATION ${DATA_INSTALL_DIR}/cmake/modules) diff --git a/cmake/modules/FindKNepomuk.cmake b/cmake/modules/FindKNepomuk.cmake deleted file mode 100644 index 655f6fe8..00000000 --- a/cmake/modules/FindKNepomuk.cmake +++ /dev/null @@ -1,39 +0,0 @@ -# Once done this will define -# -# KNEPOMUK_FOUND - system has the Nepomuk-KDE backbone lib KNep -# KNEPOMUK_INCLUDES - the libKNep include directory -# KNEPOMUK_LIBRARIES - Link these to use libKNep -# - -# Copyright (c) 2008, Sebastian Trueg, -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. - - -if(KNEPOMUK_INCLUDES AND KNEPOMUK_LIBRARIES) - set(KNepomuk_FIND_QUIETLY TRUE) -endif(KNEPOMUK_INCLUDES AND KNEPOMUK_LIBRARIES) - -FIND_PATH(KNEPOMUK_INCLUDES - NAMES - knepomuk/knepomuk.h - PATHS - ${KDE4_INCLUDE_DIR} - ${INCLUDE_INSTALL_DIR} -) - -FIND_LIBRARY(KNEPOMUK_LIBRARIES - NAMES - knepomuk - PATHS - ${KDE4_LIB_DIR} - ${LIB_INSTALL_DIR} -) - -include(FindPackageHandleStandardArgs) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(KNepomuk DEFAULT_MSG KNEPOMUK_INCLUDES KNEPOMUK_LIBRARIES ) - - -MARK_AS_ADVANCED(KNEPOMUK_INCLUDES KNEPOMUK_LIBRARIES) - diff --git a/cmake/modules/FindNepomuk.cmake b/cmake/modules/FindNepomuk.cmake deleted file mode 100644 index b822aee7..00000000 --- a/cmake/modules/FindNepomuk.cmake +++ /dev/null @@ -1,96 +0,0 @@ -# Once done this will define -# -# NEPOMUK_FOUND - system has Nepomuk -# NEPOMUK_INCLUDE_DIRS - all include directories needed to compile Nepomuk -# NEPOMUK_INCLUDE_DIR - the Nepomuk include directory (do not use. only for compatibility) -# NEPOMUK_LIBRARIES - Link these to use Nepomuk -# NEPOMUK_QUERY_LIBRARIES - Link these to use Nepomuk query -# NEPOMUK_UTILS_LIBRARIES - Link these to use Nepomuk utils -# NEPOMUK_DEFINITIONS - Compiler switches required for using Nepomuk -# -# Nepomuk requires Soprano, so this module checks for Soprano too. -# - - -# Copyright (c) 2008-2009, Sebastian Trueg, -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. - - -if (NOT DEFINED Soprano_FOUND) - find_package(Soprano ${SOPRANO_MIN_VERSION}) -endif (NOT DEFINED Soprano_FOUND) - -if (NOT DEFINED SHAREDDESKTOPONTOLOGIES_FOUND) - find_package(SharedDesktopOntologies) -endif (NOT DEFINED SHAREDDESKTOPONTOLOGIES_FOUND) - -# Check for the following stuff independent from whether soprano has been found -# or not. This will give a better error message at the end. -find_path(NEPOMUK_INCLUDE_DIR - NAMES - nepomuk/resource.h - HINTS - ${KDE4_INCLUDE_DIR} - ${INCLUDE_INSTALL_DIR} - ) - -set(NEPOMUK_INCLUDE_DIRS ${NEPOMUK_INCLUDE_DIR} ${SOPRANO_INCLUDE_DIR}) - -find_library(NEPOMUK_LIBRARIES - NAMES - nepomuk - HINTS - ${KDE4_LIB_DIR} - ${LIB_INSTALL_DIR} - ) - -set(NEPOMUK_LIBRARIES ${NEPOMUK_LIBRARIES} ${SOPRANO_LIBRARIES}) - -find_library(NEPOMUK_QUERY_LIBRARIES - NAMES - nepomukquery - HINTS - ${KDE4_LIB_DIR} - ${LIB_INSTALL_DIR} - ) - -find_library(NEPOMUK_UTILS_LIBRARIES - NAMES - nepomukutils - HINTS - ${KDE4_LIB_DIR} - ${LIB_INSTALL_DIR} -) - -find_file(NEPOMUK_ADDONTOLOGYCLASSES_FILE NepomukAddOntologyClasses.cmake - HINTS ${KDE4_DATA_INSTALL_DIR}/cmake/modules/ - PATH_SUFFIXES share/apps/cmake/modules/ - ) - -include("${NEPOMUK_ADDONTOLOGYCLASSES_FILE}" OPTIONAL) - -mark_as_advanced(NEPOMUK_INCLUDE_DIR NEPOMUK_INCLUDE_DIRS NEPOMUK_LIBRARIES NEPOMUK_QUERY_LIBRARIES NEPOMUK_UTILS_LIBRARIES NEPOMUK_ADDONTOLOGIES_FILE) - -include(FindPackageHandleStandardArgs) -# List all nepomuk and also all necessary soprano variables here, to make it -# easier for the user to see what was missing: -if(NOT WINCE) -find_package_handle_standard_args(Nepomuk DEFAULT_MSG - NEPOMUK_LIBRARIES NEPOMUK_INCLUDE_DIR NEPOMUK_ADDONTOLOGYCLASSES_FILE - Soprano_FOUND - SHAREDDESKTOPONTOLOGIES_FOUND - ) -else(NOT WINCE) -#FIXME: There are no backends at this time -find_package_handle_standard_args(Nepomuk DEFAULT_MSG - NEPOMUK_LIBRARIES NEPOMUK_INCLUDE_DIR NEPOMUK_ADDONTOLOGYCLASSES_FILE - Soprano_FOUND - SHAREDDESKTOPONTOLOGIES_FOUND - ) -endif(NOT WINCE) - -#to retain backward compatibility -set (Nepomuk_FOUND ${NEPOMUK_FOUND}) - diff --git a/cmake/modules/FindSoprano.cmake b/cmake/modules/FindSoprano.cmake deleted file mode 100644 index 99daa4f3..00000000 --- a/cmake/modules/FindSoprano.cmake +++ /dev/null @@ -1,245 +0,0 @@ -# -# Find an installation of Soprano -# -# Sets the following variables: -# Soprano_FOUND, SOPRANO_FOUND - true is Soprano has been found -# SOPRANO_ONTO2VOCABULARYCLASS_EXECUTABLE - the onto2vocabularyclass program, required for adding ontologies -# SOPRANO_SOPRANOCMD_EXECUTABLE - the sopranocmd program -# SOPRANO_INCLUDE_DIR - The include directory -# SOPRANO_LIBRARIES - The Soprano core library to link to (libsoprano) -# SOPRANO_INDEX_LIBRARIES - The Soprano index library (libsopranoindex) -# SOPRANO_CLIENT_LIBRARIES - The Soprano client library (libsopranoclient) -# SOPRANO_SERVER_LIBRARIES - The Soprano server library (libsopranoserver) -# SOPRANO_VERSION - The Soprano version (string value) -# -# SOPRANO_PLUGIN_NQUADPARSER_FOUND - true if the nquadparser plugin is found -# SOPRANO_PLUGIN_NQUADSERIALIZER_FOUND - true if the nquadserializer plugin is found -# SOPRANO_PLUGIN_RAPTORPARSER_FOUND - true if the raptorparser plugin is found -# SOPRANO_PLUGIN_RAPTORSERIALIZER_FOUND - true if the raptorserializer plugin is found -# SOPRANO_PLUGIN_REDLANDBACKEND_FOUND - true if the redlandbackend plugin is found -# SOPRANO_PLUGIN_SESAME2BACKEND_FOUND - true if the sesame2backend plugin is found -# SOPRANO_PLUGIN_VIRTUOSOBACKEND_FOUND - true if the virtuosobackend plugin is found -# -# Options: -# Set SOPRANO_MIN_VERSION to set the minimum required Soprano version (default: 1.99) -# -# FindSoprano.cmake supports the COMPONENTS keyword of find_package(). -# If the REQUIRED keyword is used and any of the specified components have not been -# found, SOPRANO_FOUND will be set to FALSE. -# -# The following components are supported: -# PLUGIN_NQUADPARSER -# PLUGIN_NQUADSERIALIZER -# PLUGIN_RAPTORPARSER -# PLUGIN_RAPTORSERIALIZER -# PLUGIN_REDLANDBACKEND -# PLUGIN_SESAME2BACKEND -# PLUGIN_VIRTUOSOBACKEND - -# Copyright (c) 2008, Sebastian Trueg, -# Copyright (c) 2009, Alexander Neundorf, -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. - - -include(FindLibraryWithDebug) - -find_program(SOPRANO_SOPRANOCMD_EXECUTABLE - NAMES sopranocmd - HINTS - ${BIN_INSTALL_DIR} - ${KDE4_BIN_INSTALL_DIR} - ) - -if(NOT WINCE) -find_program(SOPRANO_ONTO2VOCABULARYCLASS_EXECUTABLE - NAMES onto2vocabularyclass - HINTS - ${BIN_INSTALL_DIR} - ${KDE4_BIN_INSTALL_DIR} - ) -else(NOT WINCE) -find_program(SOPRANO_ONTO2VOCABULARYCLASS_EXECUTABLE - NAMES onto2vocabularyclass - PATHS ${HOST_BINDIR} - NO_DEFAULT_PATH - ) -endif(NOT WINCE) - - -find_path(SOPRANO_INCLUDE_DIR - NAMES - soprano/soprano.h - HINTS - ${INCLUDE_INSTALL_DIR} - ${KDE4_INCLUDE_DIR} - ) - -find_library_with_debug(SOPRANO_INDEX_LIBRARIES - WIN32_DEBUG_POSTFIX d - NAMES - sopranoindex - HINTS - ${LIB_INSTALL_DIR} - ${KDE4_LIB_DIR} - ) - -find_library_with_debug(SOPRANO_CLIENT_LIBRARIES - WIN32_DEBUG_POSTFIX d - NAMES - sopranoclient - HINTS - ${LIB_INSTALL_DIR} - ${KDE4_LIB_DIR} - ) - -find_library_with_debug(SOPRANO_LIBRARIES - WIN32_DEBUG_POSTFIX d - NAMES soprano - HINTS - ${LIB_INSTALL_DIR} - ${KDE4_LIB_DIR} -) - -find_library_with_debug(SOPRANO_SERVER_LIBRARIES - WIN32_DEBUG_POSTFIX d - NAMES - sopranoserver - HINTS - ${LIB_INSTALL_DIR} - ${KDE4_LIB_DIR} - ) - -# check Soprano version - -# Support SOPRANO_MIN_VERSION for compatibility: -if(NOT Soprano_FIND_VERSION) - set(Soprano_FIND_VERSION "${SOPRANO_MIN_VERSION}") -endif(NOT Soprano_FIND_VERSION) - -# We set a default for the minimum required version to be backwards compatible -if(NOT Soprano_FIND_VERSION) - set(Soprano_FIND_VERSION "1.99") -endif(NOT Soprano_FIND_VERSION) - - -if(SOPRANO_INCLUDE_DIR) - file(READ ${SOPRANO_INCLUDE_DIR}/soprano/version.h SOPRANO_VERSION_CONTENT) - string(REGEX MATCH "SOPRANO_VERSION_STRING \".*\"\n" SOPRANO_VERSION_MATCH "${SOPRANO_VERSION_CONTENT}") - if(SOPRANO_VERSION_MATCH) - string(REGEX REPLACE "SOPRANO_VERSION_STRING \"(.*)\"\n" "\\1" SOPRANO_VERSION ${SOPRANO_VERSION_MATCH}) - # find_package_handle_standard_args will do the version checking - endif(SOPRANO_VERSION_MATCH) -endif(SOPRANO_INCLUDE_DIR) - -set(_SOPRANO_REQUIRED_COMPONENTS_RESULTS) -if( Soprano_FIND_COMPONENTS ) - foreach( _component ${Soprano_FIND_COMPONENTS} ) - set(_SOPRANO_REQUIRED_COMPONENTS_RESULTS ${_SOPRANO_REQUIRED_COMPONENTS_RESULTS} SOPRANO_${_component}_FOUND) - endforeach( _component ) -endif( Soprano_FIND_COMPONENTS ) - -#look for parser plugins -if(SOPRANO_INCLUDE_DIR) - get_filename_component(_SOPRANO_PREFIX ${SOPRANO_INCLUDE_DIR} PATH) - - find_path(SOPRANO_PLUGIN_ROOT_DIR - NAMES - soprano/plugins - HINTS - ${_SOPRANO_PREFIX}/share - ${SHARE_INSTALL_PREFIX} - PATH_SUFFIXES share - ) - set(SOPRANO_PLUGIN_DIR "${SOPRANO_PLUGIN_ROOT_DIR}/soprano/plugins") - - if(EXISTS ${SOPRANO_PLUGIN_DIR}/nquadparser.desktop) - set(SOPRANO_PLUGIN_NQUADPARSER_FOUND TRUE) - set(_plugins "${_plugins} nquadparser") - endif(EXISTS ${SOPRANO_PLUGIN_DIR}/nquadparser.desktop) - - if(EXISTS ${SOPRANO_PLUGIN_DIR}/nquadserializer.desktop) - set(SOPRANO_PLUGIN_NQUADSERIALIZER_FOUND TRUE) - set(_plugins "${_plugins} nquadserializer") - endif(EXISTS ${SOPRANO_PLUGIN_DIR}/nquadserializer.desktop) - - if(EXISTS ${SOPRANO_PLUGIN_DIR}/raptorparser.desktop) - set(SOPRANO_PLUGIN_RAPTORPARSER_FOUND TRUE) - set(_plugins "${_plugins} raptorparser") - endif(EXISTS ${SOPRANO_PLUGIN_DIR}/raptorparser.desktop) - - if(EXISTS ${SOPRANO_PLUGIN_DIR}/raptorserializer.desktop) - set(SOPRANO_PLUGIN_RAPTORSERIALIZER_FOUND TRUE) - set(_plugins "${_plugins} raptorserializer") - endif(EXISTS ${SOPRANO_PLUGIN_DIR}/raptorserializer.desktop) - - if(EXISTS ${SOPRANO_PLUGIN_DIR}/redlandbackend.desktop) - set(SOPRANO_PLUGIN_REDLANDBACKEND_FOUND TRUE) - set(_plugins "${_plugins} redlandbackend") - endif(EXISTS ${SOPRANO_PLUGIN_DIR}/redlandbackend.desktop) - - if(EXISTS ${SOPRANO_PLUGIN_DIR}/sesame2backend.desktop) - set(SOPRANO_PLUGIN_SESAME2BACKEND_FOUND TRUE) - set(_plugins "${_plugins} sesame2backend") - endif(EXISTS ${SOPRANO_PLUGIN_DIR}/sesame2backend.desktop) - - if(EXISTS ${SOPRANO_PLUGIN_DIR}/virtuosobackend.desktop) - set(SOPRANO_PLUGIN_VIRTUOSOBACKEND_FOUND TRUE) - set(_plugins "${_plugins} virtuosobackend") - endif(EXISTS ${SOPRANO_PLUGIN_DIR}/virtuosobackend.desktop) - - # make sure the Soprano cmake macros are found - # We also include it directly for convenience - find_file(_SOPRANO_MACRO_FILE NAMES SopranoAddOntology.cmake HINTS ${_SOPRANO_PREFIX}/share/soprano/cmake ) - if(_SOPRANO_MACRO_FILE) - # new Soprano > 2.3.0 location - include(${_SOPRANO_MACRO_FILE}) - set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${_SOPRANO_PREFIX}/share/soprano/cmake) - else(_SOPRANO_MACRO_FILE) - # the old Soprano 2.3.0 location - find_file(_SOPRANO_MACRO_FILE_OLD NAMES SopranoAddOntology.cmake HINTS ${_SOPRANO_PREFIX}/share/apps/cmake/modules ) - if(_SOPRANO_MACRO_FILE_OLD) - include(${_SOPRANO_MACRO_FILE_OLD}) - set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${_SOPRANO_PREFIX}/share/apps/cmake/modules) - endif(_SOPRANO_MACRO_FILE_OLD) - endif(_SOPRANO_MACRO_FILE) - -endif(SOPRANO_INCLUDE_DIR) - -include(FindPackageHandleStandardArgs) - -find_package_handle_standard_args(Soprano REQUIRED_VARS SOPRANO_INCLUDE_DIR SOPRANO_LIBRARIES - ${_SOPRANO_REQUIRED_COMPONENTS_RESULTS} - VERSION_VAR SOPRANO_VERSION) - -# for compatibility: -set(Soprano_FOUND ${SOPRANO_FOUND}) - -# check for all the libs as required to make sure that we do not try to compile with an old version - -if(SOPRANO_FOUND AND SOPRANO_INDEX_LIBRARIES) - set(SopranoIndex_FOUND TRUE) -endif(SOPRANO_FOUND AND SOPRANO_INDEX_LIBRARIES) - -if(SOPRANO_FOUND AND SOPRANO_CLIENT_LIBRARIES) - set(SopranoClient_FOUND TRUE) -endif(SOPRANO_FOUND AND SOPRANO_CLIENT_LIBRARIES) - -if(SOPRANO_FOUND AND SOPRANO_SERVER_LIBRARIES) - set(SopranoServer_FOUND TRUE) -endif(SOPRANO_FOUND AND SOPRANO_SERVER_LIBRARIES) - - - -mark_as_advanced(SOPRANO_CLIENT_LIBRARIES - SOPRANO_INDEX_LIBRARIES - SOPRANO_LIBRARIES - SOPRANO_SERVER_LIBRARIES - SOPRANO_INCLUDE_DIR - SOPRANO_PLUGIN_ROOT_DIR - _SOPRANO_MACRO_FILE - SOPRANO_ONTO2VOCABULARYCLASS_EXECUTABLE - SOPRANO_SOPRANOCMD_EXECUTABLE - ) - diff --git a/cmake/modules/NepomukAddOntologyClasses.cmake b/cmake/modules/NepomukAddOntologyClasses.cmake deleted file mode 100644 index a2bdd5bb..00000000 --- a/cmake/modules/NepomukAddOntologyClasses.cmake +++ /dev/null @@ -1,115 +0,0 @@ -# -# Use the Nepomuk resource class generator to generate convinient Resource subclasses -# from ontologies. -# -# Usage: -# NEPOMUK_ADD_ONTOLOGY_CLASSES( -# [FAST] -# [ONTOLOGIES] [ ...] -# [CLASSES [ ...]] -# [VISIBILITY ] -# ) -# -# If FAST is specified the rcgen parameter --fast will be used which results in resource classes -# not based on Nepomuk::Resource but on a custom class which does not perform any checks and simply -# writes the data to Nepomuk (hence the name fast). -# -# The optional CLASSES parameter allows to specify the classes to be generated (RDF URIs) in -# case one does not want all classes in the ontologies to be generated. -# -# The optional VISIBILITY parameter can only be used in non-fast mode and allows to set the gcc visibility -# to make the generated classes usable in a publically exported API. The is used to create -# the name of the export macro and the export include file. Thus, when using "VISIBILITY foobar" include -# file "foobar_export.h" needs to define FOOBAR_EXPORT. -# -# Copyright (c) 2009 Sebastian Trueg -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. -# -macro(NEPOMUK_ADD_ONTOLOGY_CLASSES _sources) - # extract arguments - set(_current_arg_type "onto") - foreach(_arg ${ARGN}) - if(${_arg} STREQUAL "ONTOLOGIES") - set(_current_arg_type "onto") - elseif(${_arg} STREQUAL "VISIBILITY") - set(_current_arg_type "visib") - elseif(${_arg} STREQUAL "CLASSES") - set(_current_arg_type "class") - elseif(${_arg} STREQUAL "FAST") - set(_fastmode "--fast") - else(${_arg} STREQUAL "ONTOLOGIES") - if(${_current_arg_type} STREQUAL "onto") - list(APPEND _ontologies ${_arg}) - get_filename_component(_filename ${_arg} NAME) - list(APPEND _ontofilenames ${_filename}) - elseif(${_current_arg_type} STREQUAL "class") - list(APPEND _classes "--class" "${_arg}") - else(${_current_arg_type} STREQUAL "onto") - set(_visibility "--visibility" "${_arg}") - endif(${_current_arg_type} STREQUAL "onto") - endif(${_arg} STREQUAL "ONTOLOGIES") - endforeach(_arg) - - # find our helper program (first in the install dir, then everywhere) - if(NOT WINCE) - find_program(RCGEN nepomuk-rcgen PATHS ${KDE4_BIN_INSTALL_DIR} ${BIN_INSTALL_DIR} NO_DEFAULT_PATH) - find_program(RCGEN nepomuk-rcgen) - else(NOT WINCE) - find_program(RCGEN nepomuk-rcgen PATHS ${HOST_BINDIR} NO_DEFAULT_PATH) - endif(NOT WINCE) - - if(NOT RCGEN) - message(SEND_ERROR "Failed to find the Nepomuk source generator" ) - else(NOT RCGEN) - file(TO_NATIVE_PATH ${RCGEN} RCGEN) - - # we generate the files in the current binary dir - set(_targetdir ${CMAKE_CURRENT_BINARY_DIR}) - - # generate the list of source and header files - execute_process( - COMMAND ${RCGEN} ${_fastmode} --listheaders --prefix ${_targetdir}/ ${_classes} ${_visibility} ${_ontologies} - OUTPUT_VARIABLE _out_headers - RESULT_VARIABLE rcgen_result - ) - if(NOT ${rcgen_result} EQUAL 0) - message(SEND_ERROR "Running ${RCGEN} to generate list of headers failed with error code ${rcgen_result}") - endif(NOT ${rcgen_result} EQUAL 0) - - execute_process( - COMMAND ${RCGEN} ${_fastmode} --listsources --prefix ${_targetdir}/ ${_classes} ${_visibility} ${_ontologies} - OUTPUT_VARIABLE _out_sources - RESULT_VARIABLE rcgen_result - ) - if(NOT ${rcgen_result} EQUAL 0) - message(SEND_ERROR "Running ${RCGEN} to generate list of sources failed with error code ${rcgen_result}") - endif(NOT ${rcgen_result} EQUAL 0) - - add_custom_command(OUTPUT ${_out_headers} ${_out_sources} - COMMAND ${RCGEN} ${_fastmode} --writeall --target ${_targetdir}/ ${_classes} ${_visibility} ${_ontologies} - DEPENDS ${_ontologies} - COMMENT "Generating ontology source files from ${_ontofilenames}" - ) - - # make sure the includes are found - include_directories(${_targetdir}) - - # finally append the source files to the source list - list(APPEND ${_sources} ${_out_sources}) - endif(NOT RCGEN) - - # reset variable names used - unset(_current_arg_type) - unset(_arg) - unset(_ontologies) - unset(_ontofilenames) - unset(_classes) - unset(_visibility) - unset(_fastmode) - unset(_targetdir) - unset(_out_headers) - unset(_out_sources) - unset(rcgen_result) -endmacro(NEPOMUK_ADD_ONTOLOGY_CLASSES) diff --git a/cmake/modules/NepomukMacros.cmake b/cmake/modules/NepomukMacros.cmake deleted file mode 100644 index 14acd2bb..00000000 --- a/cmake/modules/NepomukMacros.cmake +++ /dev/null @@ -1,67 +0,0 @@ -# This file contains the following macros: -# -# NEPOMUK_GENERATE_FROM_ONTOLOGY -# Parameters: -# ontofile - Path to the NRL ontology defining the resources to be generated. -# targetdir - Folder to which the generated sources should be written. -# out_headers - Variable which will be filled with the names of all generated headers. -# out_sources - Variable which will be filled with the names of all generated sources. -# out_includes - Variable which will be filled with complete include statements of all -# generated resource classes. -# -# In addition to the parameters an arbitrary number of template filenames can be set as arguments -# -# In case of success NEPOMUK_RESOURCES_GENERATED is true, otherwise false - -# (C) 2007 Sebastian Trueg - - -macro(NEPOMUK_GENERATE_FROM_ONTOLOGY ontofile targetdir out_headers out_sources out_includes) - - # init - set(NEPOMUK_RESOURCES_GENERATED false) - - find_program(RCGEN nepomuk-rcgen PATHS ${KDE4_BIN_INSTALL_DIR} ${BIN_INSTALL_DIR} NO_DEFAULT_PATH) - - if(NOT RCGEN) - - message(STATUS "Failed to find the Nepomuk source generator" ) - - else(NOT RCGEN) - - FILE(TO_NATIVE_PATH ${RCGEN} RCGEN) - - execute_process( - COMMAND ${RCGEN} --listheaders --prefix ${targetdir}/ --ontologies ${ontofile} - OUTPUT_VARIABLE ${out_headers} - RESULT_VARIABLE rcgen_result - ) - - # If the first call succeeds it is very very likely that the rest will, too - if(${rcgen_result} EQUAL 0) - - execute_process( - COMMAND ${RCGEN} --listsources --prefix ${targetdir}/ --ontologies ${ontofile} - OUTPUT_VARIABLE ${out_sources} - ) - - execute_process( - COMMAND ${RCGEN} --listincludes --ontologies ${ontofile} - OUTPUT_VARIABLE ${out_includes} - ) - - execute_process( - COMMAND ${RCGEN} --writeall --templates ${ARGN} --target ${targetdir}/ --ontologies ${ontofile} - ) - - set(NEPOMUK_RESOURCES_GENERATED true) - - else(${rcgen_result} EQUAL 0) - - message(STATUS "Failed to generate Nepomuk resource classes.") - - endif(${rcgen_result} EQUAL 0) - - endif(NOT RCGEN) - -endmacro(NEPOMUK_GENERATE_FROM_ONTOLOGY) diff --git a/config-nepomuk.h.cmake b/config-nepomuk.h.cmake deleted file mode 100644 index fe7364f6..00000000 --- a/config-nepomuk.h.cmake +++ /dev/null @@ -1 +0,0 @@ -#cmakedefine HAVE_NEPOMUK diff --git a/includes/CMakeLists.txt b/includes/CMakeLists.txt index fbf5a795..b70ff13d 100644 --- a/includes/CMakeLists.txt +++ b/includes/CMakeLists.txt @@ -917,77 +917,6 @@ install( FILES DESTINATION ${INCLUDE_INSTALL_DIR}/KDE/khtml COMPONENT Devel) -install(FILES - Nepomuk/File - Nepomuk/KRatingPainter - Nepomuk/KRatingWidget - Nepomuk/MassUpdateJob - Nepomuk/Resource - Nepomuk/ResourceManager - Nepomuk/Service - Nepomuk/Tag - Nepomuk/TagWidget - Nepomuk/Thing - Nepomuk/Variant -DESTINATION ${INCLUDE_INSTALL_DIR}/KDE/Nepomuk COMPONENT Devel) - - -install(FILES - Nepomuk/Types/Class - Nepomuk/Types/Literal - Nepomuk/Types/Ontology - Nepomuk/Types/Property -DESTINATION ${INCLUDE_INSTALL_DIR}/KDE/Nepomuk/Types COMPONENT Devel) - - -install(FILES - Nepomuk/Query/AndTerm - Nepomuk/Query/ComparisonTerm - Nepomuk/Query/FileQuery - Nepomuk/Query/GroupTerm - Nepomuk/Query/LiteralTerm - Nepomuk/Query/NegationTerm - Nepomuk/Query/OptionalTerm - Nepomuk/Query/OrTerm - Nepomuk/Query/Query - Nepomuk/Query/QueryParser - Nepomuk/Query/QueryServiceClient - Nepomuk/Query/ResourceTerm - Nepomuk/Query/ResourceTypeTerm - Nepomuk/Query/Result - Nepomuk/Query/SimpleTerm - Nepomuk/Query/StandardQuery - Nepomuk/Query/Term -DESTINATION ${INCLUDE_INSTALL_DIR}/KDE/Nepomuk/Query COMPONENT Devel) - - -install(FILES - Nepomuk/Utils/DynamicResourceFacet - Nepomuk/Utils/Facet - Nepomuk/Utils/FacetWidget - Nepomuk/Utils/ProxyFacet - Nepomuk/Utils/ResourceModel - Nepomuk/Utils/SearchWidget - Nepomuk/Utils/SimpleFacet - Nepomuk/Utils/SimpleResourceModel -DESTINATION ${INCLUDE_INSTALL_DIR}/KDE/Nepomuk/Utils COMPONENT Devel) - - -install(FILES - Nepomuk/Vocabulary/NCAL - Nepomuk/Vocabulary/NCO - Nepomuk/Vocabulary/NDO - Nepomuk/Vocabulary/NEXIF - Nepomuk/Vocabulary/NFO - Nepomuk/Vocabulary/NIE - Nepomuk/Vocabulary/NMM - Nepomuk/Vocabulary/NMO - Nepomuk/Vocabulary/NUAO - Nepomuk/Vocabulary/PIMO - Nepomuk/Vocabulary/TMO -DESTINATION ${INCLUDE_INSTALL_DIR}/KDE/Nepomuk/Vocabulary COMPONENT Devel) - - install(FILES Plasma/AbstractDialogManager Plasma/AbstractRunner diff --git a/includes/Nepomuk/File b/includes/Nepomuk/File deleted file mode 100644 index c99bd8f6..00000000 --- a/includes/Nepomuk/File +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/file.h" diff --git a/includes/Nepomuk/KRatingPainter b/includes/Nepomuk/KRatingPainter deleted file mode 100644 index 300dd7d5..00000000 --- a/includes/Nepomuk/KRatingPainter +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/kratingpainter.h" diff --git a/includes/Nepomuk/KRatingWidget b/includes/Nepomuk/KRatingWidget deleted file mode 100644 index c76b4ea8..00000000 --- a/includes/Nepomuk/KRatingWidget +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/kratingwidget.h" diff --git a/includes/Nepomuk/MassUpdateJob b/includes/Nepomuk/MassUpdateJob deleted file mode 100644 index 5ffd21a0..00000000 --- a/includes/Nepomuk/MassUpdateJob +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/nepomukmassupdatejob.h" diff --git a/includes/Nepomuk/Query/AndTerm b/includes/Nepomuk/Query/AndTerm deleted file mode 100644 index ced21a8f..00000000 --- a/includes/Nepomuk/Query/AndTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/andterm.h" diff --git a/includes/Nepomuk/Query/ComparisonTerm b/includes/Nepomuk/Query/ComparisonTerm deleted file mode 100644 index 632b150b..00000000 --- a/includes/Nepomuk/Query/ComparisonTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/comparisonterm.h" diff --git a/includes/Nepomuk/Query/FileQuery b/includes/Nepomuk/Query/FileQuery deleted file mode 100644 index fbdd163d..00000000 --- a/includes/Nepomuk/Query/FileQuery +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/filequery.h" diff --git a/includes/Nepomuk/Query/GroupTerm b/includes/Nepomuk/Query/GroupTerm deleted file mode 100644 index 08461d34..00000000 --- a/includes/Nepomuk/Query/GroupTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/groupterm.h" diff --git a/includes/Nepomuk/Query/LiteralTerm b/includes/Nepomuk/Query/LiteralTerm deleted file mode 100644 index 3b1984e4..00000000 --- a/includes/Nepomuk/Query/LiteralTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/literalterm.h" diff --git a/includes/Nepomuk/Query/NegationTerm b/includes/Nepomuk/Query/NegationTerm deleted file mode 100644 index 02635c94..00000000 --- a/includes/Nepomuk/Query/NegationTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/negationterm.h" diff --git a/includes/Nepomuk/Query/OptionalTerm b/includes/Nepomuk/Query/OptionalTerm deleted file mode 100644 index 31b3e522..00000000 --- a/includes/Nepomuk/Query/OptionalTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/optionalterm.h" diff --git a/includes/Nepomuk/Query/OrTerm b/includes/Nepomuk/Query/OrTerm deleted file mode 100644 index b11a584c..00000000 --- a/includes/Nepomuk/Query/OrTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/orterm.h" diff --git a/includes/Nepomuk/Query/Query b/includes/Nepomuk/Query/Query deleted file mode 100644 index 1c7ce9d8..00000000 --- a/includes/Nepomuk/Query/Query +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/query.h" diff --git a/includes/Nepomuk/Query/QueryParser b/includes/Nepomuk/Query/QueryParser deleted file mode 100644 index ca40e840..00000000 --- a/includes/Nepomuk/Query/QueryParser +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/queryparser.h" diff --git a/includes/Nepomuk/Query/QueryServiceClient b/includes/Nepomuk/Query/QueryServiceClient deleted file mode 100644 index 2a2c7827..00000000 --- a/includes/Nepomuk/Query/QueryServiceClient +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/queryserviceclient.h" diff --git a/includes/Nepomuk/Query/ResourceTerm b/includes/Nepomuk/Query/ResourceTerm deleted file mode 100644 index 97c72ef2..00000000 --- a/includes/Nepomuk/Query/ResourceTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/resourceterm.h" diff --git a/includes/Nepomuk/Query/ResourceTypeTerm b/includes/Nepomuk/Query/ResourceTypeTerm deleted file mode 100644 index f542adf3..00000000 --- a/includes/Nepomuk/Query/ResourceTypeTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/resourcetypeterm.h" diff --git a/includes/Nepomuk/Query/Result b/includes/Nepomuk/Query/Result deleted file mode 100644 index 91fe55d2..00000000 --- a/includes/Nepomuk/Query/Result +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/result.h" diff --git a/includes/Nepomuk/Query/SimpleTerm b/includes/Nepomuk/Query/SimpleTerm deleted file mode 100644 index 1799e611..00000000 --- a/includes/Nepomuk/Query/SimpleTerm +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/simpleterm.h" diff --git a/includes/Nepomuk/Query/StandardQuery b/includes/Nepomuk/Query/StandardQuery deleted file mode 100644 index 9146f416..00000000 --- a/includes/Nepomuk/Query/StandardQuery +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/standardqueries.h" diff --git a/includes/Nepomuk/Query/Term b/includes/Nepomuk/Query/Term deleted file mode 100644 index 89089d8f..00000000 --- a/includes/Nepomuk/Query/Term +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/term.h" diff --git a/includes/Nepomuk/Resource b/includes/Nepomuk/Resource deleted file mode 100644 index c10defc6..00000000 --- a/includes/Nepomuk/Resource +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/resource.h" diff --git a/includes/Nepomuk/ResourceManager b/includes/Nepomuk/ResourceManager deleted file mode 100644 index 5722e3cb..00000000 --- a/includes/Nepomuk/ResourceManager +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/resourcemanager.h" diff --git a/includes/Nepomuk/Service b/includes/Nepomuk/Service deleted file mode 100644 index 89aa47cb..00000000 --- a/includes/Nepomuk/Service +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/nepomukservice.h" diff --git a/includes/Nepomuk/Tag b/includes/Nepomuk/Tag deleted file mode 100644 index fe3186d1..00000000 --- a/includes/Nepomuk/Tag +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/tag.h" diff --git a/includes/Nepomuk/TagWidget b/includes/Nepomuk/TagWidget deleted file mode 100644 index 8214a2de..00000000 --- a/includes/Nepomuk/TagWidget +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/tagwidget.h" diff --git a/includes/Nepomuk/Thing b/includes/Nepomuk/Thing deleted file mode 100644 index 4c8715f3..00000000 --- a/includes/Nepomuk/Thing +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/thing.h" diff --git a/includes/Nepomuk/Types/Class b/includes/Nepomuk/Types/Class deleted file mode 100644 index 87a6c560..00000000 --- a/includes/Nepomuk/Types/Class +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/class.h" diff --git a/includes/Nepomuk/Types/Literal b/includes/Nepomuk/Types/Literal deleted file mode 100644 index c4681abb..00000000 --- a/includes/Nepomuk/Types/Literal +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/literal.h" diff --git a/includes/Nepomuk/Types/Ontology b/includes/Nepomuk/Types/Ontology deleted file mode 100644 index dab1173b..00000000 --- a/includes/Nepomuk/Types/Ontology +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/ontology.h" diff --git a/includes/Nepomuk/Types/Property b/includes/Nepomuk/Types/Property deleted file mode 100644 index cd26830b..00000000 --- a/includes/Nepomuk/Types/Property +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/property.h" diff --git a/includes/Nepomuk/Utils/DynamicResourceFacet b/includes/Nepomuk/Utils/DynamicResourceFacet deleted file mode 100644 index 4e99e2a1..00000000 --- a/includes/Nepomuk/Utils/DynamicResourceFacet +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/dynamicresourcefacet.h" diff --git a/includes/Nepomuk/Utils/Facet b/includes/Nepomuk/Utils/Facet deleted file mode 100644 index bb64034a..00000000 --- a/includes/Nepomuk/Utils/Facet +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/facet.h" diff --git a/includes/Nepomuk/Utils/FacetWidget b/includes/Nepomuk/Utils/FacetWidget deleted file mode 100644 index d3b7b525..00000000 --- a/includes/Nepomuk/Utils/FacetWidget +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/facetwidget.h" diff --git a/includes/Nepomuk/Utils/ProxyFacet b/includes/Nepomuk/Utils/ProxyFacet deleted file mode 100644 index f14d88c1..00000000 --- a/includes/Nepomuk/Utils/ProxyFacet +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/proxyfacet.h" diff --git a/includes/Nepomuk/Utils/ResourceModel b/includes/Nepomuk/Utils/ResourceModel deleted file mode 100644 index 77a85d00..00000000 --- a/includes/Nepomuk/Utils/ResourceModel +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/resourcemodel.h" diff --git a/includes/Nepomuk/Utils/SearchWidget b/includes/Nepomuk/Utils/SearchWidget deleted file mode 100644 index e9ee5c1f..00000000 --- a/includes/Nepomuk/Utils/SearchWidget +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/searchwidget.h" diff --git a/includes/Nepomuk/Utils/SimpleFacet b/includes/Nepomuk/Utils/SimpleFacet deleted file mode 100644 index 789ccd54..00000000 --- a/includes/Nepomuk/Utils/SimpleFacet +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/simplefacet.h" diff --git a/includes/Nepomuk/Utils/SimpleResourceModel b/includes/Nepomuk/Utils/SimpleResourceModel deleted file mode 100644 index 442b0c37..00000000 --- a/includes/Nepomuk/Utils/SimpleResourceModel +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/simpleresourcemodel.h" diff --git a/includes/Nepomuk/Variant b/includes/Nepomuk/Variant deleted file mode 100644 index a5c3adf2..00000000 --- a/includes/Nepomuk/Variant +++ /dev/null @@ -1 +0,0 @@ -#include "../../nepomuk/variant.h" diff --git a/includes/Nepomuk/Vocabulary/NCAL b/includes/Nepomuk/Vocabulary/NCAL deleted file mode 100644 index 73ab8811..00000000 --- a/includes/Nepomuk/Vocabulary/NCAL +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/ncal.h" diff --git a/includes/Nepomuk/Vocabulary/NCO b/includes/Nepomuk/Vocabulary/NCO deleted file mode 100644 index 83982bd5..00000000 --- a/includes/Nepomuk/Vocabulary/NCO +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/nco.h" diff --git a/includes/Nepomuk/Vocabulary/NDO b/includes/Nepomuk/Vocabulary/NDO deleted file mode 100644 index 33252a20..00000000 --- a/includes/Nepomuk/Vocabulary/NDO +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/ndo.h" diff --git a/includes/Nepomuk/Vocabulary/NEXIF b/includes/Nepomuk/Vocabulary/NEXIF deleted file mode 100644 index 6ccff090..00000000 --- a/includes/Nepomuk/Vocabulary/NEXIF +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/nexif.h" diff --git a/includes/Nepomuk/Vocabulary/NFO b/includes/Nepomuk/Vocabulary/NFO deleted file mode 100644 index fbe79495..00000000 --- a/includes/Nepomuk/Vocabulary/NFO +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/nfo.h" diff --git a/includes/Nepomuk/Vocabulary/NIE b/includes/Nepomuk/Vocabulary/NIE deleted file mode 100644 index 30913233..00000000 --- a/includes/Nepomuk/Vocabulary/NIE +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/nie.h" diff --git a/includes/Nepomuk/Vocabulary/NMM b/includes/Nepomuk/Vocabulary/NMM deleted file mode 100644 index 43674057..00000000 --- a/includes/Nepomuk/Vocabulary/NMM +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/nmm.h" diff --git a/includes/Nepomuk/Vocabulary/NMO b/includes/Nepomuk/Vocabulary/NMO deleted file mode 100644 index d80eb6f7..00000000 --- a/includes/Nepomuk/Vocabulary/NMO +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/nmo.h" diff --git a/includes/Nepomuk/Vocabulary/NUAO b/includes/Nepomuk/Vocabulary/NUAO deleted file mode 100644 index 30dd11b2..00000000 --- a/includes/Nepomuk/Vocabulary/NUAO +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/nuao.h" diff --git a/includes/Nepomuk/Vocabulary/PIMO b/includes/Nepomuk/Vocabulary/PIMO deleted file mode 100644 index b7334a82..00000000 --- a/includes/Nepomuk/Vocabulary/PIMO +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/pimo.h" diff --git a/includes/Nepomuk/Vocabulary/TMO b/includes/Nepomuk/Vocabulary/TMO deleted file mode 100644 index ca663f78..00000000 --- a/includes/Nepomuk/Vocabulary/TMO +++ /dev/null @@ -1 +0,0 @@ -#include "../../../nepomuk/tmo.h" diff --git a/kdecore/io/kdebug.h b/kdecore/io/kdebug.h index ccb3a2a8..1389ad97 100644 --- a/kdecore/io/kdebug.h +++ b/kdecore/io/kdebug.h @@ -219,7 +219,6 @@ class QObject; KDECORE_EXPORT QDebug operator<<(QDebug s, const KUrl &url); KDECORE_EXPORT QDebug operator<<(QDebug s, const KDateTime &time); -#if 1 || defined(KDE3_SUPPORT) #ifndef KDE_NO_DEPRECATED class KDE_DEPRECATED kndbgstream { }; typedef QDebug kdbgstream; @@ -232,7 +231,6 @@ inline KDE_DEPRECATED QString kdBacktrace(int levels=-1) { return kBacktrace( le static inline KDE_DEPRECATED QDebug kndDebug() { return kDebugDevNull(); } #endif -#endif class WrongSyntax {}; diff --git a/kfile/CMakeLists.txt b/kfile/CMakeLists.txt index ceae140c..c3750cf9 100644 --- a/kfile/CMakeLists.txt +++ b/kfile/CMakeLists.txt @@ -5,9 +5,6 @@ include_directories( ${CMAKE_SOURCE_DIR}/solid ${CMAKE_BINARY_DIR}/solid ) -if(Soprano_FOUND) -include_directories(${SOPRANO_INCLUDE_DIR}) -endif(Soprano_FOUND) add_subdirectory(tests) diff --git a/kio/CMakeLists.txt b/kio/CMakeLists.txt index 2bb60d68..44b1b078 100644 --- a/kio/CMakeLists.txt +++ b/kio/CMakeLists.txt @@ -2,37 +2,17 @@ project(kio) if(KDE_PLATFORM_FEATURE_BINARY_INCOMPATIBLE_FEATURE_REDUCTION) set(KIO_NO_SOLID TRUE) - set(KIO_NO_NEPOMUK TRUE) endif(KDE_PLATFORM_FEATURE_BINARY_INCOMPATIBLE_FEATURE_REDUCTION) -if(NOT HAVE_NEPOMUK) - set(KIO_NO_NEPOMUK TRUE) -endif(NOT HAVE_NEPOMUK) - if(NOT STRIGI_FOUND) set(KIO_NO_STRIGI TRUE) endif(NOT STRIGI_FOUND) -if(NOT SOPRANO_FOUND) - set(KIO_NO_SOPRANO TRUE) -endif(NOT SOPRANO_FOUND) - if(OPENSSL_FOUND) set(KSSL_HAVE_SSL 1) include_directories(${OPENSSL_INCLUDE_DIR}) endif(OPENSSL_FOUND) -if(NOT KIO_NO_NEPOMUK) - include_directories( - ${SOPRANO_INCLUDE_DIR} - ${CMAKE_SOURCE_DIR}/nepomuk/ - ${CMAKE_SOURCE_DIR}/nepomuk/core/ - ${CMAKE_SOURCE_DIR}/nepomuk/types/ - ${CMAKE_SOURCE_DIR}/nepomuk/ui/ - ${CMAKE_SOURCE_DIR}/nepomuk/query/ - ) -endif(NOT KIO_NO_NEPOMUK) - # This applies to all subdirs; let's put kio's dependencies (and own dirs) here, once and for all include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/bookmarks @@ -53,10 +33,6 @@ if (NOT KIO_NO_STRIGI) set(KIO_EXTRA_LIBS ${KIO_EXTRA_LIBS} ${STRIGI_STREAMANALYZER_LIBRARY} ${STRIGI_STREAMS_LIBRARY}) endif() -if (NOT KIO_NO_SOPRANO) - include_directories(${SOPRANO_INCLUDE_DIR}) -endif (NOT KIO_NO_SOPRANO) - if(NOT KIO_NO_SOLID) include_directories(${CMAKE_BINARY_DIR}/solid/) include_directories(${CMAKE_SOURCE_DIR}/solid/) @@ -250,15 +226,6 @@ if(NOT KIO_NO_SOLID) ) endif(NOT KIO_NO_SOLID) -if(NOT KIO_NO_NEPOMUK) - set(kfile_STAT_SRCS - ${kfile_STAT_SRCS} - kfile/kcommentwidget.cpp - kfile/kfilemetadatareader.cpp - kfile/kfilemetadataprovider.cpp - ) -endif(NOT KIO_NO_NEPOMUK) - if(NOT WIN32) set(kfile_STAT_SRCS ${kfile_STAT_SRCS} @@ -305,12 +272,6 @@ set(kio_LIB_PRIVATE_SRCS kio/slaveinterface_p.h ) -if(NOT KIO_NO_NEPOMUK) - set(kfilemetadatareaderprocess_SRCS - kfile/kfilemetadatareaderprocess.cpp - ) -endif(NOT KIO_NO_NEPOMUK) - kde4_add_ui_files(kio_LIB_SRCS kfile/kpropertiesdesktopadvbase.ui kfile/kpropertiesdesktopbase.ui @@ -326,11 +287,6 @@ install(FILES kssl/ksslcertificatemanager.upd kde4_add_library(kio ${LIBRARY_TYPE} ${kio_LIB_SRCS}) -if(NOT KIO_NO_NEPOMUK) - kde4_add_executable(kfilemetadatareader ${kfilemetadatareaderprocess_SRCS}) - target_link_libraries(kfilemetadatareader ${KDE4_KIO_LIBS} ${KDE4_NEPOMUK_LIBRARY} nepomukutils) - target_link_libraries(kio ${KDE4_NEPOMUK_LIBRARY} nepomukquery nepomukutils) -endif(NOT KIO_NO_NEPOMUK) target_link_libraries(kio ${KDE4_KDEUI_LIBS} ${ZLIB_LIBRARY} ${QT_QTNETWORK_LIBRARY} ${QT_QTXML_LIBRARY} ${QT_QTSVG_LIBRARY} ${X11_LIBRARIES} ${KIO_EXTRA_LIBS}) target_link_libraries(kio LINK_INTERFACE_LIBRARIES kdeui kdecore ${QT_QTNETWORK_LIBRARY} ${QT_QTXML_LIBRARY} ${QT_QTGUI_LIBRARY} ) @@ -349,9 +305,6 @@ set_target_properties(kio PROPERTIES VERSION ${KDE_NON_GENERIC_LIB_VERSION} ########### install files ############### install(TARGETS kio EXPORT kdelibsLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS}) -if(NOT KIO_NO_NEPOMUK) - install(TARGETS kfilemetadatareader ${INSTALL_TARGETS_DEFAULT_ARGS}) -endif(NOT KIO_NO_NEPOMUK) install( PROGRAMS useragent.pl proxytype.pl DESTINATION ${KCONF_UPDATE_INSTALL_DIR} ) diff --git a/kio/kfile/kcommentwidget.cpp b/kio/kfile/kcommentwidget.cpp deleted file mode 100644 index d36a8d61..00000000 --- a/kio/kfile/kcommentwidget.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/***************************************************************************** - * Copyright (C) 2008 by Sebastian Trueg * - * Copyright (C) 2009 by Peter Penz * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public License * - * along with this library; see the file COPYING.LIB. If not, write to * - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * - * Boston, MA 02110-1301, USA. * - *****************************************************************************/ - -#include "kcommentwidget_p.h" - -#include -#include - -#include -#include -#include -#include -#include - -KCommentWidget::KCommentWidget(QWidget* parent) : - QWidget(parent), - m_readOnly(false), - m_label(0), - m_sizeHintHelper(0), - m_comment() -{ - m_label = new QLabel(this); - m_label->setWordWrap(true); - m_label->setAlignment(Qt::AlignTop); - connect(m_label, SIGNAL(linkActivated(QString)), this, SLOT(slotLinkActivated(QString))); - - m_sizeHintHelper = new QLabel(this); - m_sizeHintHelper->hide(); - - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setMargin(0); - layout->addWidget(m_label); - - setText(m_comment); -} - -KCommentWidget::~KCommentWidget() -{ -} - -void KCommentWidget::setText(const QString& comment) -{ - QString text; - if (comment.isEmpty()) { - if (m_readOnly) { - text = "-"; - } else { - text = "" + i18nc("@label", "Add Comment...") + ""; - } - } else { - if (m_readOnly) { - text = Qt::escape(comment); - } else { - text = "

" + Qt::escape(comment) + " " + i18nc("@label", "Change...") + "

"; - } - } - - m_label->setText(text); - m_sizeHintHelper->setText(text); - m_comment = comment; -} - -QString KCommentWidget::text() const -{ - return m_comment; -} - -void KCommentWidget::setReadOnly(bool readOnly) -{ - m_readOnly = readOnly; - setText(m_comment); -} - -bool KCommentWidget::isReadOnly() const -{ - return m_readOnly; -} - -QSize KCommentWidget::sizeHint() const -{ - // Per default QLabel tries to provide a square size hint. This - // does not work well for complex layouts that rely on a heightForWidth() - // functionality with unclipped content. Use an unwrapped text label - // as layout helper instead, that returns the preferred size of - // the rich-text line. - return m_sizeHintHelper->sizeHint(); -} - -bool KCommentWidget::event(QEvent* event) -{ - if (event->type() == QEvent::Polish) { - m_label->setForegroundRole(foregroundRole()); - } - return QWidget::event(event); -} - -void KCommentWidget::slotLinkActivated(const QString& link) -{ - QPointer dialog = new KDialog(this); - - QTextEdit* editor = new QTextEdit(dialog); - editor->setText(m_comment); - - dialog->setMainWidget(editor); - - const QString caption = (link == "changeComment") ? - i18nc("@title:window", "Change Comment") : - i18nc("@title:window", "Add Comment"); - dialog->setCaption(caption); - dialog->setButtons(KDialog::Ok | KDialog::Cancel); - dialog->setDefaultButton(KDialog::Ok); - - KConfigGroup dialogConfig(KGlobal::config(), "Nepomuk KEditCommentDialog"); - dialog->restoreDialogSize(dialogConfig); - - if (dialog->exec() == QDialog::Accepted) { - const QString oldText = m_comment; - if (dialog != 0) { - setText(editor->toPlainText()); - } - if (oldText != m_comment) { - emit commentChanged(m_comment); - } - } - - if (dialog != 0) { - dialog->saveDialogSize(dialogConfig); - delete dialog; - dialog = 0; - } -} - -#include "kcommentwidget_p.moc" diff --git a/kio/kfile/kcommentwidget_p.h b/kio/kfile/kcommentwidget_p.h deleted file mode 100644 index 95488ea0..00000000 --- a/kio/kfile/kcommentwidget_p.h +++ /dev/null @@ -1,69 +0,0 @@ -/***************************************************************************** - * Copyright (C) 2008 by Sebastian Trueg * - * Copyright (C) 2009 by Peter Penz * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public License * - * along with this library; see the file COPYING.LIB. If not, write to * - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * - * Boston, MA 02110-1301, USA. * - *****************************************************************************/ - -#ifndef KCOMMENT_WIDGET -#define KCOMMENT_WIDGET - -#include -#include - -class QLabel; - -/** - * @brief Allows to edit and show a comment as part of KMetaDataWidget. - */ -class KCommentWidget : public QWidget -{ - Q_OBJECT - -public: - explicit KCommentWidget(QWidget* parent = 0); - virtual ~KCommentWidget(); - - void setText(const QString& comment); - QString text() const; - - /** - * If set to true, the comment cannot be changed by the user. - * Per default read-only is disabled. - */ - // TODO: provide common interface class for metadatawidgets - void setReadOnly(bool readOnly); - bool isReadOnly() const; - - virtual QSize sizeHint() const; - -signals: - void commentChanged(const QString& comment); - -protected: - virtual bool event(QEvent* event); - -private slots: - void slotLinkActivated(const QString& link); - -private: - bool m_readOnly; - QLabel* m_label; - QLabel* m_sizeHintHelper; // see comment in KCommentWidget::sizeHint() - QString m_comment; -}; - -#endif diff --git a/kio/kfile/kfilemetadataconfigurationwidget.cpp b/kio/kfile/kfilemetadataconfigurationwidget.cpp index c7d07408..72569f28 100644 --- a/kio/kfile/kfilemetadataconfigurationwidget.cpp +++ b/kio/kfile/kfilemetadataconfigurationwidget.cpp @@ -27,15 +27,6 @@ #include #include -#ifndef KIO_NO_NEPOMUK - #define DISABLE_NEPOMUK_LEGACY - #include - #include - #include - #include - - #include "kfilemetadataprovider_p.h" -#endif #include #include @@ -60,9 +51,6 @@ public: int m_visibleDataTypes; KFileItemList m_fileItems; -#ifndef KIO_NO_NEPOMUK - KFileMetaDataProvider* m_provider; -#endif QListWidget* m_metaDataList; private: @@ -72,9 +60,6 @@ private: KFileMetaDataConfigurationWidget::Private::Private(KFileMetaDataConfigurationWidget* parent) : m_visibleDataTypes(0), m_fileItems(), -#ifndef KIO_NO_NEPOMUK - m_provider(0), -#endif m_metaDataList(0), q(parent) { @@ -85,9 +70,6 @@ KFileMetaDataConfigurationWidget::Private::Private(KFileMetaDataConfigurationWid QVBoxLayout* layout = new QVBoxLayout(q); layout->addWidget(m_metaDataList); -#ifndef KIO_NO_NEPOMUK - m_provider = new KFileMetaDataProvider(q); -#endif } KFileMetaDataConfigurationWidget::Private::~Private() @@ -96,11 +78,6 @@ KFileMetaDataConfigurationWidget::Private::~Private() void KFileMetaDataConfigurationWidget::Private::loadMetaData() { -#ifndef KIO_NO_NEPOMUK - m_provider->setItems(m_fileItems); - connect(m_provider, SIGNAL(loadingFinished()), - q, SLOT(slotLoadingFinished())); -#endif } void KFileMetaDataConfigurationWidget::Private::addItem(const KUrl& uri) @@ -133,13 +110,7 @@ void KFileMetaDataConfigurationWidget::Private::addItem(const KUrl& uri) KConfig config("kmetainformationrc", KConfig::NoGlobals); KConfigGroup settings = config.group("Show"); -#ifndef KIO_NO_NEPOMUK - const QString label = (m_provider == 0) - ? KNfoTranslator::instance().translation(uri) - : m_provider->label(uri); -#else const QString label = KNfoTranslator::instance().translation(uri); -#endif QListWidgetItem* item = new QListWidgetItem(label, m_metaDataList); item->setData(Qt::UserRole, key); @@ -149,18 +120,6 @@ void KFileMetaDataConfigurationWidget::Private::addItem(const KUrl& uri) void KFileMetaDataConfigurationWidget::Private::slotLoadingFinished() { -#ifndef KIO_NO_NEPOMUK - // Get all meta information labels that are available for - // the currently shown file item and add them to the list. - Q_ASSERT(m_provider != 0); - - const QHash data = m_provider->data(); - QHash::const_iterator it = data.constBegin(); - while (it != data.constEnd()) { - addItem(it.key()); - ++it; - } -#endif } KFileMetaDataConfigurationWidget::KFileMetaDataConfigurationWidget(QWidget* parent) : diff --git a/kio/kfile/kfilemetadataprovider.cpp b/kio/kfile/kfilemetadataprovider.cpp deleted file mode 100644 index 66d4ba6b..00000000 --- a/kio/kfile/kfilemetadataprovider.cpp +++ /dev/null @@ -1,559 +0,0 @@ -/***************************************************************************** - * Copyright (C) 2010 by Peter Penz * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public License * - * along with this library; see the file COPYING.LIB. If not, write to * - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * - * Boston, MA 02110-1301, USA. * - *****************************************************************************/ - -#include "kfilemetadataprovider_p.h" - -#include -#include -#include "knfotranslator_p.h" -#include -#include -#include - -#ifndef KIO_NO_NEPOMUK - #define DISABLE_NEPOMUK_LEGACY - #include "nepomukmassupdatejob.h" - #include "tagwidget.h" - #include "tag.h" - #include "kratingwidget.h" - #include "resource.h" - #include "resourcemanager.h" - - #include "kcommentwidget_p.h" -#else - namespace Nepomuk - { - typedef int Tag; - } -#endif - -#include -#include - -// Required includes for subDirectoriesCount(): -#ifdef Q_WS_WIN - #include -#else - #include - #include -#endif - -namespace { - static QString plainText(const QString& richText) - { - QString plainText; - plainText.reserve(richText.length()); - - bool skip = false; - for (int i = 0; i < richText.length(); ++i) { - const QChar c = richText.at(i); - if (c == QLatin1Char('<')) { - skip = true; - } else if (c == QLatin1Char('>')) { - skip = false; - } else if (!skip) { - plainText.append(c); - } - } - - return plainText; - } -} - -// The default size hint of QLabel tries to return a square size. -// This does not work well in combination with layouts that use -// heightForWidth(): In this case it is possible that the content -// of a label might get clipped. By specifying a size hint -// with a maximum width that is necessary to contain the whole text, -// using heightForWidth() assures having a non-clipped text. -class ValueWidget : public QLabel -{ -public: - explicit ValueWidget(QWidget* parent = 0); - virtual QSize sizeHint() const; -}; - -ValueWidget::ValueWidget(QWidget* parent) : - QLabel(parent) -{ -} - -QSize ValueWidget::sizeHint() const -{ - QFontMetrics metrics(font()); - // TODO: QLabel internally provides already a method sizeForWidth(), - // that would be sufficient. However this method is not accessible, so - // as workaround the tags from a richtext are removed manually here to - // have a proper size hint. - return metrics.size(Qt::TextSingleLine, plainText(text())); -} - - - -class KFileMetaDataProvider::Private -{ - -public: - Private(KFileMetaDataProvider* parent); - ~Private(); - - void slotLoadingFinished(); - - void slotRatingChanged(unsigned int rating); - void slotTagsChanged(const QList& tags); - void slotCommentChanged(const QString& comment); - - void slotMetaDataUpdateDone(); - void slotTagClicked(const Nepomuk::Tag& tag); - void slotLinkActivated(const QString& link); - - /** - * Disables the metadata widget and starts the job that - * changes the meta data asynchronously. After the job - * has been finished, the metadata widget gets enabled again. - */ - void startChangeDataJob(KJob* job); - -#ifndef KIO_NO_NEPOMUK - QList resourceList() const; - QWidget* createRatingWidget(int rating, QWidget* parent); - QWidget* createTagWidget(const QList& tags, QWidget* parent); - QWidget* createCommentWidget(const QString& comment, QWidget* parent); -#endif - QWidget* createValueWidget(const QString& value, QWidget* parent); - - /* - * @return The number of subdirectories for the directory \a path. - */ - static int subDirectoriesCount(const QString &path); - - bool m_readOnly; - bool m_nepomukActivated; - QList m_fileItems; - -#ifndef KIO_NO_NEPOMUK - QHash m_data; - - QList m_metaDataReaders; - KFileMetaDataReader* m_latestMetaDataReader; - - QWeakPointer m_ratingWidget; - QWeakPointer m_tagWidget; - QWeakPointer m_commentWidget; -#endif - -private: - KFileMetaDataProvider* const q; -}; - -KFileMetaDataProvider::Private::Private(KFileMetaDataProvider* parent) : - m_readOnly(false), - m_nepomukActivated(false), - m_fileItems(), -#ifndef KIO_NO_NEPOMUK - m_data(), - m_metaDataReaders(), - m_latestMetaDataReader(0), - m_ratingWidget(), - m_tagWidget(), - m_commentWidget(), -#endif - q(parent) -{ -#ifndef KIO_NO_NEPOMUK - m_nepomukActivated = Nepomuk::ResourceManager::instance()->initialized(); -#endif -} - -KFileMetaDataProvider::Private::~Private() -{ -#ifndef KIO_NO_NEPOMUK - qDeleteAll(m_metaDataReaders); -#endif -} - -void KFileMetaDataProvider::Private::slotLoadingFinished() -{ -#ifndef KIO_NO_NEPOMUK - KFileMetaDataReader* finishedMetaDataReader = qobject_cast(q->sender()); - // The process that has emitted the finished() signal - // will get deleted and removed from m_metaDataReaders. - for (int i = 0; i < m_metaDataReaders.count(); ++i) { - KFileMetaDataReader* metaDataReader = m_metaDataReaders[i]; - if (metaDataReader == finishedMetaDataReader) { - m_metaDataReaders.removeAt(i); - if (metaDataReader != m_latestMetaDataReader) { - // Ignore data of older processs, as the data got - // obsolete by m_latestMetaDataReader. - metaDataReader->deleteLater(); - return; - } - } - } - - m_data = m_latestMetaDataReader->metaData(); - m_latestMetaDataReader->deleteLater(); - - if (m_fileItems.count() == 1) { - // TODO: Handle case if remote URLs are used properly. isDir() does - // not work, the modification date needs also to be adjusted... - const KFileItem& item = m_fileItems.first(); - - if (item.isDir()) { - const int count = subDirectoriesCount(item.url().pathOrUrl()); - if (count == -1) { - m_data.insert(KUrl("kfileitem#size"), QString("Unknown")); - } else { - const QString itemCountString = i18ncp("@item:intable", "%1 item", "%1 items", count); - m_data.insert(KUrl("kfileitem#size"), itemCountString); - } - } else { - m_data.insert(KUrl("kfileitem#size"), KIO::convertSize(item.size())); - } - m_data.insert(KUrl("kfileitem#type"), item.mimeComment()); - m_data.insert(KUrl("kfileitem#modified"), KGlobal::locale()->formatDateTime(item.time(KFileItem::ModificationTime), KLocale::FancyLongDate)); - m_data.insert(KUrl("kfileitem#owner"), item.user()); - m_data.insert(KUrl("kfileitem#permissions"), item.permissionsString()); - } else if (m_fileItems.count() > 1) { - // Calculate the size of all items - quint64 totalSize = 0; - foreach (const KFileItem& item, m_fileItems) { - if (!item.isDir() && !item.isLink()) { - totalSize += item.size(); - } - } - m_data.insert(KUrl("kfileitem#totalSize"), KIO::convertSize(totalSize)); - } -#endif - - emit q->loadingFinished(); -} - -void KFileMetaDataProvider::Private::slotRatingChanged(unsigned int rating) -{ -#ifndef KIO_NO_NEPOMUK - Nepomuk::MassUpdateJob* job = Nepomuk::MassUpdateJob::rateResources(resourceList(), rating); - startChangeDataJob(job); -#else - Q_UNUSED(rating); -#endif -} - -void KFileMetaDataProvider::Private::slotTagsChanged(const QList& tags) -{ -#ifndef KIO_NO_NEPOMUK - if (!m_tagWidget.isNull()) { - m_tagWidget.data()->setSelectedTags(tags); - - Nepomuk::MassUpdateJob* job = Nepomuk::MassUpdateJob::tagResources(resourceList(), tags); - startChangeDataJob(job); - } -#else - Q_UNUSED(tags); -#endif -} - -void KFileMetaDataProvider::Private::slotCommentChanged(const QString& comment) -{ -#ifndef KIO_NO_NEPOMUK - Nepomuk::MassUpdateJob* job = Nepomuk::MassUpdateJob::commentResources(resourceList(), comment); - startChangeDataJob(job); -#else - Q_UNUSED(comment); -#endif -} - -void KFileMetaDataProvider::Private::slotTagClicked(const Nepomuk::Tag& tag) -{ -#ifndef KIO_NO_NEPOMUK - emit q->urlActivated(tag.resourceUri()); -#else - Q_UNUSED(tag); -#endif -} - -void KFileMetaDataProvider::Private::slotLinkActivated(const QString& link) -{ - emit q->urlActivated(KUrl(link)); -} - -void KFileMetaDataProvider::Private::startChangeDataJob(KJob* job) -{ - connect(job, SIGNAL(result(KJob*)), - q, SIGNAL(dataChangeFinished())); - emit q->dataChangeStarted(); - job->start(); -} - -#ifndef KIO_NO_NEPOMUK -QList KFileMetaDataProvider::Private::resourceList() const -{ - QList list; - foreach (const KFileItem& item, m_fileItems) { - const KUrl url = item.nepomukUri(); - if(url.isValid()) - list.append(Nepomuk::Resource(url)); - } - return list; -} - -QWidget* KFileMetaDataProvider::Private::createRatingWidget(int rating, QWidget* parent) -{ - KRatingWidget* ratingWidget = new KRatingWidget(parent); - const Qt::Alignment align = (ratingWidget->layoutDirection() == Qt::LeftToRight) ? - Qt::AlignLeft : Qt::AlignRight; - ratingWidget->setAlignment(align); - ratingWidget->setRating(rating); - const QFontMetrics metrics(parent->font()); - ratingWidget->setPixmapSize(metrics.height()); - - connect(ratingWidget, SIGNAL(ratingChanged(uint)), - q, SLOT(slotRatingChanged(uint))); - - m_ratingWidget = ratingWidget; - - return ratingWidget; -} - -QWidget* KFileMetaDataProvider::Private::createTagWidget(const QList& tags, QWidget* parent) -{ - Nepomuk::TagWidget* tagWidget = new Nepomuk::TagWidget(parent); - tagWidget->setModeFlags(m_readOnly - ? Nepomuk::TagWidget::MiniMode | Nepomuk::TagWidget::ReadOnly - : Nepomuk::TagWidget::MiniMode); - tagWidget->setSelectedTags(tags); - - connect(tagWidget, SIGNAL(selectionChanged(QList)), - q, SLOT(slotTagsChanged(QList))); - connect(tagWidget, SIGNAL(tagClicked(Nepomuk::Tag)), - q, SLOT(slotTagClicked(Nepomuk::Tag))); - - m_tagWidget = tagWidget; - - return tagWidget; -} - -QWidget* KFileMetaDataProvider::Private::createCommentWidget(const QString& comment, QWidget* parent) -{ - KCommentWidget* commentWidget = new KCommentWidget(parent); - commentWidget->setText(comment); - commentWidget->setReadOnly(m_readOnly); - - connect(commentWidget, SIGNAL(commentChanged(QString)), - q, SLOT(slotCommentChanged(QString))); - - m_commentWidget = commentWidget; - - return commentWidget; -} -#endif - -QWidget* KFileMetaDataProvider::Private::createValueWidget(const QString& value, QWidget* parent) -{ - ValueWidget* valueWidget = new ValueWidget(parent); - valueWidget->setWordWrap(true); - valueWidget->setAlignment(Qt::AlignTop | Qt::AlignLeft); - valueWidget->setText(m_readOnly ? plainText(value) : value); - connect(valueWidget, SIGNAL(linkActivated(QString)), q, SLOT(slotLinkActivated(QString))); - return valueWidget; -} - -KFileMetaDataProvider::KFileMetaDataProvider(QObject* parent) : - QObject(parent), - d(new Private(this)) -{ -} - -KFileMetaDataProvider::~KFileMetaDataProvider() -{ - delete d; -} - -void KFileMetaDataProvider::setItems(const KFileItemList& items) -{ - d->m_fileItems = items; - -#ifndef KIO_NO_NEPOMUK - if (items.isEmpty()) { - return; - } - Q_PRIVATE_SLOT(d,void slotDataChangeStarted()) - Q_PRIVATE_SLOT(d,void slotDataChangeFinished()) - QList urls; - foreach (const KFileItem& item, items) { - const KUrl url = item.nepomukUri(); - if (url.isValid()) { - urls.append(url); - } - } - - d->m_latestMetaDataReader = new KFileMetaDataReader(urls); - d->m_latestMetaDataReader->setReadContextData(d->m_nepomukActivated); - connect(d->m_latestMetaDataReader, SIGNAL(finished()), this, SLOT(slotLoadingFinished())); - d->m_metaDataReaders.append(d->m_latestMetaDataReader); - d->m_latestMetaDataReader->start(); -#endif -} - -QString KFileMetaDataProvider::label(const KUrl& metaDataUri) const -{ - struct TranslationItem { - const char* const key; - const char* const context; - const char* const value; - }; - - static const TranslationItem translations[] = { - { "kfileitem#comment", I18N_NOOP2_NOSTRIP("@label", "Comment") }, - { "kfileitem#modified", I18N_NOOP2_NOSTRIP("@label", "Modified") }, - { "kfileitem#owner", I18N_NOOP2_NOSTRIP("@label", "Owner") }, - { "kfileitem#permissions", I18N_NOOP2_NOSTRIP("@label", "Permissions") }, - { "kfileitem#rating", I18N_NOOP2_NOSTRIP("@label", "Rating") }, - { "kfileitem#size", I18N_NOOP2_NOSTRIP("@label", "Size") }, - { "kfileitem#tags", I18N_NOOP2_NOSTRIP("@label", "Tags") }, - { "kfileitem#totalSize", I18N_NOOP2_NOSTRIP("@label", "Total Size") }, - { "kfileitem#type", I18N_NOOP2_NOSTRIP("@label", "Type") }, - { 0, 0, 0} // Mandatory last entry - }; - - static QHash hash; - if (hash.isEmpty()) { - const TranslationItem* item = &translations[0]; - while (item->key != 0) { - hash.insert(item->key, i18nc(item->context, item->value)); - ++item; - } - } - - QString value = hash.value(metaDataUri.url()); - if (value.isEmpty()) { - value = KNfoTranslator::instance().translation(metaDataUri); - } - - return value; -} - -QString KFileMetaDataProvider::group(const KUrl& metaDataUri) const -{ - QString group; // return value - - const QString uri = metaDataUri.url(); - if (uri == QLatin1String("kfileitem#type")) { - group = QLatin1String("0FileItemA"); - } else if (uri == QLatin1String("kfileitem#size")) { - group = QLatin1String("0FileItemB"); - } else if (uri == QLatin1String("http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#width")) { - group = QLatin1String("0SizeA"); - } else if (uri == QLatin1String("http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#height")) { - group = QLatin1String("0SizeB"); - } - - return group; -} - -KFileItemList KFileMetaDataProvider::items() const -{ - return d->m_fileItems; -} - -void KFileMetaDataProvider::setReadOnly(bool readOnly) -{ - d->m_readOnly = readOnly; -} - -bool KFileMetaDataProvider::isReadOnly() const -{ - return d->m_readOnly; -} - -#ifndef KIO_NO_NEPOMUK -QHash KFileMetaDataProvider::data() const -{ - return d->m_data; -} - -QWidget* KFileMetaDataProvider::createValueWidget(const KUrl& metaDataUri, - const Nepomuk::Variant& value, - QWidget* parent) const -{ - Q_ASSERT(parent != 0); - QWidget* widget = 0; - - if (d->m_nepomukActivated) { - const QString uri = metaDataUri.url(); - if (uri == QLatin1String("kfileitem#rating")) { - widget = d->createRatingWidget(value.toInt(), parent); - } else if (uri == QLatin1String("kfileitem#tags")) { - const QStringList tagNames = value.toStringList(); - QList tags; - foreach (const QString& tagName, tagNames) { - tags.append(Nepomuk::Tag(tagName)); - } - - widget = d->createTagWidget(tags, parent); - } else if (uri == QLatin1String("kfileitem#comment")) { - widget = d->createCommentWidget(value.toString(), parent); - } - } - - if (widget == 0) { - widget = d->createValueWidget(value.toString(), parent); - } - - widget->setForegroundRole(parent->foregroundRole()); - widget->setFont(parent->font()); - - return widget; -} -#endif - -int KFileMetaDataProvider::Private::subDirectoriesCount(const QString& path) -{ -#ifdef Q_WS_WIN - QDir dir(path); - return dir.entryList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::System).count(); -#else - // Taken from kdelibs/kio/kio/kdirmodel.cpp - // Copyright (C) 2006 David Faure - - int count = -1; - DIR* dir = ::opendir(QFile::encodeName(path)); - if (dir) { - count = 0; - struct dirent *dirEntry = 0; - while ((dirEntry = ::readdir(dir))) { // krazy:exclude=syscalls - if (dirEntry->d_name[0] == '.') { - if (dirEntry->d_name[1] == '\0') { - // Skip "." - continue; - } - if (dirEntry->d_name[1] == '.' && dirEntry->d_name[2] == '\0') { - // Skip ".." - continue; - } - } - ++count; - } - ::closedir(dir); - } - return count; -#endif -} - -#include "kfilemetadataprovider_p.moc" diff --git a/kio/kfile/kfilemetadataprovider_p.h b/kio/kfile/kfilemetadataprovider_p.h deleted file mode 100644 index 09d924a3..00000000 --- a/kio/kfile/kfilemetadataprovider_p.h +++ /dev/null @@ -1,145 +0,0 @@ -/***************************************************************************** - * Copyright (C) 2010 by Peter Penz * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public License * - * along with this library; see the file COPYING.LIB. If not, write to * - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * - * Boston, MA 02110-1301, USA. * - *****************************************************************************/ - -#ifndef KFILEMETADATAMODEL_H -#define KFILEMETADATAMODEL_H - -#include - -#include -#include -#include - -#include -#ifndef KIO_NO_NEPOMUK - #define DISABLE_NEPOMUK_LEGACY - #include -#endif - -class KFileItemList; -class KProcess; -class KUrl; -class QWidget; - -/** - * @brief Provides the data for the KMetaDataWidget. - * - * The default implementation provides all meta data - * that are available due to Strigi and Nepomuk. If custom - * meta data should be added, the method KFileMetaDataProvider::loadData() - * must be overwritten. - * - * @see KFileMetaDataWidget - */ -class KFileMetaDataProvider : public QObject -{ - Q_OBJECT - -public: - explicit KFileMetaDataProvider(QObject* parent = 0); - virtual ~KFileMetaDataProvider(); - - /** - * Sets the items, where the meta data should be - * requested. The loading of the meta data is done - * asynchronously. The signal loadingFinished() is - * emitted, as soon as the loading has been finished. - * The meta data can be retrieved by - * KFileMetaDataProvider::data() afterwards. The label for - * each item can be retrieved by KFileMetaDataProvider::label(). - */ - void setItems(const KFileItemList& items); - KFileItemList items() const; - - /** - * If set to true, data such as the comment, tag or rating cannot be changed by the user. - * Per default read-only is disabled. The method readOnlyChanged() can be overwritten - * to react on the change. - */ - void setReadOnly(bool readOnly); - bool isReadOnly() const; - - /** - * @return Translated string for the label of the meta data represented - * by \p metaDataUri. If no custom translation is provided, the - * base implementation must be invoked. - */ - virtual QString label(const KUrl& metaDataUri) const; - - /** - * Meta data items are sorted alphabetically by their translated - * label per default. However it is possible to provide an internal - * prefix to the label, so that specific items are grouped together. - * For example it makes sense that the meta data for 'width' and 'height' - * of an image are shown below each other. By adding a common prefix, - * a grouping is done. - * @return Returns the name of the group the meta data indicated - * by \p metaDataUri belongs to. Per default an empty string - * is returned. - */ - virtual QString group(const KUrl& metaDataUri) const; - -#ifndef KIO_NO_NEPOMUK - /** - * @return Meta data for the items that have been set by - * KFileMetaDataProvider::setItems(). The method should - * be invoked after the signal loadingFinished() has - * been received (otherwise no data will be returned). - */ - virtual QHash data() const; - - /** - * @return Factory method that returns a widget that should be used - * to show the meta data represented by \p metaDataUri. If - * no custom value widget is used for the given URI, the base - * implementation must be invoked. Per default an instance - * of QLabel will be returned. - */ - virtual QWidget* createValueWidget(const KUrl& metaDataUri, - const Nepomuk::Variant& value, - QWidget* parent) const; -#endif - -Q_SIGNALS: - /** - * Is emitted after the loading triggered by KFileMetaDataProvider::setItems() - * has been finished. - */ - void loadingFinished(); - - void urlActivated(const KUrl& url); - - void dataChangeStarted(); - void dataChangeFinished(); - -private: - class Private; - Private* const d; - - Q_PRIVATE_SLOT(d, void slotLoadingFinished()) - Q_PRIVATE_SLOT(d, void slotRatingChanged(unsigned int rating)) - Q_PRIVATE_SLOT(d, void slotTagsChanged(const QList& tags)) - Q_PRIVATE_SLOT(d, void slotCommentChanged(const QString& comment)) - Q_PRIVATE_SLOT(d, void slotTagClicked(const Nepomuk::Tag& tag)) - Q_PRIVATE_SLOT(d, void slotLinkActivated(const QString&)) - - friend class KLoadMetaDataThread; // invokes KMetaDataObject::loadData() -}; - -#endif diff --git a/kio/kfile/kfilemetadatareader.cpp b/kio/kfile/kfilemetadatareader.cpp deleted file mode 100644 index 2fa4745d..00000000 --- a/kio/kfile/kfilemetadatareader.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/***************************************************************************** - * Copyright (C) 2011 by Peter Penz * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public License * - * along with this library; see the file COPYING.LIB. If not, write to * - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * - * Boston, MA 02110-1301, USA. * - *****************************************************************************/ - -#include "kfilemetadatareader_p.h" - -#include -#include - -class KFileMetaDataReader::Private -{ -public: - Private(KFileMetaDataReader* parent); - ~Private(); - - void slotLoadingFinished(int exitCode, QProcess::ExitStatus exitStatus); - - bool m_readContextData; - KProcess* m_process; - QHash m_metaData; - -private: - KFileMetaDataReader* const q; -}; - -KFileMetaDataReader::Private::Private(KFileMetaDataReader* parent) : - m_readContextData(true), - m_process(new KProcess()), - m_metaData(), - q(parent) -{ -} - -KFileMetaDataReader::Private::~Private() -{ - delete m_process; -} - -void KFileMetaDataReader::Private::slotLoadingFinished(int exitCode, QProcess::ExitStatus exitStatus) -{ - Q_UNUSED(exitCode); - Q_UNUSED(exitStatus); - - QDataStream in(QByteArray::fromBase64(m_process->readLine())); - - KUrl key; - Nepomuk::Variant value; - while (!in.atEnd()) { - in >> key; - - // Unlike QVariant no streaming operators are implemented for Nepomuk::Variant. - // So it is required to manually decode the variant from the stream. See - // function sendMetaData() in kfilemetadatareaderprocess.cpp for the encoding - // counterpart. - int streamType; - in >> streamType; - - switch (streamType) { - case 0: { - QStringList stringList; - in >> stringList; - value = stringList; - break; - } - case 1: { - QString resource; - in >> resource; - value = resource; - break; - } - - default: - QVariant variant; - in >> variant; - value = Nepomuk::Variant(variant); - } - - m_metaData.insert(key, value); - } - - emit q->finished(); -} - -KFileMetaDataReader::KFileMetaDataReader(const QList& urls, QObject* parent) : - QObject(parent), - d(new Private(this)) -{ - const QString fileMetaDataReaderExe = KStandardDirs::findExe(QLatin1String("kfilemetadatareader")); - (*d->m_process) << fileMetaDataReaderExe; - - foreach (const KUrl& url, urls) { - (*d->m_process) << url.url(); - } - - d->m_process->setOutputChannelMode(KProcess::OnlyStdoutChannel); - d->m_process->setNextOpenMode(QIODevice::ReadOnly); - connect(d->m_process, SIGNAL(finished(int,QProcess::ExitStatus)), - this, SLOT(slotLoadingFinished(int,QProcess::ExitStatus))); -} - -KFileMetaDataReader::~KFileMetaDataReader() -{ - delete d; -} - -void KFileMetaDataReader::setReadContextData(bool read) -{ - d->m_readContextData = read; -} - -bool KFileMetaDataReader::readContextData() const -{ - return d->m_readContextData; -} - -void KFileMetaDataReader::start() -{ - if (d->m_process->state() == QProcess::NotRunning) { - if (!d->m_readContextData) { - (*d->m_process) << "--file"; - } - d->m_process->start(); - } -} - -QHash KFileMetaDataReader::metaData() const -{ - return d->m_metaData; -} - -#include "kfilemetadatareader_p.moc" diff --git a/kio/kfile/kfilemetadatareader_p.h b/kio/kfile/kfilemetadatareader_p.h deleted file mode 100644 index 7447a72c..00000000 --- a/kio/kfile/kfilemetadatareader_p.h +++ /dev/null @@ -1,92 +0,0 @@ -/***************************************************************************** - * Copyright (C) 2011 by Peter Penz * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public License * - * along with this library; see the file COPYING.LIB. If not, write to * - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * - * Boston, MA 02110-1301, USA. * - *****************************************************************************/ - -#ifndef KFILEMETADATAREADER_H -#define KFILEMETADATAREADER_H - -#include - -#include - -#include -#include -#include -#include -#include - -/** - * @brief Provides metadata extracted from files. - * - * The reading of the metadata is done asynchronously in a process. - * This assures that the caller won't get blocked and also prevents - * that the caller crashes in case if a metadata-analyzer plugin is instable. - * - * @since 4.7 - * @internal - */ -class KFileMetaDataReader : public QObject -{ - Q_OBJECT - -public: - /** - * @param urls List of files where the metadata should be extracted from. - * @param parent Parent object. - */ - explicit KFileMetaDataReader(const QList& urls, QObject* parent = 0); - virtual ~KFileMetaDataReader(); - - /** - * If \p read is set to true also metadata that is persisted outside the - * files itself (like e.g. rating, comments or tags) are read. Per - * default the reading of context data is enabled. Pass false if only the metadata - * persisted inside the file should be read. - */ - void setReadContextData(bool read); - bool readContextData() const; - - /** - * Starts the reading of the metadata inside a custom process. - * The signal finished() will get emitted if the reading has been finished. - * Use metaData() to access the read metadata. - */ - void start(); - - /** - * @return The read metadata of the given files. The method provides valid values - * after the signal finished() has been emitted. If it is invoked before - * an empty hash-table will be returned. - */ - QHash metaData() const; - -Q_SIGNALS: - /** - * Is emitted if the reading of the metadata inside a custom process has been finished. - * The method metaData() can be used afterwards to access the metadata. - */ - void finished(); - -private: - class Private; - Private* d; - - Q_PRIVATE_SLOT(d, void slotLoadingFinished(int, QProcess::ExitStatus)) -}; - -#endif diff --git a/kio/kfile/kfilemetadatareaderprocess.cpp b/kio/kfile/kfilemetadatareaderprocess.cpp deleted file mode 100644 index 51030878..00000000 --- a/kio/kfile/kfilemetadatareaderprocess.cpp +++ /dev/null @@ -1,257 +0,0 @@ -/***************************************************************************** - * Copyright (C) 2011 by Peter Penz * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public License * - * along with this library; see the file COPYING.LIB. If not, write to * - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * - * Boston, MA 02110-1301, USA. * - *****************************************************************************/ - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#define DISABLE_NEPOMUK_LEGACY -#include "config-nepomuk.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -class KFileMetaDataReaderApplication : public QCoreApplication -{ - Q_OBJECT - -public: - KFileMetaDataReaderApplication(int& argc, char** argv); - -private Q_SLOTS: - void readAndSendMetaData(); - -private: - void sendMetaData(const QHash& data); - QHash readFileMetaData(const QList& urls) const; - QHash readFileAndContextMetaData(const QList& urls) const; -}; - - - -KFileMetaDataReaderApplication::KFileMetaDataReaderApplication(int& argc, char** argv) : - QCoreApplication(argc, argv) -{ - QTimer::singleShot(0, this, SLOT(readAndSendMetaData())); -} - -void KFileMetaDataReaderApplication::readAndSendMetaData() -{ - const KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); - - KUrl::List urls; - for (int i = 0; i < args->count(); ++i) { - urls.append(KUrl(args->arg(i))); - } - - QHash metaData; - if (args->isSet("file")) { - metaData = readFileMetaData(urls); - } else { - metaData = readFileAndContextMetaData(urls); - } - - sendMetaData(metaData); - - quit(); -} - -void KFileMetaDataReaderApplication::sendMetaData(const QHash& data) -{ - QByteArray byteArray; - QDataStream out(&byteArray, QIODevice::WriteOnly); - - QHashIterator it(data); - while (it.hasNext()) { - it.next(); - - out << it.key(); - - // Unlike QVariant no streaming operators are implemented for Nepomuk::Variant. - // So it is required to manually encode the variant for the stream. - // The decoding counterpart is located in KFileMetaDataReader. - const Nepomuk::Variant& variant = it.value(); - if (variant.isList()) { - out << 0 << variant.toStringList(); - } else if (variant.isResource()) { - out << 1 << variant.toString(); - } else { - out << 2 << variant.variant(); - } - } - - cout << byteArray.toBase64().constData(); -} - -QHash KFileMetaDataReaderApplication::readFileMetaData(const QList& urls) const -{ - QHash data; - - // Currently only the meta-data of one file is supported. - // It might be an option to read all meta-data and show - // ranges for each key. - if (urls.count() == 1) { - const QString path = urls.first().toLocalFile(); - KFileMetaInfo metaInfo(path, QString(), KFileMetaInfo::Fastest); - const QHash metaInfoItems = metaInfo.items(); - foreach (const KFileMetaInfoItem& metaInfoItem, metaInfoItems) { - const QString uriString = metaInfoItem.name(); - const Nepomuk::Variant value(metaInfoItem.value()); - data.insert(uriString, - Nepomuk::Utils::formatPropertyValue(Nepomuk::Types::Property(), value)); - } - } - - return data; -} - -QHash KFileMetaDataReaderApplication::readFileAndContextMetaData(const QList& urls) const -{ - QHash metaData; - - bool isNepomukIndexerActive = false; - if (Nepomuk::ResourceManager::instance()->initialized()) { - KConfig config("nepomukserverrc"); - isNepomukIndexerActive = config.group("Service-nepomukfileindexer").readEntry("autostart", false); - } else { - // No context meta data can be read without enabled Nepomuk - return readFileMetaData(urls); - } - - unsigned int rating = 0; - QString comment; - QList tags; - - if (urls.count() == 1) { - // Read the metadata of the file that are provided as properties - // (e.g. image-size, artist, album, ...) - bool useReadFromFileFallback = true; - - Nepomuk::Resource file(urls.first()); - if (file.isValid() && !file.resourceUri().isEmpty()) { - QHash variants = file.properties(); - QHash::const_iterator it = variants.constBegin(); - while (it != variants.constEnd()) { - Nepomuk::Types::Property prop(it.key()); - metaData.insert(prop.uri(), Nepomuk::Utils::formatPropertyValue(prop, it.value(), - QList() << file, - Nepomuk::Utils::WithKioLinks)); - ++it; - } - useReadFromFileFallback = !isNepomukIndexerActive || variants.isEmpty(); - - rating = file.rating(); - comment = file.description(); - tags = file.tags(); - } - - if (useReadFromFileFallback) { - // No metadata could be received with Nepomuk. Parse the file - // itself as fallback to extract metadata. - metaData = readFileMetaData(QList() << urls.first()); - } - } else { - // Read the data for rating, comment and tags - bool first = true; - foreach (const KUrl& url, urls) { - Nepomuk::Resource file(url); - if (!file.isValid()) { - continue; - } - - if (!first && rating != file.rating()) { - rating = 0; // Reset rating - } else if (first) { - rating = file.rating(); - } - - if (!first && comment != file.description()) { - comment.clear(); // Reset comment - } else if (first) { - comment = file.description(); - } - - if (!first && tags != file.tags()) { - tags.clear(); // Reset tags - } else if (first) { - tags = file.tags(); - } - - first = false; - } - } - - metaData.insert(KUrl("kfileitem#rating"), rating); - metaData.insert(KUrl("kfileitem#comment"), comment); - - QList tagVariants; - foreach (const Nepomuk::Tag& tag, tags) { - tagVariants.append(Nepomuk::Variant(tag)); - } - metaData.insert(KUrl("kfileitem#tags"), tagVariants); - - return metaData; -} - -int main(int argc, char *argv[]) -{ - KAboutData aboutData("kfilemetadatareader", "kio4", ki18n("KFileMetaDataReader"), - "1.0", - ki18n("KFileMetaDataReader can be used to read metadata from a file"), - KAboutData::License_GPL, - ki18n("(C) 2011, Peter Penz")); - aboutData.addAuthor(ki18n("Peter Penz"), ki18n("Current maintainer"), "peter.penz19@gmail.com"); - KComponentData compData(&aboutData); - - KCmdLineArgs::init(argc, argv, &aboutData); - - KCmdLineOptions options; - options.add("file", ki18n("Only the meta data that is part of the file is read")); - options.add("+[arg]", ki18n("List of URLs where the meta-data should be read from")); - - KCmdLineArgs::addCmdLineOptions(options); - - KFileMetaDataReaderApplication app(argc, argv); - return app.exec(); -} - -#include "kfilemetadatareaderprocess.moc" diff --git a/kio/kfile/kfilemetadatawidget.cpp b/kio/kfile/kfilemetadatawidget.cpp index 241e3f33..9526e8a6 100644 --- a/kio/kfile/kfilemetadatawidget.cpp +++ b/kio/kfile/kfilemetadatawidget.cpp @@ -33,16 +33,6 @@ #include #include -#ifndef KIO_NO_NEPOMUK - #define DISABLE_NEPOMUK_LEGACY - - #include - #include - - #include - - #include "kfilemetadataprovider_p.h" -#endif class KFileMetaDataWidget::Private { @@ -77,20 +67,8 @@ public: void slotDataChangeStarted(); void slotDataChangeFinished(); -#ifndef KIO_NO_NEPOMUK - QList sortedKeys(const QHash& data) const; - - /** - * @return True, if at least one of the file items \a m_fileItems has - * a valid Nepomuk URI. - */ - bool hasNepomukUris() const; -#endif QList m_rows; -#ifndef KIO_NO_NEPOMUK - KFileMetaDataProvider* m_provider; -#endif QGridLayout* m_gridLayout; private: @@ -99,21 +77,11 @@ private: KFileMetaDataWidget::Private::Private(KFileMetaDataWidget* parent) : m_rows(), -#ifndef KIO_NO_NEPOMUK - m_provider(0), -#endif m_gridLayout(0), q(parent) { initMetaInfoSettings(); -#ifndef KIO_NO_NEPOMUK - // TODO: If KFileMetaDataProvider might get a public class in future KDE releases, - // the following code should be moved into KFileMetaDataWidget::setModel(): - m_provider = new KFileMetaDataProvider(q); - connect(m_provider, SIGNAL(loadingFinished()), q, SLOT(slotLoadingFinished())); - connect(m_provider, SIGNAL(urlActivated(KUrl)), q, SIGNAL(urlActivated(KUrl))); -#endif } KFileMetaDataWidget::Private::~Private() @@ -188,77 +156,8 @@ void KFileMetaDataWidget::Private::deleteRows() void KFileMetaDataWidget::Private::slotLoadingFinished() { -#ifndef KIO_NO_NEPOMUK - deleteRows(); - - if (!hasNepomukUris()) { - q->updateGeometry(); - emit q->metaDataRequestFinished(m_provider->items()); - return; - } - - if (m_gridLayout == 0) { - m_gridLayout = new QGridLayout(q); - m_gridLayout->setMargin(0); - m_gridLayout->setSpacing(q->fontMetrics().height() / 4); - } - - QHash data = m_provider->data(); - - // Remove all items, that are marked as hidden in kmetainformationrc - KConfig config("kmetainformationrc", KConfig::NoGlobals); - KConfigGroup settings = config.group("Show"); - QHash::iterator it = data.begin(); - while (it != data.end()) { - const QString uriString = it.key().url(); - if (!settings.readEntry(uriString, true) || - !Nepomuk::Types::Property(it.key()).userVisible()) { - it = data.erase(it); - } else { - ++it; - } - } - - // Iterate through all remaining items embed the label - // and the value as new row in the widget - int rowIndex = 0; - const QList keys = sortedKeys(data); - foreach (const KUrl& key, keys) { - const Nepomuk::Variant value = data[key]; - QString itemLabel = m_provider->label(key); - itemLabel.append(QLatin1Char(':')); - - // Create label - QLabel* label = new QLabel(itemLabel, q); - label->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); - label->setForegroundRole(q->foregroundRole()); - label->setFont(q->font()); - label->setWordWrap(true); - label->setAlignment(Qt::AlignTop | Qt::AlignRight); - - // Create value-widget - QWidget* valueWidget = m_provider->createValueWidget(key, value, q); - - // Add the label and value-widget to grid layout - m_gridLayout->addWidget(label, rowIndex, 0, Qt::AlignRight); - const int spacerWidth = QFontMetrics(q->font()).size(Qt::TextSingleLine, " ").width(); - m_gridLayout->addItem(new QSpacerItem(spacerWidth, 1), rowIndex, 1); - m_gridLayout->addWidget(valueWidget, rowIndex, 2, Qt::AlignLeft); - - // Remember the label and value-widget as row - Row row; - row.label = label; - row.value = valueWidget; - m_rows.append(row); - - ++rowIndex; - } -#endif q->updateGeometry(); -#ifndef KIO_NO_NEPOMUK - emit q->metaDataRequestFinished(m_provider->items()); -#endif } void KFileMetaDataWidget::Private::slotLinkActivated(const QString& link) @@ -279,47 +178,6 @@ void KFileMetaDataWidget::Private::slotDataChangeFinished() q->setEnabled(true); } -#ifndef KIO_NO_NEPOMUK -QList KFileMetaDataWidget::Private::sortedKeys(const QHash& data) const -{ - // Create a map, where the translated label prefixed with the - // sort priority acts as key. The data of each entry is the URI - // of the data. By this the all URIs are sorted by the sort priority - // and sub sorted by the translated labels. - QMap map; - QHash::const_iterator hashIt = data.constBegin(); - while (hashIt != data.constEnd()) { - const KUrl uri = hashIt.key(); - - QString key = m_provider->group(uri); - key += m_provider->label(uri); - - map.insert(key, uri); - ++hashIt; - } - - // Apply the URIs from the map to the list that will get returned. - // The list will then be alphabetically ordered by the translated labels of the URIs. - QList list; - QMap::const_iterator mapIt = map.constBegin(); - while (mapIt != map.constEnd()) { - list.append(mapIt.value()); - ++mapIt; - } - - return list; -} - -bool KFileMetaDataWidget::Private::hasNepomukUris() const -{ - foreach (const KFileItem& fileItem, m_provider->items()) { - if (fileItem.nepomukUri().isValid()) { - return true; - } - } - return false; -} -#endif KFileMetaDataWidget::KFileMetaDataWidget(QWidget* parent) : QWidget(parent), @@ -334,34 +192,20 @@ KFileMetaDataWidget::~KFileMetaDataWidget() void KFileMetaDataWidget::setItems(const KFileItemList& items) { -#ifndef KIO_NO_NEPOMUK - d->m_provider->setItems(items); -#endif } KFileItemList KFileMetaDataWidget::items() const { -#ifndef KIO_NO_NEPOMUK - return d->m_provider->items(); -#else return KFileItemList(); -#endif } void KFileMetaDataWidget::setReadOnly(bool readOnly) { -#ifndef KIO_NO_NEPOMUK - d->m_provider->setReadOnly(readOnly); -#endif } bool KFileMetaDataWidget::isReadOnly() const { -#ifndef KIO_NO_NEPOMUK - return d->m_provider->isReadOnly(); -#else return true; -#endif } QSize KFileMetaDataWidget::sizeHint() const diff --git a/kio/kfile/knfotranslator.cpp b/kio/kfile/knfotranslator.cpp index 389e3b7d..ed3f62ac 100644 --- a/kio/kfile/knfotranslator.cpp +++ b/kio/kfile/knfotranslator.cpp @@ -24,10 +24,6 @@ #include #include -#ifndef KIO_NO_NEPOMUK -#define DISABLE_NEPOMUK_LEGACY -#include "property.h" -#endif struct TranslationItem { const char* const key; @@ -131,15 +127,11 @@ QString KNfoTranslator::translation(const KUrl& uri) const } // fallback if the URI is not translated -#ifndef KIO_NO_NEPOMUK - const QString label = Nepomuk::Types::Property(uri).label(); -#else QString label; const int index = key.indexOf(QChar('#')); if (index >= 0) { label = key.right(key.size() - index - 1); } -#endif QString tunedLabel; const int labelLength = label.length(); if (labelLength > 0) { diff --git a/kio/kio/kfileitem.cpp b/kio/kio/kfileitem.cpp index bdaf21a3..66e753f6 100644 --- a/kio/kio/kfileitem.cpp +++ b/kio/kio/kfileitem.cpp @@ -1621,23 +1621,7 @@ KUrl KFileItem::targetUrl() const KUrl KFileItem::nepomukUri() const { -#ifndef KIO_NO_NEPOMUK - if (!d) - return KUrl(); - - const QString nepomukUriStr = d->m_entry.stringValue( KIO::UDSEntry::UDS_NEPOMUK_URI ); - if(!nepomukUriStr.isEmpty()) { - return KUrl(nepomukUriStr); - } - else if(targetUrl().isLocalFile()) { - return targetUrl(); - } - else { - return KUrl(); - } -#else return KUrl(); -#endif } /* diff --git a/kio/kio/kfilemetainfoitem.cpp b/kio/kio/kfilemetainfoitem.cpp index 1cab458a..3b3adbc8 100644 --- a/kio/kio/kfilemetainfoitem.cpp +++ b/kio/kio/kfilemetainfoitem.cpp @@ -21,7 +21,6 @@ #include "kfilemetainfoitem.h" #include "kfilemetainfoitem_p.h" -#include KFileMetaInfoItem::KFileMetaInfoItem() : d(new KFileMetaInfoItemPrivate()) { } @@ -34,9 +33,6 @@ KFileMetaInfoItem::KFileMetaInfoItem(const QString& pp, #ifndef KDE_NO_DEPRECATED d->pp = pp; #else -#ifndef KIO_NO_NEPOMUK - d->pp = QUrl(pp); -#endif #endif d->value = v; d->writer = w; @@ -55,11 +51,7 @@ KFileMetaInfoItem::name() const { #ifndef KDE_NO_DEPRECATED return d->pp.name(); #else - #ifndef KIO_NO_NEPOMUK - return d->pp.name(); - #else - return QString::null; - #endif + return QString::null; #endif } const QVariant& diff --git a/kio/kio/kfilemetainfoitem_p.h b/kio/kio/kfilemetainfoitem_p.h index 48bb4f1c..c811a60b 100644 --- a/kio/kio/kfilemetainfoitem_p.h +++ b/kio/kio/kfilemetainfoitem_p.h @@ -27,9 +27,6 @@ #ifndef KDE_NO_DEPRECATED #include #else -#ifndef KIO_NO_NEPOMUK -#include -#endif #endif #include @@ -43,9 +40,6 @@ public: #ifndef KDE_NO_DEPRECATED PredicateProperties pp; #else -#ifndef KIO_NO_NEPOMUK - Nepomuk::Types::Property pp; -#endif #endif KUrl propertyUri; QVariant value; diff --git a/kparts/CMakeLists.txt b/kparts/CMakeLists.txt index 2eab2e82..1b36db49 100644 --- a/kparts/CMakeLists.txt +++ b/kparts/CMakeLists.txt @@ -3,12 +3,6 @@ project(kparts) add_subdirectory( tests ) include_directories(${KDE4_KIO_INCLUDES} ${kparts_BINARY_DIR}) -if(HAVE_NEPOMUK) - include_directories(${nepomuk_SOURCE_DIR} ${nepomuk_SOURCE_DIR}/core ${nepomuk_SOURCE_DIR}/types) -endif(HAVE_NEPOMUK) -if(Soprano_FOUND) -include_directories(${SOPRANO_INCLUDE_DIR}) -endif(Soprano_FOUND) ########### next target ############### @@ -37,10 +31,6 @@ kde4_add_library(kparts ${LIBRARY_TYPE} ${kparts_LIB_SRCS}) target_link_libraries(kparts ${KDE4_KDECORE_LIBS} kdeui kio) target_link_libraries(kparts LINK_INTERFACE_LIBRARIES kio kdeui kdecore ${QT_QTCORE_LIBRARY} ${QT_QTGUI_LIBRARY} ) -if(HAVE_NEPOMUK) - target_link_libraries(kparts nepomuk nepomukutils) - target_link_libraries(kparts LINK_INTERFACE_LIBRARIES nepomuk nepomukutils ) -endif(HAVE_NEPOMUK) set_target_properties(kparts PROPERTIES VERSION ${GENERIC_LIB_VERSION} SOVERSION ${GENERIC_LIB_SOVERSION} diff --git a/kparts/browserrun_p.h b/kparts/browserrun_p.h index 00ce0653..bd544d46 100644 --- a/kparts/browserrun_p.h +++ b/kparts/browserrun_p.h @@ -24,14 +24,8 @@ #include #include -#include "config-nepomuk.h" - #include -#ifdef HAVE_NEPOMUK -#include "../nepomuk/utils/utils.h" -#endif - namespace KParts { /** @@ -64,12 +58,6 @@ private Q_SLOTS: kDebug() << "download finished: srcUrl=" << fileCopyJob->srcUrl() << "destUrl=" << fileCopyJob->destUrl() << "referrer=" << m_metaData.value("referrer"); -#ifdef HAVE_NEPOMUK - Nepomuk::Utils::createCopyEvent( fileCopyJob->srcUrl(), - fileCopyJob->destUrl(), - m_downloadJobStartTime, - KUrl(m_metaData.value("referrer")) ); -#endif } } diff --git a/nepomuk/.emacs-dirvars b/nepomuk/.emacs-dirvars deleted file mode 100644 index 14e0f051..00000000 --- a/nepomuk/.emacs-dirvars +++ /dev/null @@ -1,14 +0,0 @@ -;; -*- emacs-lisp -*- -;; -;; This file is processed by the dirvars emacs package. Each variable -;; setting below is performed when this dirvars file is loaded. -;; -indent-tabs-mode: nil -tab-width: 8 -c-basic-offset: 4 -evaluate: (c-set-offset 'innamespace '4) -kde-emacs-after-parent-string: "" -evaluate: (c-set-offset 'inline-open '0) -kdab-qt-version: 4 -kdab-jump-project-name: kde -magic-parens-mode: nil diff --git a/nepomuk/CMakeLists.txt b/nepomuk/CMakeLists.txt deleted file mode 100644 index 04cdc72b..00000000 --- a/nepomuk/CMakeLists.txt +++ /dev/null @@ -1,209 +0,0 @@ -project(nepomuk) - -include(SopranoAddOntology) - -set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules") - -add_definitions(-DKDE_DEFAULT_DEBUG_AREA=300000) -add_definitions(-DQT_USE_FAST_CONCATENATION -DQT_USE_FAST_OPERATOR_PLUS) - -if(KDE_NO_DEPRECATED) - add_definitions(-DDISABLE_NEPOMUK_LEGACY=1) -endif(KDE_NO_DEPRECATED) - - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/core - ${CMAKE_CURRENT_SOURCE_DIR}/types - ${CMAKE_CURRENT_SOURCE_DIR}/ui - ${CMAKE_CURRENT_SOURCE_DIR}/query - ${CMAKE_CURRENT_SOURCE_DIR}/utils - ${CMAKE_SOURCE_DIR} - ${KDE4_KIO_INCLUDES} - ${QT_INCLUDES} - ${SOPRANO_INCLUDE_DIR} -) - -set(nepomuk_core_SRCS - core/variant.cpp - core/resourcedata.cpp - core/resourcemanager.cpp - core/nepomukmainmodel.cpp - core/dbusconnectionpool.cpp - core/resource.cpp - core/thing.cpp - core/file.cpp - core/tag.cpp - core/nepomukservice.cpp - core/dbustypes.cpp - core/resourcewatcher.cpp -) - -qt4_add_dbus_interface(nepomuk_core_SRCS - core/org.kde.nepomuk.ResourceWatcherConnection.xml - resourcewatcherconnectioninterface) - -qt4_add_dbus_interface(nepomuk_core_SRCS - core/org.kde.nepomuk.ResourceWatcher.xml - resourcewatchermanagerinterface) - - -if(NOT KDE_NO_DEPRECATED) - set(nepomuk_core_SRCS - ${nepomuk_core_SRCS} - core/tools.cpp - ) -endif(NOT KDE_NO_DEPRECATED) - -set(nepomuk_ui_SRCS - ui/ktagcloudwidget.cpp - ui/kblocklayout.cpp - ui/kmetadatatagcloud.cpp - ui/ktagdisplaywidget.cpp - ui/nepomukmassupdatejob.cpp - ui/tagwidget.cpp - ui/kedittagsdialog.cpp - ui/tagcheckbox.cpp -) - -set(nepomuk_types_SRCS - types/entity.cpp - types/ontology.cpp - types/class.cpp - types/property.cpp - types/literal.cpp - types/entitymanager.cpp -) - -if(NOT KDE_NO_DEPRECATED) - set(nepomuk_types_SRCS - ${nepomuk_types_SRCS} - types/desktopontologyloader.cpp - types/fileontologyloader.cpp - types/global.cpp - types/nepomukontologyloader.cpp - types/ontologyloader.cpp - types/ontologymanager.cpp - ) -endif(NOT KDE_NO_DEPRECATED) - -set(nepomuk_query_SRCS - query/term.cpp - query/negationterm.cpp - query/orterm.cpp - query/andterm.cpp - query/comparisonterm.cpp - query/simpleterm.cpp - query/groupterm.cpp - query/resourceterm.cpp - query/literalterm.cpp - query/resourcetypeterm.cpp - query/optionalterm.cpp - query/query.cpp - query/query_p.cpp - query/filequery.cpp - query/queryparser.cpp - query/dateparser.cpp - query/result.cpp - query/queryserviceclient.cpp - query/dbusoperators.cpp -) - -set(nepomuk_LIB_SRCS - ${nepomuk_core_SRCS} - ${nepomuk_ui_SRCS} - ${nepomuk_types_SRCS} -# ${nepomuk_query_SRCS} -) - -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/nie.trig" "NIE" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/nfo.trig" "NFO" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/ncal.trig" "NCAL" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/nco.trig" "NCO" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/nmo.trig" "NMO" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/nmm.trig" "NMM" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/nexif.trig" "NEXIF" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/pimo/pimo.trig" "PIMO" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/pimo/tmo.trig" "TMO" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nepomuk/nuao.trig" "NUAO" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") -soprano_add_ontology(nepomuk_LIB_SRCS "${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nepomuk/ndo.trig" "NDO" "Nepomuk::Vocabulary" "trig" VISIBILITY "nepomuk") - -kde4_add_library(nepomuk ${LIBRARY_TYPE} ${nepomuk_LIB_SRCS}) - -target_link_libraries(nepomuk - ${SOPRANO_LIBRARIES} - ${SOPRANO_CLIENT_LIBRARIES} - ${QT_QTCORE_LIBRARY} - ${QT_QTGUI_LIBRARY} - ${QT_QTDBUS_LIBRARY} - kdecore - kdeui -) - -target_link_libraries(nepomuk - LINK_INTERFACE_LIBRARIES - kdeui - ${SOPRANO_LIBRARIES}) - - -set_target_properties(nepomuk PROPERTIES - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) - -install(TARGETS nepomuk EXPORT kdelibsLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS}) - -install(FILES - nepomuk_export.h - core/variant.h - core/resourcemanager.h - core/nepomukservice.h - core/resource.h - core/thing.h - core/tag.h - core/file.h - types/entity.h - types/class.h - types/property.h - types/ontology.h - types/literal.h - ui/ktagcloudwidget.h - ui/kmetadatatagcloud.h - ui/kmetadatatagwidget.h - ui/ktagdisplaywidget.h - ui/nepomukmassupdatejob.h - ui/tagwidget.h - # Vocabularies - ${CMAKE_CURRENT_BINARY_DIR}/nie.h - ${CMAKE_CURRENT_BINARY_DIR}/nfo.h - ${CMAKE_CURRENT_BINARY_DIR}/ncal.h - ${CMAKE_CURRENT_BINARY_DIR}/nco.h - ${CMAKE_CURRENT_BINARY_DIR}/nmo.h - ${CMAKE_CURRENT_BINARY_DIR}/nmm.h - ${CMAKE_CURRENT_BINARY_DIR}/nexif.h - ${CMAKE_CURRENT_BINARY_DIR}/pimo.h - ${CMAKE_CURRENT_BINARY_DIR}/tmo.h - ${CMAKE_CURRENT_BINARY_DIR}/nuao.h - ${CMAKE_CURRENT_BINARY_DIR}/ndo.h - - DESTINATION ${INCLUDE_INSTALL_DIR}/nepomuk COMPONENT Devel -) - -if(NOT KDE_NO_DEPRECATED) - install(FILES - core/tools.h - types/desktopontologyloader.h - types/fileontologyloader.h - types/global.h - types/nepomukontologyloader.h - types/ontologyloader.h - types/ontologymanager.h - DESTINATION ${INCLUDE_INSTALL_DIR}/nepomuk COMPONENT Devel - ) -endif(NOT KDE_NO_DEPRECATED) - -add_subdirectory(rcgen) -add_subdirectory(query) -add_subdirectory(utils) -add_subdirectory(test) diff --git a/nepomuk/Mainpage.dox b/nepomuk/Mainpage.dox deleted file mode 100644 index 262d2347..00000000 --- a/nepomuk/Mainpage.dox +++ /dev/null @@ -1,647 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2006-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - - -/** \mainpage The Nepomuk Meta Data Library - -

-Overview | -\ref hacking "Using" | -\ref examples "Examples" | -\ref page_ontology "Desktop Ontologies" | -\ref nepomuk-rcgen "Resource Generator" -

- -This is the KDE Meta Data library (not to confuse with KFileMetaData). It consists of -the following parts: -\li The main resource handling centered around Nepomuk::Resource -\li The handling of ontologies via classes in the Nepomuk::Types namespace -\li The desktop Nepomuk::Query API -\li \ref nepomuk_facets -\li Several utility methods and classes - - -\section overview The General Idea - -Three types of meta data can be identified: - --# Meta data that is stored with the data itself and is available at all -times. This includes id3 tags, the number of pages in a pdf document, or -even the size of a file or the subject of an email. --# Meta data that is created by the user manually like annotations or tags -that are assigned to files, emails, or whatever resources. --# Meta data that can be gathered automatically by applications such as the -source of a downloaded file or the email an attachment was saved from or the -original when copying a file locally. - -Type 1 is already handled in many implementations. KDE itself includes the -KMetaFileInfo classes that allow extracting this kind of meta information from -files and the Strigi system even creates a searchable index of this information. - -Nepomuk is intended for meta data of type 2 and 3. It provides an easy way to -create and read meta data for arbitrary resources (this includes for example files -or emails, but also contacts or maybe even a paragraph in a pdf file). - -The simplest type of meta data that can be handled with Nepomuk is a comment. It -is a simple string associated with a resource (a file for example). This comment -is created by the user using an application that is based on Nepomuk. - -Nepomuk's core is designed to allow arbitrary types of meta data, i.e. any resource -can be related with any other resource or value by simply naming the relation and -providing the value. -The power of Nepomuk, however, lies in that it provides a class for each type -of resource. Each of these classes provide convenience methods to allow a simple -handling of the meta data. These classes are automatically generated from a -description of types and properties, i.e. an ontology (see \ref page_ontology). - -Nepomuk is resource based. Thus, working with Nepomuk is always done with instances -representing a certain resource. This resource has a list of properties. Properties -are named and have a certain type. The type can either be another resource (compare -a file that was an attachment from an email) or a literal (this means for example a -string, or an integer; the comment mentioned earlier would be a string literal). -Each property can either have a cardinality of 1 (again a file can only be saved from -one email) or greater than 1 (i.e. infinite, like one file can have arbitrary many -associated comments). See \ref hacking on how Nepomuk handles literals and cardinalities -greater than 1. - -\section toc Further Reading - -- \ref page_ontology -- \ref hacking -- \ref examples -- \ref nepomuk-rcgen -- The Nepomuk techbase tutorials - -\authors -Sebastian Trueg \ - -\maintainers -Sebastian Trueg \ - -\licenses -\lgpl - -*/ - - -/** \page hacking Using Nepomuk - -

-\ref index "Overview" | -Using | -\ref examples "Examples" | -\ref page_ontology "Desktop Ontologies" | -\ref nepomuk-rcgen "Resource Generator" -

- -\section hacking_resources Handling Resources - -In general there are two ways of using Nepomuk. - --# The preferred way: use the Resource subclasses as generated from \ref page_ontology - This is also the much simpler way since Nepomuk takes care of all type casting and - list handling automatically. --# Using Nepomuk::Resource directly. This is much harder since in this case - the type names (i.e. their URIs as defined in \ref page_ontology) have to be known. - On the other hand it allows to use additional resource types not defined in the ontology - and handle resources without knowing their type. - -Since all resource classes are derived from Nepomuk::Resource and only add additional methods -both ways can be used interchangeably. - -Resource objects (and thus also all objects of classes derived from Resource) with the same -URI share their data. Thus, if one is changed the other one is, too. - - -\subsection hacking_theeasyway Using Resource Subclasses - -Using Resource subclasses directly is very simple. All that is necessary to handle a -resource is to know its type and its URI (the URI can vary a lot between resource types; -The simplest example is certainly a local file: the URI is the path to the file). - -To access or create meta data for a resource one simply creates an instance of the -corresponding class and passes the resource URI to its constructor. - -In case of a file this would look as follows. - -\code -Nepomuk::File f( "/home/foo/bar.txt" ); -\endcode - -Now meta data can be read and set via the methods provided by Nepomuk::File -such as Nepomuk::File::setAnnotation. - -Each resource class also provides a static method which returns all existing instances -of this type. -See Nepomuk::File::allFiles for an example. - -See also \ref nepomuk-rcgen - - -\subsection hacking_thehardway Using Resource Directly - -Using the Nepomuk::Resource class directly forces one to learn a little more about -the internals of Nepomuk. Resource provides four methods to handle the properties of a -resource (reminder: all Resource subclasses as generated from \ref page_ontology are based -one these methods): - -- Nepomuk::Resource::property -- Nepomuk::Resource::setProperty -- Nepomuk::Resource::removeProperty -- Nepomuk::Resource::properties - -Each property's value is represented by a Nepomuk::Variant object which can contain -another Resource or a literal (string, int, ...) or even a list of the former two. Other than -with the Resource subclasses no automatic type conversion is performed. - -In case of a property that can have multiple values (cardinality greater than 1) Nepomuk::Resource::setProperty -has to be called with a list to set more than one (the Resource subclasses simplify this by -adding add methods in addition to the set method) and Nepomuk::Resource::getProperty -will also return a list (in both cases encapsulated in a Variant object). - -When creating a Resource object there are two cases that are dealt with differently: - -- The resource does not exist yet, i.e. no information about it is stored. In this case Nepomuk - does not know the type of the resource and will fall back to %http://www.w3.org/2000/01/rdf-schema\#Resource. -- If the resource already exists the type may be empty. It will then be read from the local meta - data store (where it was saved before by Nepomuk automatically). - -As a rule of thumb one should always define the type when creating meta data and leave it empty when -reading meta data. - -When using the plain Nepomuk::Resource class one is completely free to choose the -resource URIs, the type URIs, and the property URIs. However, to preserve compatibility with -other applications one is encouraged to stick to those define in \ref page_ontology. - -\section hacking_general Nepomuk Details - -Nepomuk is designed so the user (the developer of a client application) does not have to care about loading or -saving the data. All data is stored directly into the RDF storage and also read from it directly. - -Although in normal operation it is sufficient to only work with Nepomuk::Resource and -its subclasses errors might occur. This is where the Nepomuk::ResourceManager comes -in: it provides the Nepomuk::ResourceManager::init method which can be called manually -(the resource manager will be initialized automatically anyway) to check if the initialization was -successful and Nepomuk can be used. In addition it provides the Nepomuk::ResourceManager::error -signal which is emitted whenever an error occurs. - - -See \ref examples for further examples. -*/ - - -/** \page examples Nepomuk Examples - -

-\ref index "Overview" | -\ref hacking "Using" | -Examples | -\ref page_ontology "Desktop Ontologies" | -\ref nepomuk-rcgen "Resource Generator" -

- -\section examples_resource Resource Handling Examples - -Add an annotation (a comment) to a file. - -\code -Nepomuk::File f( "/home/foo/bar.txt" ); -f.setAnnotation( "This is just a test file that contains nothing of interest." ); -\endcode - -The following example creates a new tag. The tag can be accessed through its name -which works as an identifier. Nepomuk automatically creates a new unique URI if this -tag does not already exist. - -\code -Nepomuk::Tag tag( "MyTag" ); -Nepomuk::File f( "/home/foo/bar.txt" ); -f.addTag( tag ); -\endcode - -Reading the information using plain Resource methods: - -\code -Nepomuk::Resource f( "/home/foo/bar.txt" ); -QString annotation = f.getProperty( Soprano::Vocabulary::NAO::decription() ).toString(); -QList tags = f.getProperty( Soprano::Vocabulary::NAO::hasTag() ).toResourceList(); -QListIterator it( tags ); -while( it.hasNext() ) - kdDebug() << "File tagged with tag: " - << it.next().genericLabel(); -\endcode - -Reading the information using the convenience classes (be aware that these classes need to be generated -from an ontology using the \ref nepomuk-rcgen "Resource Generator"): - -\code -Nepomuk::File f( "/home/foo/bar.txt" ); -QString description = f.description(); -QList tags = f.getTags(); -QListIterator it( tags ); -while( it.hasNext() ) - kdDebug() << "File tagged with tag: " << it.next().genericLabel(); -\endcode - -Present all defined properties of an arbitrary resource to the user including -internationalized labels: - -\code -Nepomuk::Resource f( "/home/foo/bar.txt" ); -QHash properties = f.properties(); -QHashIterator it( properties ); -while( it.hasNext() ) { - it.next(); - kdDebug() << Nepomuk::Types::Property( it.key() ).label() << ": " << it.value().toString() << endl; -} -\endcode - - -\section examples_query Query Examples - -Perform a simple full text query that looks for any resource containing -the value 'nepomuk': - -\code -Nepomuk::Query::LiteralTerm nepomukTerm("nepomuk"); -Nepomuk::Query::Query query( nepomukTerm ); -\endcode - -Create a query that lists all resources tagged with a tag whose name -matches 'nepomuk': - -\code -Nepomuk::Query::ComparisonTerm term( Soprano::Vocabulary::NAO::hasTag(), - Nepomuk::Query::LiteralTerm("nepomuk") ); -Nepomuk::Query::Query query( term ); -\endcode - -Create a query that lists all resources tagged with a specific tag: - -\code -Nepomuk::Tag tag = getFancyTag(); -Nepomuk::Query::ComparisonTerm term( Soprano::Vocabulary::NAO::hasTag(), - Nepomuk::Query::ResourceTerm( tag ) ); -Nepomuk::Query::Query query( term ); -\endcode - -Create a query that lists all resource tagged with both the tags used -above: - -\code -Nepomuk::Tag tag = getFancyTag(); -Nepomuk::Query::ComparisonTerm fancyTagTerm( Soprano::Vocabulary::NAO::hasTag(), - Nepomuk::Query::ResourceTerm( tag ) ); -Nepomuk::Query::ComparisonTerm nepomukTagTerm( Soprano::Vocabulary::NAO::hasTag(), - Nepomuk::Query::LiteralTerm("nepomuk") ); -Nepomuk::Query::Query query( Nepomuk::Query::AndTerm(fancyTagTerm, nepomukTagTerm) ); -\endcode - - -Create a query that lists all \b files tagged with a specific tag: - -\code -Nepomuk::Tag tag = getFancyTag(); -Nepomuk::Query::ComparisonTerm term( Soprano::Vocabulary::NAO::hasTag(), - Nepomuk::Query::ResourceTerm( tag ) ); -Nepomuk::Query::FileQuery fileQuery( term ); -\endcode - - -Any other term can be used as sub term in a ComparisonTerm (%Vocabulary namespace generated via \ref nepomuk-rcgen). -The following query does return all resources related to person contacts that are tagged with \p tag. - -\code -Nepomuk::Query::AndTerm andTerm; -andTerm.addSubTerm( Nepomuk::Query::ResourceTypeTerm( Nepomuk::Vocabulary::NCO::PersonContact() ) ); -andTerm.addSubTerm( Nepomuk::Query::ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), - Nepomuk::Query::ResourceTerm( tag ) ) ); -Nepomuk::Query::ComparisonTerm cterm( Nepomuk::Vocabulary::NAO::isRelated(), - andTerm ); -\endcode - - -To make matters even more complex the above ComparisonTerm can be inverted: - -\code -cterm.setInverted(true); -\endcode - -This will not match resources related to some tagged person contact but match -resources that some tagged person contact is related to (sounds confusing but -remember that the properties are not symmetric by default, i.e. the graph of -data is directed.) - - -\subsection query_examples_file Listing Files - -Restrict the search to a specific folder: - -\code -fileQuery.addIncludeFolder( KUrl("/home/foobar/thegoodstuff") ); -\endcode - -Restrict the search to files-only (Vocabulary namespace generated via -onto2vocabularyclass -using \p ${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/nfo.trig): - -\code -Nepomuk::Query::Term folderTerm = Nepomuk::Query::ResourceTypeTerm( Nepomuk::Vocabulary::NFO::Folder() ); -Nepomuk::Query::Term noFolderTerm = Nepomuk::Query::NegationTerm::negateTerm(folderTerm); -fileQuery.setTerm( Nepomuk::Query::AndTerm( fileQuery.term(), noFolderTerm ) ); -\endcode - -List all query results in a KDirModel: - -\code -KDirModel* model = getFancyDirModel(); -Nepomuk::Query::Query query = buildFancyQuery(); -KUrl searchUrl = query.toSearchUrl(); -model->dirLister()->open( searchUrl ); -\endcode - -KIO will use the \p nepomuksearch:/ slave to list search results as file entries. - -\subsection query_examples_misc Misc Query Examples - -Match all EmailAddress instances with a specific email address: -\code -Nepomuk::Query::ComparisonTerm email( Nepomuk::Vocabulary::NCO::emailAddress(), Soprano::LiteralValue( "trueg@kde.org" ) ); -\endcode - -Match all nco:PersonContact instances: -\code -Nepomuk::Query::ResourceTypeTerm type( Nepomuk::Vocabulary::NCO::PersonContact() ); -\endcode - -Match all person contacts with a specific email address: -\code -Nepomuk::Query::AndTerm( type, Nepomuk::Query::ComparisonTerm( Nepomuk::Vocabulary::NCO::hasEmailAddress(), email ) ); -\endcode -*/ - - -/** \page page_ontology The Desktop Ontologies - -

-\ref index "Overview" | -\ref hacking "Using" | -\ref examples "Examples" | -Desktop Ontologies | -\ref nepomuk-rcgen "Resource Generator" -

- -The Desktop ontologies define the possible types and properties that can be used as metadata. -The ontologies are based on RDF/S and NRL (The Nepomuk Representation Language which adds some -OWL-like properties like cardinality or also named graphs). The types and properties can either -be used directly with the Resource class or through generated classes. -*/ - - -/** \page nepomuk-rcgen The Nepomuk Resource Generator - -

-\ref index "Overview" | -\ref hacking "Using" | -\ref examples "Examples" | -\ref page_ontology "Desktop Ontologies" | -Resource Generator -

- -The power of Nepomuk lies in the generated classes which allows the application developer to set -and retrieve metadata according to standards without knowing any specific RDF URIs or names of properties. -The idea is that the resource generator (which is installed along with the Nepomuk libraries) creates -Resource subclasses that provide wrapper methods for Resource::getProperty and Resource::setProperty from -ontology descriptions. - - -\section rcgen_cmake Usage through CMake - -The simplest way to use the resource generator is through CMake. Nepomuk provides a macro to automatically -add the class generation target. The macro is used similar to the macro for adding ui files. - -\code -include(NepomukAddOntologyClasses) -\endcode - -This will provide a macro called NEPOMUK_ADD_ONTOLOGY_CLASSES: - -\code -NEPOMUK_ADD_ONTOLOGY_CLASSES( - [FAST] - [ONTOLOGIES] [ ...] - [CLASSES [ ...]] - [VISIBILITY ] - ) -\endcode - -If FAST is specified the rcgen parameter --fast will be used which results in resource classes -not based on Nepomuk::Resource but on a custom class which does not perform any checks and simply -writes the data to Nepomuk (hence the name fast). - -The optional CLASSES parameter allows to specify the classes to be generated (RDF class names) in -case one does not want all classes in the ontologies to be generated. If omitted all classes in the -ontology files will be generated. - -The optional VISIBILITY parameter can only be used in non-fast mode and allows to set the gcc visibility -to make the generated classes usable in a publically exported API. The is used to create -the name of the export macro and the export include file. Thus, when using "VISIBILITY foobar" include -file "foobar_export.h" needs to define FOOBAR_EXPORT. - -\subsection rcgen_cmake_example Example - -\code -include(NepomukAddOntologyClasses) - -set(SRCS [...]) - -nepomuk_add_ontology_classes(SRCS ONTOLOGIES ontology.trig) - -kde4_add_executable(foobar ${SRCS}) -target_link_libraries(foobar - nepomuk -) -\endcode -*/ - -/** \namespace Nepomuk::Types -\brief The %Types namespace contains all classes used to handle ontology entities such as classes and properties. -*/ - -/** \namespace Nepomuk::Vocabulary -\brief The %Vocabulary namespace contains the most commonly used classes and methods used to easily access the vocabularies. - -If the vocabulary you are looking for is not present, it can be created using the \em onto2vocabularyclass tool provided by \em %Soprano. The best way to do that is through the provided cmake macro: - -\code -soprano_add_ontology(my_SRC ${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/nfo.trig "NFO" "Nepomuk::Vocabulary" "trig") -\endcode - -Here both \em %Soprano and \em SharedDesktopOntologies have been found through the cmake macros provided by the packages and kdelibs. -*/ - -/** \namespace Nepomuk::Query - -\brief The %Query namespace contains all classes that make up the Nepomuk %Query API. - -Constructing queries consists of creating and combining different types of Term subclasses or using the -QueryParser to parse user queries (see the QueryParser documentation for details on the query syntax). - -The constructed queries can then be executed on the nepomuk query service via the QueryServiceClient, -used directly on a Soprano::Model (for example the %Nepomuk main model which can be retrieved via -ResourceManager::mainModel()), or listed via KIO (see Query::Query::toSearchUrl()). - -\section nepomuk_constructing_queries Constructing Queries - -Basically all one needs to know is that each Term matches a set of resources. Different types of terms do -so in different ways. The simplest type is the ResourceTerm which matches exactly one resource by URI. -The ComparisonTerm matches all resources that have a property with a certain value. The LiteralTerm by -itselt matches all resources that contain the string value in one of their properties, and so on. - -Thus, constructing a query means to combine all constraints that the results should fulfill using AndTerm -and maybe OrTerm. Everything can also the nested and most importantly (this is the one real graph query -thing in the API) ComparisonTerm can use any other term as object, meaning it can compare the value of -a property (if it is not a literal value) to the results of a subquery. A simple example would be the -following: - -\code -// match all EmailAddress instances with a specific email address: -Nepomuk::Query::ComparisonTerm email( Nepomuk::Vocabulary::NCO::emailAddress(), Soprano::LiteralValue( "trueg@kde.org" ) ); - -// match all nco:PersonContact instances -Nepomuk::Query::ResourceTypeTerm type( Nepomuk::Vocabulary::NCO::PersonContact() ); - -// match all person contacts with a specific email address -Nepomuk::Query::AndTerm( type, Nepomuk::Query::ComparisonTerm( Nepomuk::Vocabulary::NCO::hasEmailAddress(), email ) ); -\endcode - -\subsection nepomuk_fancy_query_operators Fancy Operators - -Starting with KDE SC 4.6 queries can be constructed using well known C++ operators. The above examples can now be -written as: - -\code -// match all EmailAddress instances with a specific email address: -Nepomuk::Query::ComparisonTerm email = Nepomuk::Vocabulary::NCO::emailAddress() == Soprano::LiteralValue( "trueg@kde.org" ); - -// match all nco:PersonContact instances -Nepomuk::Query::ResourceTypeTerm type( Nepomuk::Vocabulary::NCO::PersonContact() ); - -// match all person contacts with a specific email address -Nepomuk::Query::AndTerm = type && ( Nepomuk::Vocabulary::NCO::hasEmailAddress() == email ); -\endcode - -Furthermore literal comparisons can now be written as: - -\code -Nepomuk::Query::ComparisonTerm mtime - = Nepomuk::Vocabulary::NIE::lastModified() > Nepomuk::Query::LiteralTerm( QDateTime::currentDateTime().addDays(-7) ); -\endcode - -\sa \ref examples_query -*/ - -/** \namespace Nepomuk::Utils -\brief The %Utils namespace contains utility and convenience methods and classes that help the application developer with -using %Nepomuk. -An essential part of the %Utils is the \ref nepomuk_facets which allows developers to easily integrate a filter-based -search interface into their applications. -*/ - - -/** \defgroup nepomuk_facets The Facet API -\brief A set of classes which allow for easy filter-based search interfaces. - -The Facet API which was introduced in KDE SC 4.6 provides a set of classes that allow the integration of a filter-based -search interface into applications. It consists of the abstract Nepomuk::Utils::Facet class which has to be subclassed to implement -a facet of a query and a convenient GUI element Nepomuk::Utils::FacetWidget which provides all the necessary user interaction. - -If Nepomuk::Utils::FacetWidget does not suit the particular use case in an application Nepomuk::Utils::FacetModel is provided -as a more advanced approach to handling facets. If even that is too constrained one can always handle the facets manually. - -For convenience Nepomuk::Utils::SimpleFacet and Nepomuk::Utils::DynamicResourceFacet as well as a set of static factory methods in -Nepomuk::Utils::Facet are provided to make facet creation as simple as possible. - -\section nepomuk_facet_examples Facet Examples - -Nepomuk::Utils::ProxyFacet comes with a nice feature which allows to set a condition for the facet (Nepomuk::Utils::ProxyFacet::setFacetCondition()). -The condition is a simple query term and means that the facet will not provide any choices unless the condition is met. -This is best illustrated with a small example: - -Imagine a facet that filters on image sizes: - -\code -Nepomuk::Utils::SimpleFacet* imageSizeFacet = new Nepomuk::Utils::SimpleFacet(); -imageSizeFacet->addTerm( i18n("Small"), Vocabulary::NFO::width() <= Nepomuk::Query::LiteralTerm(300)); -imageSizeFacet->addTerm( i18n("Medium"), (Vocabulary::NFO::width() > Nepomuk::Query::LiteralTerm(300)) && - (Vocabulary::NFO::width() <= Nepomuk::Query::LiteralTerm(800))); -imageSizeFacet->addTerm( i18n("Large"), Vocabulary::NFO::width() > Nepomuk::Query::LiteralTerm(800)); -\endcode - -So far so good. However, this facet does only make sense for images. Thus, we want the choices to be hidden when the query -shows other kinds of resources. What is the width of a project or an event? The solution is the facet condition: - -\code -Nepomuk::Utils::ProxyFacet* proxy = new Nepomuk::Utils::ProxyFacet(); -proxy->setSourceFacet(imageSizeFacet); -proxy->setFacetCondition(Nepomuk::Query::ResourceTypeTerm(Vocabulary::NFO::Image())); -\endcode - -Now the proxy facet will only show any choices if the query contains the condition term, ie. if only images are queried. -Be aware though that this feature does only work if the client uses Nepomuk::Utils::Facet::setClientQuery(). - -The same approach could be used to filter a Nepomuk::Utils::DynamicResourceFacet which filters on artists only when looking -for audio files. - -\note -The \e Vocabulary namespace can be generated via the \em onto2vocabularyclass tool provided by \em %Soprano. The best way to do -that is through the provided cmake macro: -\code -soprano_add_ontology(my_SRC ${SHAREDDESKTOPONTOLOGIES_ROOT_DIR}/nie/nfo.trig "NFO" "Nepomuk::Vocabulary" "trig") -\endcode -Here both \em %Soprano and \em SharedDesktopOntologies have been found through the cmake macros provided by the packages and kdelibs. -*/ - -// DOXYGEN_SET_RECURSIVE = NO -// DOXYGEN_SET_FILE_PATTERNS = *.h -// DOXYGEN_SET_INPUT = @topdir@/nepomuk/Mainpage.dox -// DOXYGEN_SET_INPUT += @topdir@/nepomuk/core -// DOXYGEN_SET_INPUT += @topdir@/nepomuk/ui -// DOXYGEN_SET_INPUT += @topdir@/nepomuk/types -// DOXYGEN_SET_INPUT += @topdir@/nepomuk/query -// DOXYGEN_SET_INPUT += @topdir@/nepomuk/utils -// DOXYGEN_SET_EXCLUDE = @topdir@/nepomuk/core/resourcedata.h -// DOXYGEN_SET_EXCLUDE += @topdir@/nepomuk/core/nepomukmainmodel.h -// DOXYGEN_SET_EXCLUDE += @topdir@/nepomuk/core/resourcefiltermodel.h -// DOXYGEN_SET_EXCLUDE += @topdir@/nepomuk/core/nie.h -// DOXYGEN_SET_EXCLUDE += @topdir@/nepomuk/types/entitymanager.h -// DOXYGEN_SET_EXCLUDE += @topdir@/nepomuk/ui/tagcheckbox.h -// DOXYGEN_SET_EXCLUDE += @topdir@/nepomuk/ui/kblocklayout.h -// DOXYGEN_SET_EXCLUDE += @topdir@/nepomuk/utils/searchlineedit.h -// DOXYGEN_SET_EXCLUDE += @topdir@/nepomuk/utils/facetfiltermodel.h -// DOXYGEN_SET_EXCLUDE += @topdir@/nepomuk/utils/facetdelegate.h -// DOXYGEN_SET_EXCLUDE_PATTERNS += @topdir@/nepomuk/core/*_p.h -// DOXYGEN_SET_EXCLUDE_PATTERNS += @topdir@/nepomuk/types/*_p.h -// DOXYGEN_SET_EXCLUDE_PATTERNS += @topdir@/nepomuk/ui/*_p.h -// DOXYGEN_SET_EXCLUDE_PATTERNS += @topdir@/nepomuk/query/*_p.h -// DOXYGEN_SET_EXCLUDE_PATTERNS += @topdir@/nepomuk/utils/*_p.h -// DOXYGEN_SET_PROJECT_NAME = Nepomuk -// vim:ts=4:sw=4:expandtab:filetype=doxygen diff --git a/nepomuk/core/dbusconnectionpool.cpp b/nepomuk/core/dbusconnectionpool.cpp deleted file mode 100644 index 3b7541c5..00000000 --- a/nepomuk/core/dbusconnectionpool.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2010 Sebastian Trueg - * Copyright (C) 2010 David Faure - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "dbusconnectionpool.h" -#include - -namespace { -QAtomicInt s_connectionCounter; - -class DBusConnectionPoolPrivate -{ -public: - DBusConnectionPoolPrivate() - : m_connection( QDBusConnection::connectToBus( - QDBusConnection::SessionBus, - QString::fromLatin1("NepomukQueryServiceConnection%1").arg(newNumber()) ) ) - { - } - ~DBusConnectionPoolPrivate() { - QDBusConnection::disconnectFromBus( m_connection.name() ); - } - - QDBusConnection connection() const { return m_connection; } - -private: - static int newNumber() { - return s_connectionCounter.fetchAndAddAcquire(1); - } - QDBusConnection m_connection; -}; -} - -QThreadStorage s_perThreadConnection; - -QDBusConnection DBusConnectionPool::threadConnection() -{ - if (!s_perThreadConnection.hasLocalData()) { - s_perThreadConnection.setLocalData(new DBusConnectionPoolPrivate); - } - return s_perThreadConnection.localData()->connection(); -} diff --git a/nepomuk/core/dbusconnectionpool.h b/nepomuk/core/dbusconnectionpool.h deleted file mode 100644 index dd075f8a..00000000 --- a/nepomuk/core/dbusconnectionpool.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2010 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _DBUS_CONNECTION_POOL_H_ -#define _DBUS_CONNECTION_POOL_H_ - -#include - -namespace DBusConnectionPool -{ -/** - * The DBusConnectionPool works around the problem - * of QDBusConnection not being thread-safe. As soon as that - * has been fixed (either directly in libdbus or with a work- - * around in Qt) this method can be dropped in favor of - * QDBusConnection::sessionBus(). - */ -QDBusConnection threadConnection(); -} - -#endif - diff --git a/nepomuk/core/dbustypes.cpp b/nepomuk/core/dbustypes.cpp deleted file mode 100644 index 9d69578c..00000000 --- a/nepomuk/core/dbustypes.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2011 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "dbustypes.h" - -#include -#include -#include -#include -#include - -#include "kurl.h" -#include "kdebug.h" - -QString Nepomuk::DBus::convertUri(const QUrl& uri) -{ - return KUrl(uri).url(); -} - -QStringList Nepomuk::DBus::convertUriList(const QList& uris) -{ - QStringList uriStrings; - foreach(const QUrl& uri, uris) - uriStrings << convertUri(uri); - return uriStrings; -} - -QVariantList Nepomuk::DBus::normalizeVariantList(const QVariantList& l) -{ - QVariantList newL; - QListIterator it(l); - while(it.hasNext()) { - QVariant v = it.next(); - if(v.userType() == qMetaTypeId()) { - newL.append(QVariant(QUrl(v.value()))); - } - else { - newL.append(v); - } - } - return newL; -} - -QVariant Nepomuk::DBus::resolveDBusArguments(const QVariant& v) -{ - // - // trueg: QDBus does not automatically convert non-basic types but gives us a QDBusArgument in a QVariant. - // Thus, we need to handle QUrl, QTime, QDate, and QDateTime as a special cases here. They is the only complex types we support. - // - if(v.userType() == qMetaTypeId()) { - const QDBusArgument arg = v.value(); - - QVariant v; - if(arg.currentSignature() == QLatin1String("(s)")) { - QUrl url; - arg >> url; - return url; - } - else if(arg.currentSignature() == QLatin1String("(iii)")) { - QDate date; - arg >> date; - return date; - } - else if(arg.currentSignature() == QLatin1String("(iiii)")) { - QTime time; - arg >> time; - return time; - } - else if(arg.currentSignature() == QLatin1String("((iii)(iiii)i)")) { - QDateTime dt; - arg >> dt; - return dt; - } - else { - kDebug() << "Unknown type signature in property hash value:" << arg.currentSignature(); - return QVariant(); - } - } - else { - return v; - } -} - -QVariantList Nepomuk::DBus::resolveDBusArguments(const QVariantList& l) -{ - QVariantList newL; - QListIterator it(l); - while(it.hasNext()) { - newL.append(resolveDBusArguments(it.next())); - } - return newL; -} - -void Nepomuk::DBus::registerDBusTypes() -{ - // we need QUrl to be able to pass it in a QVariant - qDBusRegisterMetaType(); -} - -// We need the QUrl serialization to be able to pass URIs in variants -QDBusArgument& operator<<( QDBusArgument& arg, const QUrl& url ) -{ - arg.beginStructure(); - arg << QString::fromLatin1(url.toEncoded()); - arg.endStructure(); - return arg; -} - -// We need the QUrl serialization to be able to pass URIs in variants -const QDBusArgument& operator>>( const QDBusArgument& arg, QUrl& url ) -{ - arg.beginStructure(); - QString uriString; - arg >> uriString; - url = QUrl::fromEncoded(uriString.toLatin1()); - arg.endStructure(); - return arg; -} diff --git a/nepomuk/core/dbustypes.h b/nepomuk/core/dbustypes.h deleted file mode 100644 index 4a66a20d..00000000 --- a/nepomuk/core/dbustypes.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2011 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef DBUSTYPES_H -#define DBUSTYPES_H - -#include -#include -#include -#include -#include -#include - -// #include "simpleresource.h" -// #include "nepomukdatamanagement_export.h" -#include "nepomuk_export.h" - -//CAUTION: Q_DECLARE_METATYPE doesn't accept template arguments like QHash -typedef QHash __nepomuk_QHashQStringQString; -Q_DECLARE_METATYPE( __nepomuk_QHashQStringQString ) - -namespace Nepomuk { - namespace DBus { - QString NEPOMUK_EXPORT convertUri(const QUrl& uri); - QStringList NEPOMUK_EXPORT convertUriList(const QList& uris); - - /// Convert QDBusArguments variants into QUrl, QDate, QTime, and QDateTime variants - NEPOMUK_EXPORT QVariant resolveDBusArguments(const QVariant& v); - NEPOMUK_EXPORT QVariantList resolveDBusArguments(const QVariantList& l); - - /// Replaces KUrl with QUrl for DBus marshalling. - QVariantList normalizeVariantList(const QVariantList& l); - - NEPOMUK_EXPORT void registerDBusTypes(); - } -} - -QDBusArgument& operator<<( QDBusArgument& arg, const QUrl& url ); -const QDBusArgument& operator>>( const QDBusArgument& arg, QUrl& url ); - -#endif // DBUSTYPES_H diff --git a/nepomuk/core/file.cpp b/nepomuk/core/file.cpp deleted file mode 100644 index 38c616bd..00000000 --- a/nepomuk/core/file.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "file.h" -#include "variant.h" -#include "nie.h" -#include "nfo.h" - -Nepomuk::File::File( const KUrl& url, ResourceManager* manager ) - : Resource( url, Nepomuk::Vocabulary::NFO::FileDataObject(), manager ) -{ -} - - -Nepomuk::File::File( const Resource& other ) - : Resource( other ) -{ -} - - -Nepomuk::File::~File() -{ -} - - -Nepomuk::File& Nepomuk::File::operator=( const KUrl& url ) -{ - this->Resource::operator=(url); - return (*this); -} - - -KUrl Nepomuk::File::url() const -{ - return property( Nepomuk::Vocabulary::NIE::url() ).toUrl(); -} - - -Nepomuk::File Nepomuk::File::dirResource() const -{ - if( isFile() ) { - return File( url().upUrl() ); - } - else { - return File(); - } -} diff --git a/nepomuk/core/file.h b/nepomuk/core/file.h deleted file mode 100644 index 2b67de5d..00000000 --- a/nepomuk/core/file.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_FILE_H_ -#define _NEPOMUK_FILE_H_ - -#include "resource.h" -#include "nepomuk_export.h" - -namespace Nepomuk { - /** - * \class File file.h Nepomuk/File - * - * \brief A Nepomuk resource representing a file. - * - * %File is a convinience class which allows to easily handle file - * resources which are sort of a special case in %Nepomuk. - * - * \author Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUK_EXPORT File : public Resource - { - public: - /** - * Create a new file resource. - * - * \param url The URL to the file. - * \param manager The resource manager to use. This allows to mix resources from different - * managers and, thus, different models. - */ - File( const KUrl& url = KUrl(), ResourceManager* manager = 0 ); - - /** - * Construct from a Resource - */ - File( const Resource& other ); - - /** - * Desctructor - */ - ~File(); - - /** - * Assignment operator. - */ - File& operator=( const KUrl& url ); - - /** - * The URL of the file. Be aware that this differs from - * Resource::resourceUri() and is stored as nie:url - * in the %Nepomuk database. - * - * \return The URL of the file or an empty KUrl in case this - * resource does not represent a file. - */ - KUrl url() const; - - /** - * Returns the resource representing the containing folder, - * ie. the folder containing this file resource. - * - * \return The resource representing the folder or an invalid - * resource in case this resource is invalid or not a file. - */ - File dirResource() const; - }; -} - -#endif diff --git a/nepomuk/core/nepomukmainmodel.cpp b/nepomuk/core/nepomukmainmodel.cpp deleted file mode 100644 index 73370afa..00000000 --- a/nepomuk/core/nepomukmainmodel.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2008-2012 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "nepomukmainmodel.h" -#include "resourcemanager.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - - -using namespace Soprano; - -class Nepomuk::MainModel::Private -{ -public: - Private() - : virtuosoModel( 0 ), - dummyModel( 0 ), - m_initMutex( QMutex::Recursive ) { - } - - ~Private() { - delete virtuosoModel; - delete dummyModel; - } - - Soprano::StorageModel* virtuosoModel; - Soprano::Util::DummyModel* dummyModel; - - void init( bool forced ) { - QMutexLocker lock( &m_initMutex ); - - if( !forced && virtuosoModel ) - return; - - Soprano::PluginManager* pm = Soprano::PluginManager::instance(); - const Soprano::Backend* backend = pm->discoverBackendByName( QLatin1String( "virtuosobackend" ) ); - - if ( !backend || !backend->isAvailable() ) { - kError() << "Could not find virtuoso backend"; - } - - Soprano::BackendSettings settings; - - KConfig config("nepomukserverrc"); - KConfigGroup repoConfig = config.group( "main Settings" ); - int portNumber = repoConfig.readEntry("Port", 0); - if(!portNumber) { - kError() << "Could not find virtuoso to connect to. Aborting"; - return; - } - - settings << Soprano::BackendSetting( Soprano::BackendOptionHost, "localhost" ); - settings << Soprano::BackendSetting( Soprano::BackendOptionPort, portNumber ); - settings << Soprano::BackendSetting( Soprano::BackendOptionUsername, "dba" ); - settings << Soprano::BackendSetting( Soprano::BackendOptionPassword, "dba" ); - settings << Soprano::BackendSetting( "noStatementSignals", true ); - settings << Soprano::BackendSetting( "fakeBooleans", false ); - settings << Soprano::BackendSetting( "emptyGraphs", false ); - - // FIXME: Can we really delete the model? What about open iterators? - if( virtuosoModel ) - virtuosoModel->deleteLater(); - - virtuosoModel = backend ? backend->createModel( settings ) : 0; - // Listen to the virtuoso model crashing? - } - - Soprano::Model* model() { - QMutexLocker lock( &m_initMutex ); - - init( false ); - - if ( virtuosoModel ) { - return virtuosoModel; - } - else { - if ( !dummyModel ) { - dummyModel = new Soprano::Util::DummyModel(); - } - return dummyModel; - } - } - - QMutex m_initMutex; -}; - - -Nepomuk::MainModel::MainModel( QObject* parent ) - : Soprano::Model(), - d( new Private() ) -{ - setParent( parent ); -} - - -Nepomuk::MainModel::~MainModel() -{ - delete d; -} - - -bool Nepomuk::MainModel::isValid() const -{ - QMutexLocker lock( &d->m_initMutex ); - return d->virtuosoModel; -} - - -bool Nepomuk::MainModel::init() -{ - d->init( true ); - return isValid(); -} - -void Nepomuk::MainModel::disconnect() -{ - QMutexLocker lock( &d->m_initMutex ); - d->virtuosoModel->deleteLater(); - d->virtuosoModel = 0; -} - - -Soprano::StatementIterator Nepomuk::MainModel::listStatements( const Statement& partial ) const -{ - Soprano::StatementIterator it = d->model()->listStatements( partial ); - setError( d->model()->lastError() ); - return it; -} - - -Soprano::NodeIterator Nepomuk::MainModel::listContexts() const -{ - Soprano::NodeIterator it = d->model()->listContexts(); - setError( d->model()->lastError() ); - return it; -} - -// -// Copied from services/storage/virtuosoinferencemodel.cpp -// -namespace { - const char* s_nepomukInferenceRuleSetName = "nepomukinference"; -} - -Soprano::QueryResultIterator Nepomuk::MainModel::executeQuery( const QString& query, - Soprano::Query::QueryLanguage language, - const QString& userQueryLanguage ) const -{ - Soprano::QueryResultIterator it; - if(language == Soprano::Query::QueryLanguageSparqlNoInference) { - it = d->model()->executeQuery(query, Soprano::Query::QueryLanguageSparql); - } - else if(language == Soprano::Query::QueryLanguageSparql ) { - it = d->model()->executeQuery(QString::fromLatin1("DEFINE input:inference <%1> ") - .arg(QLatin1String(s_nepomukInferenceRuleSetName)) + query, language); - } - else { - it = d->model()->executeQuery(query, language, userQueryLanguage); - } - setError( d->model()->lastError() ); - return it; -} - - -bool Nepomuk::MainModel::containsStatement( const Statement& statement ) const -{ - bool b = d->model()->containsStatement( statement ); - setError( d->model()->lastError() ); - return b; -} - - -bool Nepomuk::MainModel::containsAnyStatement( const Statement &statement ) const -{ - bool b = d->model()->containsAnyStatement( statement ); - setError( d->model()->lastError() ); - return b; -} - - -bool Nepomuk::MainModel::isEmpty() const -{ - bool b = d->model()->isEmpty(); - setError( d->model()->lastError() ); - return b; -} - - -int Nepomuk::MainModel::statementCount() const -{ - int c = d->model()->statementCount(); - setError( d->model()->lastError() ); - return c; -} - - -Soprano::Error::ErrorCode Nepomuk::MainModel::addStatement( const Statement& statement ) -{ - Soprano::Error::ErrorCode c = d->model()->addStatement( statement ); - setError( d->model()->lastError() ); - return c; -} - - -Soprano::Error::ErrorCode Nepomuk::MainModel::removeStatement( const Statement& statement ) -{ - Soprano::Error::ErrorCode c = d->model()->removeStatement( statement ); - setError( d->model()->lastError() ); - return c; -} - - -Soprano::Error::ErrorCode Nepomuk::MainModel::removeAllStatements( const Statement& statement ) -{ - Soprano::Error::ErrorCode c = d->model()->removeAllStatements( statement ); - setError( d->model()->lastError() ); - return c; -} - - -Soprano::Node Nepomuk::MainModel::createBlankNode() -{ - Soprano::Node n = d->model()->createBlankNode(); - setError( d->model()->lastError() ); - return n; -} - -#include "nepomukmainmodel.moc" diff --git a/nepomuk/core/nepomukmainmodel.h b/nepomuk/core/nepomukmainmodel.h deleted file mode 100644 index 5313c56b..00000000 --- a/nepomuk/core/nepomukmainmodel.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2008-2010 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_MAIN_MODEL_H_ -#define _NEPOMUK_MAIN_MODEL_H_ - -#include -#include - -#include - -namespace Nepomuk { - /** - * \class MainModel nepomukmainmodel.h Nepomuk/MainModel - * - * \brief The main %Nepomuk data storage model. - * - * All user data is stored in the %Nepomuk main model. - * This is a wrapper model which communicates all commands - * to the %Nepomuk server. - * - * Usage is very simple. Just create an instance and start - * using it. Use the isValid method to check the connection - * to the server. All communication details are handled transparently. - * - * It is perfectly alright to create several instances of MainModel - * in one application as internally all is mapped to a single global - * instance which is also reused in ResourceManager::mainModel. - * - * Provides a set of convenience methods - * for maintaining resource properties. - * - * It does automatic NRL named graph handling, i.e. provedance - * data is created and deleted automatically. - * - * \warning This model assumes that no property value is stored twice, - * i.e. in two different named graphs. - * - * \author Sebastian Trueg - * - * \since 4.2 - * - * \sa ResourceManager::mainModel() - */ - class MainModel : public Soprano::Model - { - Q_OBJECT - - public: - /** - * Create a new main model. - */ - MainModel( QObject* parent = 0 ); - - /** - * Destructor. - */ - ~MainModel(); - - /** - * Check the connection to the %Nepomuk server. - * \return \p true if the connection is valid and commands can be issued, - * \p false otherwise. - */ - bool isValid() const; - - /** - * Try connecting to the Nepomuk storage service. There is no need to call - * this unless one wants to reconnect to a previously non-running system. - * All methods below do connect automatically but do not retry after a - * failure. - */ - bool init(); - - /** - * This function explicitly marks the connection to soprano as disconnected. - * - * This is necessary because the soprano method isConnected() - * does not check if the socket is actually connected, - * merely if it were successfully connected at some point in the past. - * If the socket has been remote disconnected, we need to mark it as so. - */ - void disconnect(); - - Soprano::StatementIterator listStatements( const Soprano::Statement &partial ) const; - Soprano::NodeIterator listContexts() const; - Soprano::QueryResultIterator executeQuery( const QString& query, - Soprano::Query::QueryLanguage language, - const QString& userQueryLanguage = QString() ) const; - bool containsStatement( const Soprano::Statement &statement ) const; - bool containsAnyStatement( const Soprano::Statement &statement ) const; - bool isEmpty() const; - int statementCount() const; - Soprano::Error::ErrorCode addStatement( const Soprano::Statement& statement ); - Soprano::Error::ErrorCode removeStatement( const Soprano::Statement& statement ); - Soprano::Error::ErrorCode removeAllStatements( const Soprano::Statement& statement ); - Soprano::Node createBlankNode(); - - using Model::addStatement; - using Model::removeStatement; - using Model::removeAllStatements; - - private: - class Private; - Private* const d; - }; -} - -#endif diff --git a/nepomuk/core/nepomukservice.cpp b/nepomuk/core/nepomukservice.cpp deleted file mode 100644 index 196cbf9c..00000000 --- a/nepomuk/core/nepomukservice.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* This file is part of the KDE Project - Copyright (c) 2008 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "nepomukservice.h" -#include "resourcemanager.h" - -#include - - -class Nepomuk::Service::Private -{ -public: -}; - - -Nepomuk::Service::Service( QObject* parent, bool delayedInitialization ) - : QObject( parent ), - d( new Private() ) -{ - if ( !delayedInitialization ) { - setServiceInitialized( true ); - } -} - - -Nepomuk::Service::~Service() -{ - delete d; -} - - -Soprano::Model* Nepomuk::Service::mainModel() -{ - return ResourceManager::instance()->mainModel(); -} - - -void Nepomuk::Service::setServiceInitialized( bool success ) -{ - // the parent will always be a control class in the service stub - QMetaObject::invokeMethod( parent(), - "setServiceInitialized", - Qt::QueuedConnection, // needs to be queued to give the service time to register with DBus - Q_ARG(bool, success) ); -} - -#include "nepomukservice.moc" diff --git a/nepomuk/core/nepomukservice.h b/nepomuk/core/nepomukservice.h deleted file mode 100644 index a8e0302d..00000000 --- a/nepomuk/core/nepomukservice.h +++ /dev/null @@ -1,145 +0,0 @@ -/* This file is part of the KDE Project - Copyright (c) 2008 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_SERVICE_H_ -#define _NEPOMUK_SERVICE_H_ - -#include -#include "nepomuk_export.h" - -namespace Soprano { - class Model; -} - -namespace Nepomuk { - /** - * \class Service nepomukservice.h Nepomuk/Service - * - * \brief Base class for all Nepomuk services. - * - * A %Nepomuk service is intended to perform some kind of - * operation on the %Nepomuk data storage. This can include - * data gathering, data enrichment, or enhanced data query. - * - * %Nepomuk services are started and managed by the %Nepomuk - * server. Very much like KDED modules a %Nepomuk service - * has autostart and start-on-demand properties. In addition - * a %Nepomuk service can define an arbitrary number of - * dependencies which are necessary to run the service. These - * dependencies name other services. - * - * To create a new %Nepomuk service one derives a new class from - * Nepomuk::Service and exports it as a standard KDE module, i.e. - * plugin. - * - * \code - * class MyService : public Nepomuk::Service - * { - * // do fancy stuff - * }; - * \endcode - * - * Export it as a %Nepomuk service plugin: - * - * \code - * NEPOMUK_EXPORT_SERVICE(MyService, "mynepomukservice") - * \endcode - * - * A desktop file describes the service's properties: - * - * \code - * [Desktop Entry] - * Type=Service - * X-KDE-ServiceTypes=NepomukService - * X-KDE-Library=mynepomukservice - * X-KDE-Nepomuk-autostart=true - * X-KDE-Nepomuk-start-on-demand=false - * # Dependencies default to 'nepomukstorage' - * X-KDE-Nepomuk-dependencies=nepomukfoobar - * Name=My fancy Nepomuk Service - * Comment=A Nepomuk service that does fancy things - * \endcode - * - * The %Nepomuk server will automatically export all D-Bus - * interfaces defined on the service instance. Thus, the - * simplest way to export methods via D-Bus is by marking - * them with Q_SCRIPTABLE. - * - * \author Sebastian Trueg - * - * \since 4.1 - */ - class NEPOMUK_EXPORT Service : public QObject - { - Q_OBJECT - - public: - /** - * Create a new Service. - * - * \param parent The parent object - * \param delayedInitialization If \p true the service will not - * be usable until setServiceInitialized has been called. - * This allows to design services that need to perform - * long initialization tasks. - */ - Service( QObject* parent = 0, bool delayedInitialization = false ); - - /** - * Destructor - */ - virtual ~Service(); - - protected: - /** - * \return A wrapper model which provides - * a connection to the %Nepomuk server. - */ - Soprano::Model* mainModel(); - - /** - * A %Nepomuk service can make use of a warmup phase in which - * it is not usable yet. Call this method once your service - * is fully initialized. - * - * Most services do not need to call this method. - * - * \param success Set to \c true if initialization was - * successful, \c false otherwise. - * - * \sa Service::Service - */ - void setServiceInitialized( bool success ); - - private: - class Private; - Private* const d; - }; -} - -/** - * Export a %Nepomuk service. - * - * \param classname The name of the Nepomuk::Service subclass to export. - * \param libname The name of the library which should export the service. - */ -#define NEPOMUK_EXPORT_SERVICE( classname, libname ) \ -K_PLUGIN_FACTORY(factory, registerPlugin();) \ -K_EXPORT_PLUGIN(factory(#libname)) - -#endif diff --git a/nepomuk/core/org.kde.nepomuk.ResourceWatcher.xml b/nepomuk/core/org.kde.nepomuk.ResourceWatcher.xml deleted file mode 100644 index 7f414443..00000000 --- a/nepomuk/core/org.kde.nepomuk.ResourceWatcher.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/nepomuk/core/org.kde.nepomuk.ResourceWatcherConnection.xml b/nepomuk/core/org.kde.nepomuk.ResourceWatcherConnection.xml deleted file mode 100644 index 4ec24f19..00000000 --- a/nepomuk/core/org.kde.nepomuk.ResourceWatcherConnection.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nepomuk/core/resource.cpp b/nepomuk/core/resource.cpp deleted file mode 100644 index 21ad1ce1..00000000 --- a/nepomuk/core/resource.cpp +++ /dev/null @@ -1,1020 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2010 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "resource.h" -#include "resourcedata.h" -#include "resourcemanager.h" -#include "resourcemanager_p.h" -#include "tools.h" -#include "tag.h" -#include "pimo.h" -#include "thing.h" -#include "file.h" -#include "property.h" -#include "nfo.h" -#include "nie.h" -#include "nco.h" -#include "nuao.h" - -#include "klocale.h" -#include "kdebug.h" -#include "kurl.h" -#include "kmimetype.h" - -#include -#include -#include -#include -#include - -using namespace Soprano::Vocabulary; -using namespace Nepomuk::Vocabulary; - -Nepomuk::Resource::Resource() -{ - QMutexLocker lock( &ResourceManager::instance()->d->mutex ); - m_data = ResourceManager::instance()->d->data( QUrl(), QUrl() ); - if ( m_data ) - m_data->ref( this ); -} - - -Nepomuk::Resource::Resource( ResourceManager* manager ) -{ - if(!manager) - manager = ResourceManager::instance(); - QMutexLocker lock( &manager->d->mutex ); - m_data = manager->d->data( QUrl(), QUrl() ); - if ( m_data ) - m_data->ref( this ); -} - - -Nepomuk::Resource::Resource( const Nepomuk::Resource& res ) -{ - QMutexLocker lock( &res.m_data->rm()->mutex ); - m_data = res.m_data; - if ( m_data ) - m_data->ref( this ); -} - - -Nepomuk::Resource::Resource( const QString& uri, const QUrl& type ) -{ - QMutexLocker lock( &ResourceManager::instance()->d->mutex ); - m_data = ResourceManager::instance()->d->data( uri, type ); - if ( m_data ) - m_data->ref( this ); -} - - -Nepomuk::Resource::Resource( const QString& uri, const QUrl& type, ResourceManager* manager ) -{ - if(!manager) - manager = ResourceManager::instance(); - QMutexLocker lock( &manager->d->mutex ); - m_data = manager->d->data( uri, type ); - if ( m_data ) - m_data->ref( this ); -} - - -#ifndef KDE_NO_DEPRECATED -Nepomuk::Resource::Resource( const QString& uri, const QString& type ) -{ - QMutexLocker lock( &ResourceManager::instance()->d->mutex ); - m_data = ResourceManager::instance()->d->data( uri, type ); - if ( m_data ) - m_data->ref( this ); -} -#endif - - -Nepomuk::Resource::Resource( const QUrl& uri, const QUrl& type ) -{ - QMutexLocker lock( &ResourceManager::instance()->d->mutex ); - m_data = ResourceManager::instance()->d->data( uri, type ); - if ( m_data ) - m_data->ref( this ); -} - - -Nepomuk::Resource::Resource( const QUrl& uri, const QUrl& type, ResourceManager* manager ) -{ - if(!manager) - manager = ResourceManager::instance(); - QMutexLocker lock( &manager->d->mutex ); - m_data = manager->d->data( uri, type ); - if ( m_data ) - m_data->ref( this ); -} - - -Nepomuk::Resource::Resource( Nepomuk::ResourceData* data ) -{ - QMutexLocker lock( &data->rm()->mutex ); - m_data = data; - if ( m_data ) - m_data->ref( this ); -} - - -Nepomuk::Resource::~Resource() -{ - if ( m_data ) { - QMutexLocker lock(&m_data->rm()->mutex); - m_data->deref( this ); - if ( m_data->rm()->shouldBeDeleted( m_data ) ) - delete m_data; - } -} - - -Nepomuk::Resource& Nepomuk::Resource::operator=( const Resource& res ) -{ - if( m_data != res.m_data ) { - QMutexLocker lock(&m_data->rm()->mutex); - if ( m_data && !m_data->deref( this ) && m_data->rm()->shouldBeDeleted( m_data ) ) { - delete m_data; - } - m_data = res.m_data; - if ( m_data ) - m_data->ref( this ); - } - - return *this; -} - - -Nepomuk::Resource& Nepomuk::Resource::operator=( const QUrl& res ) -{ - return operator=( Resource( res ) ); -} - - -Nepomuk::ResourceManager* Nepomuk::Resource::manager() const -{ - return m_data->rm()->m_manager; -} - - -#ifndef KDE_NO_DEPRECATED -QString Nepomuk::Resource::uri() const -{ - return resourceUri().toString(); -} -#endif - - -QUrl Nepomuk::Resource::resourceUri() const -{ - if ( m_data ) { - determineFinalResourceData(); - return m_data->uri(); - } - else { - return QUrl(); - } -} - - -#ifndef KDE_NO_DEPRECATED -QString Nepomuk::Resource::type() const -{ - return resourceType().toString(); -} -#endif - - -QUrl Nepomuk::Resource::resourceType() const -{ - determineFinalResourceData(); - return m_data->type(); -} - - -QList Nepomuk::Resource::types() const -{ - determineFinalResourceData(); - return m_data->allTypes(); -} - - -void Nepomuk::Resource::setTypes( const QList& types ) -{ - determineFinalResourceData(); - m_data->setTypes( types ); -} - - -void Nepomuk::Resource::addType( const QUrl& type ) -{ - QList tl = types(); - if( !tl.contains( type ) ) - setTypes( tl << type ); -} - - -bool Nepomuk::Resource::hasType( const QUrl& typeUri ) const -{ - determineFinalResourceData(); - return m_data->hasType( typeUri ); -} - - -QString Nepomuk::Resource::className() const -{ - return resourceType().toString().section( QRegExp( "[#:]" ), -1 ); -} - - -QHash Nepomuk::Resource::properties() const -{ - determineFinalResourceData(); - return m_data->allProperties(); -} - - -#ifndef KDE_NO_DEPRECATED -QHash Nepomuk::Resource::allProperties() const -{ - QHash pl; - QHash p = properties(); - QHash::const_iterator end = p.constEnd(); - for ( QHash::const_iterator it = p.constBegin(); - it != end; ++it ) { - pl.insert( it.key().toString(), it.value() ); - } - return pl; -} -#endif - - -bool Nepomuk::Resource::hasProperty( const QUrl& uri ) const -{ - determineFinalResourceData(); - return m_data->hasProperty( uri ); -} - - -bool Nepomuk::Resource::hasProperty( const Types::Property& p, const Variant& v ) const -{ - determineFinalResourceData(); - return m_data->hasProperty( p.uri(), v ); -} - - -#ifndef KDE_NO_DEPRECATED -bool Nepomuk::Resource::hasProperty( const QString& uri ) const -{ - return hasProperty( QUrl( uri ) ); -} -#endif - - -#ifndef KDE_NO_DEPRECATED -Nepomuk::Variant Nepomuk::Resource::property( const QString& uri ) const -{ - return property( QUrl( uri ) ); -} -#endif - - -Nepomuk::Variant Nepomuk::Resource::property( const QUrl& uri ) const -{ - determineFinalResourceData(); - return m_data->property( uri ); -} - - -#ifndef KDE_NO_DEPRECATED -void Nepomuk::Resource::setProperty( const QString& uri, const Nepomuk::Variant& value ) -{ - setProperty( QUrl( uri ), value ); -} -#endif - - -void Nepomuk::Resource::addProperty( const QUrl& uri, const Variant& value ) -{ - determineFinalResourceData(); - m_data->addProperty( uri, value ); -} - - -void Nepomuk::Resource::setProperty( const QUrl& uri, const Nepomuk::Variant& value ) -{ - determineFinalResourceData(); - m_data->setProperty( uri, value ); -} - - -#ifndef KDE_NO_DEPRECATED -void Nepomuk::Resource::removeProperty( const QString& uri ) -{ - removeProperty( QUrl( uri ) ); -} -#endif - - -void Nepomuk::Resource::removeProperty( const QUrl& uri ) -{ - determineFinalResourceData(); - m_data->removeProperty( uri ); -} - - -void Nepomuk::Resource::removeProperty( const QUrl& uri, const Variant& value ) -{ - QList vl = property( uri ).toVariantList(); - foreach( const Variant& v, value.toVariantList() ) { - vl.removeAll( v ); - } - setProperty( uri, Variant( vl ) ); -} - - -void Nepomuk::Resource::remove() -{ - determineFinalResourceData(); - m_data->remove(); -} - - -bool Nepomuk::Resource::exists() const -{ - determineFinalResourceData(); - if ( m_data ) { - return m_data->exists(); - } - else { - return false; - } -} - - -bool Nepomuk::Resource::isValid() const -{ - return m_data ? m_data->isValid() : false; -} - - -// TODO: cache this one in ResourceData -QString Nepomuk::Resource::genericLabel() const -{ - QString label = this->label(); - if(!label.isEmpty()) - return label; - - label = property( Soprano::Vocabulary::RDFS::label() ).toString(); - if(!label.isEmpty()) - return label; - - label = property( Nepomuk::Vocabulary::NIE::title() ).toString(); - if(!label.isEmpty()) - return label; - - label = property( Nepomuk::Vocabulary::NCO::fullname() ).toString(); - if(!label.isEmpty()) - return label; - - label = property( Soprano::Vocabulary::NAO::identifier() ).toString(); - if(!label.isEmpty()) - return label; - - label = m_data->pimoThing().label(); - if(!label.isEmpty()) - return label; - - label = property( Nepomuk::Vocabulary::NFO::fileName() ).toString(); - if(!label.isEmpty()) - return label; - - const KUrl nieUrl = property( Nepomuk::Vocabulary::NIE::url() ).toUrl(); - if(!nieUrl.isEmpty()) { - if(nieUrl.isLocalFile()) - return nieUrl.fileName(); - else - return nieUrl.prettyUrl(); - } - - QList go = property( Vocabulary::PIMO::groundingOccurrence() ).toResourceList(); - if( !go.isEmpty() ) { - label = go.first().genericLabel(); - if( label != KUrl(go.first().resourceUri()).pathOrUrl() ) { - return label; - } - } - - QString hashValue = property( Vocabulary::NFO::hashValue() ).toString(); - if( !hashValue.isEmpty() ) - return hashValue; - - // ugly fallback - return KUrl(resourceUri()).pathOrUrl(); -} - - -QString Nepomuk::Resource::genericDescription() const -{ - QString s = property( Soprano::Vocabulary::NAO::description() ).toString(); - if ( !s.isEmpty() ) { - return s; - } - - s = property( Soprano::Vocabulary::Xesam::summary() ).toString(); - if ( !s.isEmpty() ) { - return s; - } - - s = property( Soprano::Vocabulary::Xesam::description() ).toString(); - if ( !s.isEmpty() ) { - return s; - } - - s = property( Soprano::Vocabulary::Xesam::asText() ).toString(); - if ( !s.isEmpty() ) { - return s; - } - - s = property( Soprano::Vocabulary::RDFS::comment() ).toString(); - - return s; -} - - -QString Nepomuk::Resource::genericIcon() const -{ - if( hasType(NAO::FreeDesktopIcon()) ) { - QString label = property(NAO::iconName()).toString(); - if( !label.isEmpty() ) - return label; - - label = property(NAO::prefLabel()).toString(); - if( !label.isEmpty() ) - return label; - } - - // Symbol Resources - Variant symbol = property( NAO::hasSymbol() ); - if( symbol.isResource() ) { - QString icon = symbol.toResource().genericIcon(); - if(!icon.isEmpty()) - return icon; - } - else if( symbol.isString() ) { - // Backward compatibiltiy - QString icon = symbol.toString(); - if( !icon.isEmpty() ) - return icon; - } - - // FIXME: NAO::prefSymbol is a sub-property of nao:hasSymbol, it should be auto detected - symbol = property( NAO::prefSymbol() ); - if( symbol.isResource() ) { - QString icon = symbol.toResource().genericIcon(); - if(!icon.isEmpty()) - return icon; - } - else if( symbol.isString() ) { - // Backward compatibiltiy - QString icon = symbol.toString(); - if( !icon.isEmpty() ) - return icon; - } - - QString mimeType = property( NIE::mimeType() ).toString(); - if( !mimeType.isEmpty() ) { - if( KMimeType::Ptr m = KMimeType::mimeType( mimeType ) ) - return m->iconName(); - } - - return QString(); -} - - -Nepomuk::Thing Nepomuk::Resource::pimoThing() -{ - determineFinalResourceData(); - return m_data->pimoThing(); -} - - -bool Nepomuk::Resource::operator==( const Resource& other ) const -{ - if( this == &other ) - return true; - - if( this->m_data == other.m_data ) - return true; - - if ( !m_data || !other.m_data ) { - return false; - } - - // get the resource URIs since two different ResourceData instances - // can still represent the same Resource - determineFinalResourceData(); - other.determineFinalResourceData(); - - if( m_data->uri().isEmpty() ) - return *m_data == *other.m_data; - else - return resourceUri() == other.resourceUri(); -} - - -bool Nepomuk::Resource::operator!=( const Resource& other ) const -{ - return !operator==( other ); -} - - -QString Nepomuk::errorString( ErrorCode code ) -{ - switch( code ) { - case NoError: - return i18n("Success"); - case CommunicationError: - return i18n("Communication error"); - case InvalidType: - return i18n("Invalid type in Database"); - default: - return i18n("Unknown error"); - } -} - - -QString Nepomuk::Resource::description() const -{ - return ( property( Soprano::Vocabulary::NAO::description() ).toStringList() << QString() ).first(); -} - - -void Nepomuk::Resource::setDescription( const QString& value ) -{ - setProperty( Soprano::Vocabulary::NAO::description(), Variant( value ) ); -} - - -QString Nepomuk::Resource::descriptionUri() -{ - return Soprano::Vocabulary::NAO::description().toString(); -} - - -QStringList Nepomuk::Resource::identifiers() const -{ - return property( Soprano::Vocabulary::NAO::identifier() ).toStringList(); -} - - -void Nepomuk::Resource::setIdentifiers( const QStringList& value ) -{ - setProperty( Soprano::Vocabulary::NAO::identifier(), Variant( value ) ); -} - - -void Nepomuk::Resource::addIdentifier( const QString& value ) -{ - Variant v = property( Soprano::Vocabulary::NAO::identifier() ); - v.append( value ); - setProperty( Soprano::Vocabulary::NAO::identifier(), v ); -} - - -QString Nepomuk::Resource::identifierUri() -{ - return Soprano::Vocabulary::NAO::identifier().toString(); -} - - -QStringList Nepomuk::Resource::altLabels() const -{ - return property( Soprano::Vocabulary::NAO::altLabel() ).toStringList(); -} - - -void Nepomuk::Resource::setAltLabels( const QStringList& value ) -{ - setProperty( Soprano::Vocabulary::NAO::altLabel(), Variant( value ) ); -} - - -void Nepomuk::Resource::addAltLabel( const QString& value ) -{ - Variant v = property( Soprano::Vocabulary::NAO::altLabel() ); - v.append( value ); - setProperty( Soprano::Vocabulary::NAO::altLabel(), v ); -} - - -QString Nepomuk::Resource::altLabelUri() -{ - return Soprano::Vocabulary::NAO::altLabel().toString(); -} - - -QList Nepomuk::Resource::annotations() const -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - return convertResourceList( property( Soprano::Vocabulary::NAO::annotation() ).toResourceList() ); -} - - -void Nepomuk::Resource::setAnnotations( const QList& value ) -{ - setProperty( Soprano::Vocabulary::NAO::annotation(), Variant( value ) ); -} - - -void Nepomuk::Resource::addAnnotation( const Nepomuk::Resource& value ) -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - Variant v = property( Soprano::Vocabulary::NAO::annotation() ); - v.append( Resource( value ) ); - setProperty( Soprano::Vocabulary::NAO::annotation(), v ); -} - - -QString Nepomuk::Resource::annotationUri() -{ - return Soprano::Vocabulary::NAO::annotation().toString(); -} - - -QList Nepomuk::Resource::tags() const -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - return convertResourceList( property( Soprano::Vocabulary::NAO::hasTag() ).toResourceList() ); -} - - -void Nepomuk::Resource::setTags( const QList& value ) -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - QList l; - for( QList::const_iterator it = value.constBegin(); - it != value.constEnd(); ++it ) { - l.append( Resource( (*it) ) ); - } - setProperty( Soprano::Vocabulary::NAO::hasTag(), Variant( l ) ); -} - - -void Nepomuk::Resource::addTag( const Nepomuk::Tag& value ) -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - Variant v = property( Soprano::Vocabulary::NAO::hasTag() ); - v.append( Resource( value ) ); - setProperty( Soprano::Vocabulary::NAO::hasTag(), v ); -} - - -QString Nepomuk::Resource::tagUri() -{ - return Soprano::Vocabulary::NAO::hasTag().toString(); -} - - -QList Nepomuk::Resource::topics() const -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - return convertResourceList( property( Soprano::Vocabulary::NAO::hasTopic() ).toResourceList() ); -} - - -void Nepomuk::Resource::setTopics( const QList& value ) -{ - setProperty( Soprano::Vocabulary::NAO::hasTopic(), Variant( value ) ); -} - - -void Nepomuk::Resource::addTopic( const Nepomuk::Resource& value ) -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - Variant v = property( Soprano::Vocabulary::NAO::hasTopic() ); - v.append( Resource( value ) ); - setProperty( Soprano::Vocabulary::NAO::hasTopic(), v ); -} - - -QString Nepomuk::Resource::topicUri() -{ - return Soprano::Vocabulary::NAO::hasTopic().toString(); -} - - -QList Nepomuk::Resource::isTopicOfs() const -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - return convertResourceList( property( Soprano::Vocabulary::NAO::isTopicOf() ).toResourceList() ); -} - - -void Nepomuk::Resource::setIsTopicOfs( const QList& value ) -{ - setProperty( Soprano::Vocabulary::NAO::isTopicOf(), Variant( value ) ); -} - - -void Nepomuk::Resource::addIsTopicOf( const Nepomuk::Resource& value ) -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - Variant v = property( Soprano::Vocabulary::NAO::isTopicOf() ); - v.append( Resource( value ) ); - setProperty( Soprano::Vocabulary::NAO::isTopicOf(), v ); -} - - -QString Nepomuk::Resource::isTopicOfUri() -{ - return Soprano::Vocabulary::NAO::isTopicOf().toString(); -} - - -QList Nepomuk::Resource::isRelateds() const -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - return convertResourceList( property( Soprano::Vocabulary::NAO::isRelated() ).toResourceList() ); -} - - -void Nepomuk::Resource::setIsRelateds( const QList& value ) -{ - setProperty( Soprano::Vocabulary::NAO::isRelated(), Variant( value ) ); -} - - -void Nepomuk::Resource::addIsRelated( const Nepomuk::Resource& value ) -{ - // We always store all Resource types as plain Resource objects. - // It does not introduce any overhead (due to the implicit sharing of - // the data and has the advantage that we can mix setProperty calls - // with the special Resource subclass methods. - // More importantly Resource loads the data as Resource objects anyway. - Variant v = property( Soprano::Vocabulary::NAO::isRelated() ); - v.append( Resource( value ) ); - setProperty( Soprano::Vocabulary::NAO::isRelated(), v ); -} - - -QString Nepomuk::Resource::isRelatedUri() -{ - return Soprano::Vocabulary::NAO::isRelated().toString(); -} - - -QString Nepomuk::Resource::label() const -{ - return ( property( Soprano::Vocabulary::NAO::prefLabel() ).toStringList() << QString() ).first(); -} - - -void Nepomuk::Resource::setLabel( const QString& value ) -{ - setProperty( Soprano::Vocabulary::NAO::prefLabel(), Variant( value ) ); -} - - -QString Nepomuk::Resource::labelUri() -{ - return Soprano::Vocabulary::NAO::prefLabel().toString(); -} - - -quint32 Nepomuk::Resource::rating() const -{ - return ( property( Soprano::Vocabulary::NAO::numericRating() ).toUnsignedIntList() << 0 ).first(); -} - - -void Nepomuk::Resource::setRating( const quint32& value ) -{ - setProperty( Soprano::Vocabulary::NAO::numericRating(), Variant( value ) ); -} - - -QString Nepomuk::Resource::ratingUri() -{ - return Soprano::Vocabulary::NAO::numericRating().toString(); -} - - -QStringList Nepomuk::Resource::symbols() const -{ - QList symbolResources = property( Soprano::Vocabulary::NAO::hasSymbol() ).toResourceList(); - - QStringList symbolStrings; - foreach(const Nepomuk::Resource& symbolRes, symbolResources ) { - symbolStrings << symbolRes.label(); - } - - return symbolStrings; -} - -namespace { - QUrl uriForSymbolName(const QString& symbolName) { - // Check if it exists - // We aren't using Soprano::Node::literalToN3 cause prefLabel has a range of a literal not - // of a string - QString query = QString::fromLatin1("select ?r where { ?r a %1 . ?r %2 \"%3\" . } LIMIT 1") - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::FreeDesktopIcon()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::iconName()), - symbolName ); - - Soprano::Model* model = Nepomuk::ResourceManager::instance()->mainModel(); - Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql ); - if( it.next() ) { - return it["r"].uri(); - } - else { - Nepomuk::Resource res(QUrl(), Soprano::Vocabulary::NAO::FreeDesktopIcon()); - res.setProperty( NAO::iconName(), symbolName ); - - return res.resourceUri(); - } - } -} - -void Nepomuk::Resource::setSymbols( const QStringList& value ) -{ - QList symbolList; - foreach( const QString& symbolName, value ) { - symbolList << uriForSymbolName(symbolName); - } - - setProperty( Soprano::Vocabulary::NAO::hasSymbol(), Variant(symbolList) ); -} - - -void Nepomuk::Resource::addSymbol( const QString& value ) -{ - Variant v = property( Soprano::Vocabulary::NAO::hasSymbol() ); - v.append( uriForSymbolName(value) ); - setProperty( Soprano::Vocabulary::NAO::hasSymbol(), v ); -} - - -QString Nepomuk::Resource::symbolUri() -{ - return Soprano::Vocabulary::NAO::hasSymbol().toString(); -} - - -QList Nepomuk::Resource::annotationOf() const -{ - return convertResourceList( manager()->allResourcesWithProperty( Soprano::Vocabulary::NAO::annotation(), *this ) ); -} - - -QList Nepomuk::Resource::isRelatedOf() const -{ - return convertResourceList( manager()->allResourcesWithProperty( Soprano::Vocabulary::NAO::isRelated(), *this ) ); -} - - -// static -QList Nepomuk::Resource::allResources() -{ - return Nepomuk::convertResourceList( ResourceManager::instance()->allResourcesOfType( Soprano::Vocabulary::RDFS::Resource() ) ); -} - - -int Nepomuk::Resource::usageCount() const -{ - return property( Vocabulary::NUAO::usageCount() ).toInt(); -} - - -void Nepomuk::Resource::increaseUsageCount() -{ - int cnt = 0; - const QDateTime now = QDateTime::currentDateTime(); - if( hasProperty( Vocabulary::NUAO::usageCount() ) ) - cnt = property( Vocabulary::NUAO::usageCount() ).toInt(); - else - setProperty( Vocabulary::NUAO::firstUsage(), now ); - ++cnt; - setProperty( Vocabulary::NUAO::usageCount(), cnt ); - setProperty( Vocabulary::NUAO::lastUsage(), now ); -} - - -bool Nepomuk::Resource::isFile() const -{ - if( m_data ) { - determineFinalResourceData(); - m_data->load(); - return m_data->isFile(); - } - else { - return false; - } -} - - -Nepomuk::File Nepomuk::Resource::toFile() const -{ - return File( *this ); -} - - -// static -Nepomuk::Resource Nepomuk::Resource::fromResourceUri( const KUrl& uri, const Nepomuk::Types::Class& type, ResourceManager* manager ) -{ - if( !manager ) - manager = ResourceManager::instance(); - QMutexLocker lock( &manager->d->mutex ); - return Resource( manager->d->dataForResourceUri( uri, type.uri() ) ); -} - - -void Nepomuk::Resource::determineFinalResourceData() const -{ - QMutexLocker lock( &m_data->rm()->mutex ); - - // Get an initialized ResourceData instance - ResourceData* oldData = m_data; - ResourceData* newData = m_data->determineUri(); - - Q_ASSERT(oldData); - Q_ASSERT(newData); - - // in case we get an already existing one we update all instances - // using the old ResourceData to avoid the overhead of calling - // determineUri over and over - if( newData != oldData ) { - Q_FOREACH( Resource* res, m_data->m_resources) { - res->m_data = newData; - oldData->deref( res ); - newData->ref( res ); - } - } - - if ( !oldData->cnt() ) - delete oldData; -} - - -uint Nepomuk::qHash( const Resource& res ) -{ - return qHash(res.resourceUri()); -} diff --git a/nepomuk/core/resource.h b/nepomuk/core/resource.h deleted file mode 100644 index c35b835e..00000000 --- a/nepomuk/core/resource.h +++ /dev/null @@ -1,810 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2009 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_RESOURCE_H_ -#define _NEPOMUK_RESOURCE_H_ - -#include -#include - -#include - -#include "class.h" - -#include "nepomuk_export.h" - -namespace Nepomuk { - - class ResourceManager; - class ResourceData; - class Variant; - class Tag; - class Thing; - class File; - namespace Types { - class Property; - } - - enum ErrorCode { - NoError = 0, - CommunicationError, /**< A communication error, i.e. connection failure */ - InvalidType, - UnknownError - }; - - /** - * \return A human-readble string. - */ - // FIXME: add the uri of the resource as parameter - NEPOMUK_EXPORT QString errorString( ErrorCode code ); - - /** - * \class Resource resource.h Nepomuk/Resource - * - * \brief Resource is the central object type in Nepomuk. It represents a piece of - * information of any kind. - * - * Resources are identified by their unique URI (which - * correlates directly with the URI in the local NEPOMUK RDF storage. - * - * Resource objects with the same URI share their data. - * - * All methods in Resource are thread-safe. - * - * See \ref hacking for details on how to use Resource. - * - * \see ResourceManager - * - * \section nepomuk_resource_file_uris Special case: file URLs - * - * \p file:/ URLs are handled as a special case in Nepomuk. Starting with KDE 4.4 - * they are no longer used to identify the Nepomuk resource but only stored as - * nie:url property. All resources have \p nepomuk:/res/ URIs. The Resource - * constructors handle this automatically. Thus, one can still use file URLs to - * construct the objects. But be aware of the following example: - * - * \code - * KUrl fileUrl("file:///home/foobar/example.txt"); - * Nepomuk::Resource fileRes(fileUrl); - * QUrl fileResUri = fileRes.resourceUri(); - * \endcode - * - * Here \p fileUrl and \p fileResUri are NOT equal. The latter is the resource URI - * of the form \p nepomuk:/res/. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT Resource - { - public: - /** - * Creates an empty invalid Resource. - * An invalid resource will become valid (i.e. get a new random URI) once setProperty - * is called. - */ - Resource(); - - /** - * Creates an empty invalid Resource. - * An invalid resource will become valid (i.e. get a new random URI) once setProperty - * is called. - * - * \param manager The resource manager to use. This allows to mix resources from different - * managers and, thus, different models. - * - * \since 4.3 - */ - Resource( ResourceManager* manager ); - - /** - * Copy constructor - */ - Resource( const Resource& ); - - /** - * Creates a new Resource object. - * - * The actual resource data is loaded on demand. Thus, it is possible to work - * with Resources as if they were in memory all the time. - * - * \param pathOrIdentifier The path to a file or an arbitrary identifier of the resource. - * The following cases are handled: - * \li A local file path is converted to a local file URL - * \li A URI which already exist in Nepomuk results in loading of that particular resource. - * \li A string which already exists as the nao:identifier of a resource results in loading - * of that particular resource. - * \li Any other string is used as nao:identifier for a new resource. This resource can - * later be loaded again by using the same identifier with this constructor. - * - * \param type The URI identifying the type of the resource. If it is empty - * Resource falls back to http://www.w3.org/2000/01/rdf-schema\#Resource or - * in case the resource already exists the type will be read from the - * store. - * - * Example: - * - * The best way to understand the path or identifier system is through tags. - * There are two ways to create a resource that represents an existing tag. The first is the - * low level one: use the unique URI of the tag with the Resource(QUrl,QUrl) constructor. - * The second one is to use this constructor with the name of the tag as its identifier: - * - * \code - * Resource myTag( "Nepomuk" ); - * \endcode - * - * This will result in Resource loading the tag with nao:identifier "Nepomuk". - */ - Resource( const QString& pathOrIdentifier, const QUrl& type = QUrl() ); - - /** - * \overload - * - * \param manager The resource manager to use. This allows to mix resources from different - * managers and, thus, different models. - * - * \since 4.3 - */ - Resource( const QString& pathOrIdentifier, const QUrl& type, ResourceManager* manager ); - - /** - * \deprecated use Resource( const QString&, const QUrl& ) - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED Resource( const QString& pathOrIdentifier, const QString& type ); -#endif - - /** - * Creates a new Resource object. - * - * \param uri The URI of the resource. If no resource with this URI exists, a new one is - * created. Using an empty QUrl will result in a new resource with a random URI being created - * on the first call to setProperty. - * - * See the \ref nepomuk_resource_file_uris Special file URL handling. - * - * \param type The URI identifying the type of the resource. If it is empty - * Resource falls back to http://www.w3.org/2000/01/rdf-schema\#Resource or - * in case the resource already exists the type will be read from the - * store. - */ - Resource( const QUrl& uri, const QUrl& type = QUrl() ); - - /** - * \overload - * - * \param manager The resource manager to use. This allows to mix resources from different - * managers and, thus, different models. - * - * \since 4.3 - */ - Resource( const QUrl& uri, const QUrl& type, ResourceManager* manager ); - - /** - * Constructor used internally. - */ - Resource( ResourceData* ); - - /** - * Destructor - */ - virtual ~Resource(); - - /** - * Makes this instance of Resource a copy of other. - */ - Resource& operator=( const Resource& other ); - - /** - * Same as operator=( Resource( uri ) ) - */ - Resource& operator=( const QUrl& uri ); - - /** - * The Resource manager that manages this resource. - * - * \since 4.3 - */ - ResourceManager* manager() const; - - /** - * The URI of the resource, uniquely identifying it. This URI in most - * cases is a virtual one which has been created from a generic base - * namespace and some identifier. - * - * The most important thing to remember is that the URI of for example - * a file does not necessarily have a relation to its local path. - * (Although Nepomuk tries to keep the URI of file resources in sync - * with the file URL for convenience.) - * - * For historical reasons the method does return a URI as QString instead - * of QUrl. The value equals resourceUri().toString(). - * - * \sa resourceUri(), getIdentifiers() - * - * \deprecated use resourceUri() instead - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED QString uri() const; -#endif - - /** - * The URI of the resource, uniquely identifying it. This URI in most - * cases is a virtual one which has been created from a generic base - * namespace and some identifier. - * - * The most important thing to remember is that the URI of for example - * a file does not necessarily have a relation to its local path. - * - * \return The resource URI of the resource or an empty url if the - * resource does not exist() yet. - * - * \sa getIdentifiers() - */ - QUrl resourceUri() const; - - /** - * The main type of the resource. Nepomuk tries hard to make this - * the type furthest down the hierarchy. In case the resource has only - * one type, this is no problem. However, if the resource has multiple - * types from different type hierarchies, there is no guarantee which - * one will be used here. - * - * For historical reasons the method does return a URI as QString instead - * of QUrl. The value equals resourceType().toString(). - * - * \sa name(), hasType(), types() - * - * \deprecated use resourceType instead - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED QString type() const; -#endif - - /** - * The main type of the resource. Nepomuk tries hard to make this - * the type furthest down the hierarchy. In case the resource has only - * one type, this is no problem. However, if the resource has multiple - * types from different type hierarchies, there is no guarantee which - * one will be used here. - * - * \sa name(), hasType(), types() - */ - QUrl resourceType() const; - - /** - * \return The list of all stored types for this resource. This may - * also include types that lie in the same hierachy. - * - * \sa type(), hasType() - */ - QList types() const; - - /** - * Set the types of the resource. Previous types will be overwritten. - * - * \since 4.2 - */ - void setTypes( const QList& types ); - - /** - * Add a type to the list of types. - * - * \since 4.2 - */ - void addType( const QUrl& type ); - - /** - * Check if the resource is of a certain type. The type hierarchy - * is checked including subclass relations. - */ - bool hasType( const QUrl& typeUri ) const; - - /** - * The name of the class this Resource represents an object of. - * The classname is derived from the type URI (see Resource::uri). - * For a translated user readable name of the resource see - * Ontology::typeName. - * - * \sa type() - */ - QString className() const; - - /** - * \deprecated Use properties() - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED QHash allProperties() const; -#endif - - /** - * \return A list of all defined properties - */ - QHash properties() const; - - /** - * Check if property identified by \a uri is defined - * for this resource. - * - * \param uri The URI identifying the property. - * - * \return true if property \a uri has a value set. - */ - bool hasProperty( const QUrl& uri ) const; - - /** - * Check if the resource has a property \p p with value \p v. - * - * \since 4.5 - */ - bool hasProperty( const Types::Property& p, const Variant& v ) const; - - /** - * \deprecated use hasProperty( const QUrl& ) const - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED bool hasProperty( const QString& uri ) const; -#endif - - /** - * Retrieve the value of property \a uri. If the property is not defined for - * this resource an invalid, empty Variant object is returned. - * - * \param uri The URI identifying the property. - */ - Variant property( const QUrl& uri ) const; - - /** - * \deprecated use property( const QUrl& ) const - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED Variant property( const QString& uri ) const; -#endif - - /** - * Set a property of the resource. - * - * \param uri The URI identifying the property. - * \param value The value of the property (i.e. the object of the RDF triple(s)) - */ - void setProperty( const QUrl& uri, const Variant& value ); - - /** - * Add a property value to the existing values. - * - * \param uri The URI identifying the property. - * \param value The value of the property (i.e. the object of the RDF triple(s)) - * - * \since 4.3 - */ - void addProperty( const QUrl& uri, const Variant& value ); - - /** - * \deprecated use setProperty( const QUrl& ) - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED void setProperty( const QString& uri, const Variant& value ); -#endif - - /** - * Remove property \a uri from this resource object. - * - * \param uri The URI identifying the property. - */ - void removeProperty( const QUrl& uri ); - - /** - * Remove \a value from property \a uri of this resource object. - * - * \param uri The URI identifying the property. - * \param value The value to remove - * - * \since 4.3 - */ - void removeProperty( const QUrl& uri, const Variant& value ); - - /** - * \deprecated use removeProperty( const QUrl& ) - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED void removeProperty( const QString& uri ); -#endif - - /** - * Remove this resource completely. - * CAUTION: After calling this method the resource will have been removed from the store - * without any trace. - */ - void remove(); - - /** - * \return true if this resource (i.e. the uri of this resource) exists in the local - * NEPOMUK RDF store. - */ - bool exists() const; - - /** - * \return true if this Resource object is valid, i.e. has a proper URI and type and - * can be synced with the local NEPOMUK RDF store. - * - * An invalid resource will become valid (i.e. get a new random URI) once setProperty - * is called. - */ - bool isValid() const; - - /** - * Tries very hard to find a suitable human-readable label for this resource. - * It looks for properties such as nao:prefLabel, rdfs:label, or nao:identifier, - * or even the fileName of File resources. - * - * \return A human readable label or if all fails the URI of the resource. - */ - QString genericLabel() const; - - /** - * Tries very hard to find a suitable human-readable description of the resource. - * This description is supposed to be longer than genericLabel() and includes such properties - * as nao:description, xesam:comment, rdfs:comment - * - * \return A human readable description of the resource or an empty string if none - * could be found. - */ - QString genericDescription() const; - - /** - * Tries very hard to find an icon suitable for this resource. - * - * \return An icon name to be used with KIcon or an empty string if none was found. - */ - QString genericIcon() const; - - /** - * Get or create the PIMO thing that relates to this resource. If this resource - * itself is a pimo:Thing, a reference to this is returned. If a pimo:Thing exists - * with has as occurrence this resource, the thing is returned. Otherwise a new thing - * is created. - * - * \since 4.2 - */ - Thing pimoThing(); - - /** - * Operator to compare two Resource objects. - */ - bool operator==( const Resource& ) const; - - /** - * Operator to compare two Resource objects. - * - * \since 4.4 - */ - bool operator!=( const Resource& ) const; - - /** - * Get property 'description'. Everything can be annotated with - * a simple string comment. - */ - QString description() const; - - /** - * Set property 'description'. Everything can be annotated with - * a simple string comment. - */ - void setDescription( const QString& value ); - - /** - * \return The URI of the property 'description'. - */ - static QString descriptionUri(); - - /** - * Get property 'identifier'. - */ - QStringList identifiers() const; - - /** - * Set property 'identifier'. - */ - void setIdentifiers( const QStringList& value ); - - /** - * Add a value to property 'identifier'. - */ - void addIdentifier( const QString& value ); - - /** - * \return The URI of the property 'identifier'. - */ - static QString identifierUri(); - - /** - * Get property 'altLabel'. - */ - QStringList altLabels() const; - - /** - * Set property 'altLabel'. - */ - void setAltLabels( const QStringList& value ); - - /** - * Add a value to property 'altLabel'. - */ - void addAltLabel( const QString& value ); - - /** - * \return The URI of the property 'altLabel'. - */ - static QString altLabelUri(); - - /** - * Get property 'annotation'. - */ - QList annotations() const; - - /** - * Set property 'annotation'. - */ - void setAnnotations( const QList& value ); - - /** - * Add a value to property 'annotation'. - */ - void addAnnotation( const Resource& value ); - - /** - * \return The URI of the property 'annotation'. - */ - static QString annotationUri(); - - /** - * Get property 'Tag'. Each Resource can be tagged with an arbitrary - * number of Tags. This allows a simple grouping of resources. - */ - QList tags() const; - - /** - * Set property 'Tag'. Each Resource can be tagged with an arbitrary - * number of Tags. This allows a simple grouping of resources. - */ - void setTags( const QList& value ); - - /** - * Add a value to property 'Tag'. Each Resource can be tagged with - * an arbitrary number of Tags. This allows a simple grouping of - * resources. - */ - void addTag( const Tag& value ); - - /** - * \return The URI of the property 'Tag'. - */ - static QString tagUri(); - - /** - * Get property 'Topic'. - */ - QList topics() const; - - /** - * Set property 'Topic'. - */ - void setTopics( const QList& value ); - - /** - * Add a value to property 'Topic'. - */ - void addTopic( const Resource& value ); - - /** - * \return The URI of the property 'Topic'. - */ - static QString topicUri(); - - /** - * Get property 'isTopicOf'. - */ - QList isTopicOfs() const; - - /** - * Set property 'isTopicOf'. - */ - void setIsTopicOfs( const QList& value ); - - /** - * Add a value to property 'isTopicOf'. - */ - void addIsTopicOf( const Resource& value ); - - /** - * \return The URI of the property 'isTopicOf'. - */ - static QString isTopicOfUri(); - - /** - * Get property 'isRelated'. - */ - QList isRelateds() const; - - /** - * Set property 'isRelated'. - */ - void setIsRelateds( const QList& value ); - - /** - * Add a value to property 'isRelated'. - */ - void addIsRelated( const Resource& value ); - - /** - * \return The URI of the property 'isRelated'. - */ - static QString isRelatedUri(); - - /** - * Get property 'label'. - */ - QString label() const; - - /** - * Set property 'label'. - */ - void setLabel( const QString& value ); - - /** - * \return The URI of the property 'label'. - */ - static QString labelUri(); - - /** - * Get property 'Rating'. - */ - quint32 rating() const; - - /** - * Set property 'Rating'. - */ - void setRating( const quint32& value ); - - /** - * \return The URI of the property 'Rating'. - */ - static QString ratingUri(); - - /** - * Get property 'Symbol'. Each resource can have a symbol assigned. - * For now this is a simple string which can either be the path to - * an actual pixmap file or just the name of an icon as defined by - * the freedesktop.org standard. - */ - QStringList symbols() const; - - /** - * Set property 'Symbol'. Each resource can have a symbol assigned. - * For now this is a simple string which can either be the path to - * an actual pixmap file or just the name of an icon as defined by - * the freedesktop.org standard. - */ - void setSymbols( const QStringList& value ); - - /** - * Add a value to property 'Symbol'. Each resource can have a symbol - * assigned. For now this is a simple string which can either be - * the path to an actual pixmap file or just the name of an icon as - * defined by the freedesktop.org standard. - */ - void addSymbol( const QString& value ); - - /** - * \return The URI of the property 'Symbol'. - */ - static QString symbolUri(); - - /** - * Get all resources that have this resource set as property 'annotation'. - * \sa ResourceManager::allResourcesWithProperty - */ - QList annotationOf() const; - - /** - * Get all resources that have this resource set as property 'isRelated'. - * \sa ResourceManager::allResourcesWithProperty - */ - QList isRelatedOf() const; - - /** - * Retrieve a list of all available Resource resources. This list - * consists of all resource of type Resource that are stored in - * the local Nepomuk meta data storage and any changes made locally. - * Be aware that in some cases this list can get very big. Then it - * might be better to use libKNep directly. - * - * \sa ResourceManager::allResources - * - * \warning This list will be very big. Usage of this method is - * discouraged. Use Query::QueryServiceClient in combination with an - * empty Query::Query instead. - */ - static QList allResources(); - - /** - * \return The usage count stored for this resource. - * - * \sa increaseUsageCount() - * - * \since 4.5 - */ - int usageCount() const; - - /** - * Increase the usage count of this resource and also - * update the last used date to the current date and time. - * - * \since 4.5 - */ - void increaseUsageCount(); - - /** - * \return \p true if this resource represents a file. Use toFile() to retrieve the - * corresponding file resource which provides convinience methods to handle file - * resources. - * - * \since 4.6 - */ - bool isFile() const; - - /** - * Convert this resource into a File resource to have access to the convinience methods - * provided by the File class. - * - * \since 4.6 - */ - File toFile() const; - - /** - * Allows to quickly load a resource from its resource URI without any - * additional checks. This is mostly used for optimized code within Nepomuk. - * - * In most situations the construtor Resource( QUrl, QUrl ) is better suited. - * - * \since 4.5 - */ - static Resource fromResourceUri( const KUrl& uri, const Nepomuk::Types::Class& type = Nepomuk::Types::Class(), ResourceManager* manager = 0 ); - - private: - /** - * Determines the final ResourceData and updates m_data if - * necessary. This will call ResourceData::determineUri() - * and optionally merge with already loaded ResourceData - * instances representing the same resource. - */ - void determineFinalResourceData() const; - - ResourceData* m_data; - - class Private; - Private* d; // unused - - friend class ResourceData; - }; - - NEPOMUK_EXPORT uint qHash( const Resource& res ); -} - -#endif diff --git a/nepomuk/core/resourcedata.cpp b/nepomuk/core/resourcedata.cpp deleted file mode 100644 index aae8e815..00000000 --- a/nepomuk/core/resourcedata.cpp +++ /dev/null @@ -1,858 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2010 Sebastian Trueg - * Copyright (C) 2010-2012 Vishesh Handa - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "resourcedata.h" -#include "resourcemanager.h" -#include "resourcemanager_p.h" -#include "resource.h" -#include "tools.h" -#include "nie.h" -#include "nfo.h" -#include "pimo.h" -#include "nepomukmainmodel.h" -#include "dbusconnectionpool.h" -#include "class.h" -#include "dbustypes.h" -#include "resourcewatcher.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -using namespace Soprano; - -#define MAINMODEL (m_rm->m_manager->mainModel()) - - -Nepomuk::ResourceData::ResourceData( const QUrl& uri, const QUrl& kickOffUri, const QUrl& type, ResourceManagerPrivate* rm ) - : m_uri(uri), - m_mainType( type ), - m_modificationMutex(QMutex::Recursive), - m_cacheDirty(false), - m_addedToWatcher(false), - m_pimoThing(0), - m_groundingOccurence(0), - m_rm(rm) -{ - if( m_mainType.isEmpty() ) { - m_mainType = Soprano::Vocabulary::RDFS::Resource(); - } - - m_types << m_mainType; - - m_rm->dataCnt.ref(); - - if( !uri.isEmpty() ) { - m_cacheDirty = true; - m_rm->m_initializedData.insert( uri, this ); - m_kickoffUris.insert( uri ); - } - if( !kickOffUri.isEmpty() ) { - m_kickoffUris.insert( kickOffUri ); - - if( kickOffUri.scheme().isEmpty() ) { - // Label - const QString label = kickOffUri.toString(); - m_cache.insert( Soprano::Vocabulary::NAO::identifier(), label ); - } - else if( kickOffUri.scheme() != QLatin1String("nepomuk") ) { - // It's probably the nie:url - m_cache.insert( Nepomuk::Vocabulary::NIE::url(), kickOffUri ); - } - } - m_rm->addToKickOffList( this, m_kickoffUris ); -} - - -Nepomuk::ResourceData::~ResourceData() -{ - resetAll(true); - m_rm->dataCnt.deref(); -} - - -bool Nepomuk::ResourceData::isFile() -{ - return( m_uri.scheme() == QLatin1String("file") || - m_nieUrl.scheme() == QLatin1String("file") || - (!m_kickoffUris.isEmpty() && (*m_kickoffUris.begin()).scheme() == QLatin1String("file")) || - constHasType( Soprano::Vocabulary::Xesam::File() ) || - constHasType( Nepomuk::Vocabulary::NFO::FileDataObject() ) ); -} - - -QUrl Nepomuk::ResourceData::uri() const -{ - return m_uri; -} - - -QUrl Nepomuk::ResourceData::type() -{ - load(); - return m_mainType; -} - - -QList Nepomuk::ResourceData::allTypes() -{ - load(); - return m_types; -} - - -void Nepomuk::ResourceData::setTypes( const QList& types ) -{ - store(); - - QMutexLocker lock(&m_modificationMutex); - - // reset types - m_types.clear(); - m_mainType = Soprano::Vocabulary::RDFS::Resource(); - - QList nodes; - // load types (and set maintype) - foreach( const QUrl& url, types ) { - loadType( url ); - nodes << Node( url ); - } - - // update the data store - setProperty(Soprano::Vocabulary::RDF::type(), Nepomuk::Variant(types) ); -} - - - -void Nepomuk::ResourceData::resetAll( bool isDelete ) -{ - // remove us from all caches (store() will re-insert us later if necessary) - m_rm->mutex.lock(); - - // IMPORTANT: - // Remove from the kickOffList before removing from the resource watcher - // This is required cause otherwise the Resource::fromResourceUri creates a new - // resource which is correctly identified to the ResourceData (this), and it is - // then deleted, which calls resetAll and this cycle continues. - Q_FOREACH( const KUrl& uri, m_kickoffUris ) - m_rm->m_uriKickoffData.remove( uri ); - - if( !m_uri.isEmpty() ) { - m_rm->m_initializedData.remove( m_uri ); - if( m_rm->m_watcher && m_addedToWatcher ) { - // See load() for an explanation of the QMetaObject call - - // stop the watcher since we do not want to watch all changes in case there is no ResourceData left - if(m_rm->m_watcher->resourceCount() == 1) { - QMetaObject::invokeMethod(m_rm->m_watcher, "stop", Qt::AutoConnection); - } - - // remove this Resource from the list of watched resources - QMetaObject::invokeMethod(m_rm->m_watcher, "removeResource", Qt::AutoConnection, Q_ARG(Nepomuk::Resource, Resource::fromResourceUri(m_uri))); - m_addedToWatcher = false; - } - } - m_rm->mutex.unlock(); - - // reset all variables - m_uri = QUrl(); - m_nieUrl = KUrl(); - m_kickoffUris.clear(); - m_cache.clear(); - m_cacheDirty = false; - m_types.clear(); - delete m_pimoThing; - m_pimoThing = 0; - m_groundingOccurence = 0; - - // when we are being deleted the value of m_mainType is not important - // anymore. Also since ResourceManager is a global static it might be - // deleted after the global static behind Soprano::Vocabulary::RDFS - // which results in a crash. - if( !isDelete ) - m_mainType = Soprano::Vocabulary::RDFS::Resource(); -} - - -QHash Nepomuk::ResourceData::allProperties() -{ - load(); - return m_cache; -} - - -bool Nepomuk::ResourceData::hasProperty( const QUrl& uri ) -{ - load(); - QHash::const_iterator it = m_cache.constFind( uri ); - if( it == m_cache.constEnd() ) - return false; - - return true; -} - - -bool Nepomuk::ResourceData::hasProperty( const QUrl& p, const Variant& v ) -{ - QHash::const_iterator it = m_cache.constFind( p ); - if( it == m_cache.constEnd() ) - return false; - - QList thisVals = it.value().toVariantList(); - QList vals = v.toVariantList(); - Q_FOREACH( const Variant& val, vals ) { - if( !thisVals.contains(val) ) - return false; - } - return true; -} - - -bool Nepomuk::ResourceData::hasType( const QUrl& uri ) -{ - load(); - return constHasType( uri ); -} - - -bool Nepomuk::ResourceData::constHasType( const QUrl& uri ) const -{ - // we need to protect the reading, too. setTypes may be triggered from another thread - QMutexLocker lock(&m_modificationMutex); - - Types::Class requestedType( uri ); - for ( QList::const_iterator it = m_types.constBegin(); - it != m_types.constEnd(); ++it ) { - Types::Class availType( *it ); - if ( availType == requestedType || - availType.isSubClassOf( requestedType ) ) { - return true; - } - } - return false; -} - - -Nepomuk::Variant Nepomuk::ResourceData::property( const QUrl& uri ) -{ - load(); - - // we need to protect the reading, too. load my be triggered from another thread's - // connection to a Soprano statement signal - QMutexLocker lock(&m_modificationMutex); - - QHash::const_iterator it = m_cache.constFind( uri ); - if ( it == m_cache.constEnd() ) { - return Variant(); - } - else { - return *it; - } -} - - -bool Nepomuk::ResourceData::store() -{ - QMutexLocker lock(&m_modificationMutex); - - if ( m_uri.isEmpty() ) { - QMutexLocker rmlock(&m_rm->mutex); - - if ( m_nieUrl.isValid() && - m_nieUrl.isLocalFile() && - m_mainType == Soprano::Vocabulary::RDFS::Resource() ) { - m_mainType = Nepomuk::Vocabulary::NFO::FileDataObject(); - m_types << m_mainType; - } - - QDBusConnection bus = QDBusConnection::sessionBus(); - QDBusMessage msg = QDBusMessage::createMethodCall( QLatin1String("org.kde.NepomukStorage"), - QLatin1String("/datamanagement"), - QLatin1String("org.kde.nepomuk.DataManagement"), - QLatin1String("createResource") ); - QString app = KGlobal::mainComponent().componentName(); - QVariantList arguments; - - //FIXME: Maybe we should be setting the 'label' over here. - arguments << DBus::convertUriList(m_types) << QString() << QString() << app; - msg.setArguments( arguments ); - - QDBusMessage reply = bus.call( msg ); - if( reply.type() == QDBusMessage::ErrorMessage ) { - //TODO: Set the error somehow - kWarning() << reply.errorMessage(); - return false; - } - else if( reply.type() == QDBusMessage::ReplyMessage ) { - m_uri = reply.arguments().at(0).toUrl(); - } - - // Add us to the initialized data, i.e. make us "valid" - m_rm->m_initializedData.insert( m_uri, this ); - - // each initialized resource has to be in a kickoff list - // thus, we make sure that is the case. - if( m_kickoffUris.isEmpty() ) { - m_kickoffUris.insert( m_uri ); - m_rm->addToKickOffList( this, m_kickoffUris ); - } - - // store our grounding occurrence in case we are a thing created by the pimoThing() method - if( m_groundingOccurence ) { - if( m_groundingOccurence != this ) - m_groundingOccurence->store(); - setProperty(Vocabulary::PIMO::groundingOccurrence(), Variant(m_groundingOccurence->uri()) ); - } - - foreach( const KUrl& url, m_kickoffUris ) { - if( url.scheme().isEmpty() ) - setProperty( Soprano::Vocabulary::NAO::identifier(), Variant(url.url()) ); - else - setProperty( Nepomuk::Vocabulary::NIE::url(), Variant(url.url()) ); - } - } - - return true; -} - - -void Nepomuk::ResourceData::loadType( const QUrl& storedType ) -{ - if ( !m_types.contains( storedType ) ) { - m_types << storedType; - } - if ( m_mainType == Soprano::Vocabulary::RDFS::Resource() ) { - Q_ASSERT( !storedType.isEmpty() ); - m_mainType = storedType; - } - else { - Types::Class currentTypeClass = m_mainType; - Types::Class storedTypeClass = storedType; - - // Keep the type that is further down the hierarchy - if ( storedTypeClass.isSubClassOf( currentTypeClass ) ) { - m_mainType = storedTypeClass.uri(); - } - else { - // This is a little convenience hack since the user is most likely - // more interested in the file content than the actual file - Types::Class xesamContentClass( Soprano::Vocabulary::Xesam::Content() ); - if ( m_mainType == Soprano::Vocabulary::Xesam::File() && - ( storedTypeClass == xesamContentClass || - storedTypeClass.isSubClassOf( xesamContentClass ) ) ) { - m_mainType = storedTypeClass.uri(); - } - else { - // the same is true for nie:DataObject vs. nie:InformationElement - Types::Class nieInformationElementClass( Vocabulary::NIE::InformationElement() ); - Types::Class nieDataObjectClass( Vocabulary::NIE::DataObject() ); - if( ( currentTypeClass == nieDataObjectClass || - currentTypeClass.isSubClassOf( nieDataObjectClass ) ) && - ( storedTypeClass == nieInformationElementClass || - storedTypeClass.isSubClassOf( nieInformationElementClass ) ) ) { - m_mainType = storedTypeClass.uri(); - } - } - } - } -} - - -bool Nepomuk::ResourceData::load() -{ - QMutexLocker lock(&m_modificationMutex); - - if ( m_cacheDirty ) { - m_cache.clear(); - - if(!m_rm->m_watcher) { - // - // The ResourceWatcher is not thread-safe. Thus, we need to ensure the safety ourselves. - // We do that by simply handling all RW related operations in the manager thread. - // This also means to invoke methods on the watcher through QMetaObject to make sure they - // get queued in case of calls between different threads. - // - m_rm->m_watcher = new ResourceWatcher(m_rm->m_manager); - m_rm->m_watcher->moveToThread(m_rm->m_manager->thread()); - QObject::connect( m_rm->m_watcher, SIGNAL(propertyAdded(Nepomuk::Resource,Nepomuk::Types::Property,QVariant)), - m_rm->m_manager, SLOT(slotPropertyAdded(Nepomuk::Resource,Nepomuk::Types::Property,QVariant)) ); - QObject::connect( m_rm->m_watcher, SIGNAL(propertyRemoved(Nepomuk::Resource,Nepomuk::Types::Property,QVariant)), - m_rm->m_manager, SLOT(slotPropertyRemoved(Nepomuk::Resource,Nepomuk::Types::Property,QVariant)) ); - m_rm->m_watcher->addResource( Nepomuk::Resource::fromResourceUri(m_uri) ); - } - else { - QMetaObject::invokeMethod(m_rm->m_watcher, "addResource", Qt::AutoConnection, Q_ARG(Nepomuk::Resource, Nepomuk::Resource::fromResourceUri(m_uri)) ); - } - // (re-)start the watcher in case this resource is the only one in the list of watched - if(m_rm->m_watcher->resources().count() <= 1) { - QMetaObject::invokeMethod(m_rm->m_watcher, "start", Qt::AutoConnection); - } - m_addedToWatcher = true; - - if ( m_uri.isValid() ) { - // - // We exclude properties that are part of the inference graph - // It would only pollute the user interface - // - Soprano::QueryResultIterator it = MAINMODEL->executeQuery(QString("select distinct ?p ?o where { " - "%1 ?p ?o . }").arg(Soprano::Node::resourceToN3(m_uri)), - Soprano::Query::QueryLanguageSparqlNoInference); - while ( it.next() ) { - QUrl p = it["p"].uri(); - Soprano::Node o = it["o"]; - if ( p == Soprano::Vocabulary::RDF::type() ) { - if ( o.isResource() ) { - loadType( o.uri() ); - } - } - else { - Nepomuk::Variant var = Variant::fromNode( o ); - updateKickOffLists( p, var ); - m_cache[p].append( var ); - } - } - - m_cacheDirty = false; - - delete m_pimoThing; - m_pimoThing = 0; - if( hasType( Vocabulary::PIMO::Thing() ) ) { - m_pimoThing = new Thing( m_uri ); - } - else { - // TODO: somehow handle pimo:referencingOccurrence and pimo:occurrence - QueryResultIterator pimoIt = MAINMODEL->executeQuery( QString( "select ?r where { ?r <%1> <%2> . }") - .arg( Vocabulary::PIMO::groundingOccurrence().toString() ) - .arg( QString::fromLatin1( m_uri.toEncoded() ) ), - Soprano::Query::QueryLanguageSparqlNoInference ); - if( pimoIt.next() ) { - m_pimoThing = new Thing( pimoIt.binding("r").uri() ); - } - } - - return true; - } - else { - return false; - } - } - else { - return true; - } -} - - -void Nepomuk::ResourceData::setProperty( const QUrl& uri, const Nepomuk::Variant& value ) -{ - Q_ASSERT( uri.isValid() ); - - if( store() ) { - // step 0: make sure this resource is in the store - QMutexLocker lock(&m_modificationMutex); - - // update the store - QDBusConnection bus = QDBusConnection::sessionBus(); - QDBusMessage msg = QDBusMessage::createMethodCall( QLatin1String("org.kde.NepomukStorage"), - QLatin1String("/datamanagement"), - QLatin1String("org.kde.nepomuk.DataManagement"), - QLatin1String("setProperty") ); - QVariantList varList; - foreach( const Variant& var, value.toVariantList() ) { - // make sure resource values are identified and in the store - if( var.simpleType() == qMetaTypeId() ) { - Resource res = var.toResource(); - res.determineFinalResourceData(); - res.m_data->store(); - - varList << res.resourceUri(); - } - else { - varList << var.variant(); - } - } - - msg.setArguments( QVariantList() - << DBus::convertUriList(QList() << m_uri) - << DBus::convertUri(uri) - << QVariant(DBus::normalizeVariantList(varList)) - << KGlobal::mainComponent().componentName() ); - - QDBusMessage reply = bus.call( msg ); - if( reply.type() == QDBusMessage::ErrorMessage ) { - //TODO: Set the error somehow - kWarning() << reply.errorMessage(); - return; - } - - // update the cache for now - if( value.isValid() ) - m_cache[uri] = value; - else - m_cache.remove(uri); - - // update the kickofflists - updateKickOffLists( uri, value ); - } -} - - -void Nepomuk::ResourceData::addProperty( const QUrl& uri, const Nepomuk::Variant& value ) -{ - Q_ASSERT( uri.isValid() ); - - if( value.isValid() && store() ) { - // step 0: make sure this resource is in the store - QMutexLocker lock(&m_modificationMutex); - - // update the store - QDBusConnection bus = QDBusConnection::sessionBus(); - QDBusMessage msg = QDBusMessage::createMethodCall( QLatin1String("org.kde.NepomukStorage"), - QLatin1String("/datamanagement"), - QLatin1String("org.kde.nepomuk.DataManagement"), - QLatin1String("addProperty") ); - QVariantList varList; - foreach( const Nepomuk::Variant var, value.toVariantList() ) { - // make sure resource values are in the store - if( var.simpleType() == qMetaTypeId() ) { - Resource res = var.toResource(); - res.determineFinalResourceData(); - res.m_data->store(); - - varList << res.resourceUri(); - } - else { - varList << var.variant(); - } - } - - msg.setArguments( QVariantList() - << DBus::convertUriList(QList() << m_uri) - << DBus::convertUri(uri) - << QVariant(DBus::normalizeVariantList(varList)) - << KGlobal::mainComponent().componentName() ); - - QDBusMessage reply = bus.call( msg ); - if( reply.type() == QDBusMessage::ErrorMessage ) { - //TODO: Set the error somehow - kWarning() << reply.errorMessage(); - return; - } - - // update the cache for now - if( value.isValid() ) - m_cache[uri].append(value); - - // update the kickofflists - updateKickOffLists( uri, value ); - } -} - - -void Nepomuk::ResourceData::removeProperty( const QUrl& uri ) -{ - Q_ASSERT( uri.isValid() ); - if( !m_uri.isEmpty() ) { - QMutexLocker lock(&m_modificationMutex); - - QDBusConnection bus = QDBusConnection::sessionBus(); - QDBusMessage msg = QDBusMessage::createMethodCall( QLatin1String("org.kde.NepomukStorage"), - QLatin1String("/datamanagement"), - QLatin1String("org.kde.nepomuk.DataManagement"), - QLatin1String("removeProperties") ); - msg.setArguments( QVariantList() - << DBus::convertUri(m_uri) - << DBus::convertUri(uri) - << KGlobal::mainComponent().componentName() ); - - QDBusMessage reply = bus.call( msg ); - if( reply.type() == QDBusMessage::ErrorMessage ) { - //TODO: Set the error somehow - kWarning() << reply.errorMessage(); - return; - } - - // Update the cache - m_cache.remove( uri ); - - // update the kickofflists - updateKickOffLists( uri, Variant() ); - } -} - - -void Nepomuk::ResourceData::remove( bool recursive ) -{ - Q_UNUSED(recursive) - QMutexLocker lock(&m_modificationMutex); - - if( !m_uri.isEmpty() ) { - QDBusConnection bus = QDBusConnection::sessionBus(); - QDBusMessage msg = QDBusMessage::createMethodCall( QLatin1String("org.kde.NepomukStorage"), - QLatin1String("/datamanagement"), - QLatin1String("org.kde.nepomuk.DataManagement"), - QLatin1String("removeResources") ); - // TODO: Set the flag over here - msg.setArguments( QVariantList() - << DBus::convertUri(m_uri) - << 0 /* no flags */ - << KGlobal::mainComponent().componentName()); - - QDBusMessage reply = bus.call( msg ); - if( reply.type() == QDBusMessage::ErrorMessage ) { - //TODO: Set the error somehow - kWarning() << reply.errorMessage(); - return; - } - } - - resetAll(); -} - - -bool Nepomuk::ResourceData::exists() -{ - if( m_uri.isValid() ) { - const QString query = QString::fromLatin1("ask { %1 ?p ?o . }") - .arg( Soprano::Node::resourceToN3(m_uri) ); - return MAINMODEL->executeQuery( query, Soprano::Query::QueryLanguageSparql ).boolValue(); - } - else { - return false; - } -} - - -bool Nepomuk::ResourceData::isValid() const -{ - return( !m_mainType.isEmpty() && ( !m_uri.isEmpty() || !m_kickoffUris.isEmpty() ) ); -} - - -Nepomuk::ResourceData* Nepomuk::ResourceData::determineUri() -{ - // We have the following possible situations: - // 1. m_uri is already valid - // -> simple, nothing to do - // - // 2. m_uri is not valid - // -> we need to determine the URI - // - // 2.1. m_kickoffUri is valid - // 2.1.1. it is a file URL - // 2.1.1.1. it is nie:url for r - // -> use r as m_uri - // 2.1.1.2. it points to a file on a removable device for which we have a filex:/ URL - // -> use the r in r nie:url filex:/... - // 2.1.1.3. it is a file which is not an object in some nie:url relation - // -> create new random m_uri and use kickoffUriOrId() as m_nieUrl - // 2.1.2. it is a resource URI - // -> use it as m_uri - // - // 2.2. m_kickOffUri is not valid - // 2.2.1. m_kickOffUri is a nao:identifier for r - // -> use r as m_uri - // - - if( m_uri.isEmpty() ) { - Soprano::Model* model = MAINMODEL; - - if( !m_kickoffUris.isEmpty() ) { - KUrl kickOffUri = *m_kickoffUris.begin(); - if( kickOffUri.scheme().isEmpty() ) { - // - // Not valid. Checking for nao:identifier - // - QString query = QString::fromLatin1("select distinct ?r where { ?r %1 %2. } LIMIT 1") - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::identifier()) ) - .arg( Soprano::Node::literalToN3( kickOffUri.url() ) ); - - Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql ); - if( it.next() ) { - m_uri = it["r"].uri(); - it.close(); - } - } - else { - // - // In one query determine if the URI is already used as resource URI or as - // nie:url - // - QString query = QString::fromLatin1("select distinct ?r ?o where { " - "{ ?r %1 %2 . FILTER(?r!=%2) . } " - "UNION " - "{ %2 ?p ?o . } " - "} LIMIT 1") - .arg( Soprano::Node::resourceToN3( Nepomuk::Vocabulary::NIE::url() ) ) - .arg( Soprano::Node::resourceToN3( kickOffUri ) ); - Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql ); - if( it.next() ) { - QUrl uri = it["r"].uri(); - if( uri.isEmpty() ) { - m_uri = kickOffUri; - } - else { - m_uri = uri; - m_nieUrl = kickOffUri; - } - it.close(); - } - else if( kickOffUri.scheme() == QLatin1String("nepomuk") ) { - // for nepomuk URIs we simply use the kickoff URI as resource URI - m_uri = kickOffUri; - } - else { - // for everything else we use m_kickoffUri as nie:url with a new random m_uri - m_nieUrl = kickOffUri; - } - } - } - - // - // Move us to the final data hash now that the URI is known - // - if( !m_uri.isEmpty() ) { - m_cacheDirty = true; - ResourceDataHash::iterator it = m_rm->m_initializedData.find(m_uri); - if( it == m_rm->m_initializedData.end() ) { - m_rm->m_initializedData.insert( m_uri, this ); - } - else { - return it.value(); - } - } - } - - return this; -} - - -void Nepomuk::ResourceData::invalidateCache() -{ - m_cacheDirty = true; -} - - -Nepomuk::Thing Nepomuk::ResourceData::pimoThing() -{ - load(); - if( !m_pimoThing ) { - // - // We only create a new thing if we are a nie:InformationElement. - // All other resources will simply be converted into a pimo:Thing - // - // Files, however, are a special case in every aspect. this includes pimo things. - // Files are their own grounding occurrence. This makes a lot of things - // much simpler. - // - if( hasType( Vocabulary::PIMO::Thing() ) || - isFile() || - !hasType( Vocabulary::NIE::InformationElement() ) ) { - m_pimoThing = new Thing(this); - } - else { - m_pimoThing = new Thing(); - } - m_pimoThing->m_data->m_groundingOccurence = this; - } - return *m_pimoThing; -} - - -bool Nepomuk::ResourceData::operator==( const ResourceData& other ) const -{ - if( this == &other ) - return true; - - return( m_uri == other.m_uri && - m_mainType == other.m_mainType && - m_kickoffUris == other.m_kickoffUris ); -} - - -QDebug Nepomuk::ResourceData::operator<<( QDebug dbg ) const -{ - KUrl::List list = m_kickoffUris.toList(); - dbg << QString::fromLatin1("[kickoffuri: %1; uri: %2; type: %3; ref: %4]") - .arg( list.toStringList().join(QLatin1String(",")), - m_uri.url(), - m_mainType.toString() ) - .arg( m_ref ); - - return dbg; -} - - -QDebug operator<<( QDebug dbg, const Nepomuk::ResourceData& data ) -{ - return data.operator<<( dbg ); -} - - -void Nepomuk::ResourceData::updateKickOffLists(const QUrl& prop, const Nepomuk::Variant& v) -{ - KUrl oldUrl; - KUrl newUrl; - if( prop == Nepomuk::Vocabulary::NIE::url() ) { - oldUrl = m_nieUrl; - newUrl = v.toUrl(); - m_nieUrl = newUrl; - } - else if( prop == Soprano::Vocabulary::NAO::identifier() ) { - Q_FOREACH( const KUrl& url, m_kickoffUris ) { - if( url.scheme().isEmpty() ) { - oldUrl = url; - break; - } - } - newUrl = KUrl( v.toString() ); - } - else { - return; - } - - if( oldUrl != newUrl ) { - QMutexLocker rmlock(&m_rm->mutex); - - m_kickoffUris.remove( oldUrl ); - m_rm->m_uriKickoffData.remove( oldUrl ); - - if( !newUrl.isEmpty() ) { - m_kickoffUris.insert( newUrl ); - m_rm->m_uriKickoffData.insert( newUrl, this ); - } - } -} diff --git a/nepomuk/core/resourcedata.h b/nepomuk/core/resourcedata.h deleted file mode 100644 index 89116f6a..00000000 --- a/nepomuk/core/resourcedata.h +++ /dev/null @@ -1,220 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2010 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_RESOURCE_DATA_H_ -#define _NEPOMUK_RESOURCE_DATA_H_ - -#include -#include -#include -#include -#include -#include - -#include "variant.h" -#include "thing.h" -#include - -#include - - -namespace Nepomuk { - - class Resource; - class ResourceManagerPrivate; - - class ResourceData - { - public: - explicit ResourceData( const QUrl& uri, const QUrl& kickOffUri, const QUrl& type_, ResourceManagerPrivate* rm ); - ~ResourceData(); - - inline bool ref(Nepomuk::Resource* res) { - m_resources.push_back( res ); - return m_ref.ref(); - } - - - inline bool deref(Nepomuk::Resource* res) { - m_resources.removeAll( res ); - return m_ref.deref(); - } - - inline int cnt() const { - return m_ref; - } - - /** - * Tries to determine if this resource represents a file by examining the type and the uri. - */ - bool isFile(); - - /** - * The URI of the resource. This might be empty if the resource was not synced yet. - */ - QUrl uri() const; - - /** - * \return The main type of the resource. ResourceData tries hard to make this the - * most important type, i.e. that which is furthest down the hierachy. - */ - QUrl type(); - - QList allTypes(); - - void setTypes( const QList& types ); - - QHash allProperties(); - - bool hasProperty( const QUrl& uri ); - - bool hasProperty( const QUrl& p, const Variant& v ); - - /** - * Does also check for subClass relations. - */ - bool hasType( const QUrl& uri ); - - /** - * Check the type without loading data from the store. - */ - bool constHasType( const QUrl& type ) const; - - Variant property( const QUrl& uri ); - - /** - * Set a property. The property will directly be saved to the RDF store. - * Calls store to make sure this resource and property resources are properly - * stored. - */ - void setProperty( const QUrl& uri, const Variant& value ); - - void addProperty( const QUrl& uri, const Variant& value ); - - void removeProperty( const QUrl& uri ); - - /** - * Makes sure the resource is present in the RDF store. This means that if it does - * not exist the type and the identifier (if one has been used to create the instance) - * are stored. - * - * This is also the only place where a new URI is generated via ResourceManager::generateUniqueUri() - * in case m_uri is empty. - * - * \sa exists, setProperty - */ - bool store(); - - bool load(); - - /** - * Remove this resource data from the store completely. - * \param recursive If true all statements that contain this - * resource as an object will be removed, too. - */ - void remove( bool recursive = true ); - - /** - * This method only works with a proper URI, i.e. it does - * not work on non-initialized resources that only know - * their kickoffUriOrId - */ - bool exists(); - - bool isValid() const; - - /** - * Searches for the resource in the Nepomuk store using m_kickoffId and m_kickoffUri. - * - * This will either get the actual resource URI from the database - * and add m_data into ResourceManagerPrivate::m_initializedData - * or it will find another ResourceData instance in m_initializedData - * which represents the same resource. The ResourceData that should be - * used is returned. - * - * \returns The initialized ResourceData object representing the actual resource. - * - * m_determineUriMutex needs to be locked before calling this method - */ - ResourceData* determineUri(); - - void invalidateCache(); - - Thing pimoThing(); - - /** - * Compares the properties of two ResourceData objects taking into account the Deleted flag - */ - bool operator==( const ResourceData& other ) const; - - QDebug operator<<( QDebug dbg ) const; - - ResourceManagerPrivate* rm() const { return m_rm; } - - /// Contains a list of resources which use this ResourceData - QList m_resources; - - /// the URI that was used to construct the resource. Will be used by determineUri - /// to find the actual resource URI which is either m_kickoffUri itself or - /// a resource URI which relates to m_kickoffUri by nie:url - /// This is a set since Resource::determineFinalResourceData may add additional uris - QSet m_kickoffUris; - - QHash m_cache; - - /// Updates both m_kickoffUris and ResourceMangerPrivate's list - void updateKickOffLists( const QUrl & prop, const Variant & v ); - - private: - void loadType( const QUrl& type ); - - /// Will reset this instance to 0 as if constructed without parameters - /// Used by remove() and deleteData() - void resetAll( bool isDelete = false ); - - /// final resource URI created by determineUri - KUrl m_uri; - - /// the URL of file resources - KUrl m_nieUrl; - - QUrl m_mainType; - QList m_types; - - QAtomicInt m_ref; - - mutable QMutex m_modificationMutex; - - bool m_cacheDirty; - bool m_addedToWatcher; - - // using a pointer to avoid infinite creation loop - Thing* m_pimoThing; - - // only used for delayed storage of the pimo thing relation - ResourceData* m_groundingOccurence; - - ResourceManagerPrivate* m_rm; - }; -} - -QDebug operator<<( QDebug dbg, const Nepomuk::ResourceData& ); - -#endif diff --git a/nepomuk/core/resourcemanager.cpp b/nepomuk/core/resourcemanager.cpp deleted file mode 100644 index 5ecc4232..00000000 --- a/nepomuk/core/resourcemanager.cpp +++ /dev/null @@ -1,562 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2012 Sebastian Trueg - * Copyright (C) 2010 Vishesh Handa - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "resourcemanager.h" -#include "resourcemanager_p.h" -#include "resourcedata.h" -#include "tools.h" -#include "nepomukmainmodel.h" -#include "resource.h" -#include "class.h" -#include "nie.h" -#include "dbustypes.h" -#include "resourcewatcher.h" - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace Soprano; - -Nepomuk::ResourceManager* Nepomuk::ResourceManager::s_instance = 0; - -Nepomuk::ResourceManagerPrivate::ResourceManagerPrivate( ResourceManager* manager ) - : mainModel( 0 ), - overrideModel( 0 ), - mutex(QMutex::Recursive), - dataCnt( 0 ), - m_manager( manager ), - m_watcher( 0 ) -{ - Nepomuk::DBus::registerDBusTypes(); -} - - -Nepomuk::ResourceData* Nepomuk::ResourceManagerPrivate::data( const QUrl& uri, const QUrl& type ) -{ - if ( uri.isEmpty() ) { - // return an invalid resource which may be activated by calling setProperty - return new ResourceData( QUrl(), QUrl(), type, this ); - } - - if( ResourceData* data = findData( uri ) ) { - return data; - } - else { - return new ResourceData( QUrl(), uri, type, this ); - } -} - - -Nepomuk::ResourceData* Nepomuk::ResourceManagerPrivate::data( const QString& uriOrId, const QUrl& type ) -{ - if ( !uriOrId.isEmpty() ) { - KUrl url(uriOrId); - return data( url, type ); - } - - return new ResourceData( QUrl(), QUrl(), type, this ); -} - - -Nepomuk::ResourceData* Nepomuk::ResourceManagerPrivate::dataForResourceUri( const QUrl& uri, const QUrl& type ) -{ - if ( uri.isEmpty() ) { - // return an invalid resource which may be activated by calling setProperty - return new ResourceData( QUrl(), QUrl(), type, this ); - } - - if( ResourceData* data = findData( uri ) ) { - return data; - } - else { - return new ResourceData( uri, QUrl(), type, this ); - } -} - - -QList Nepomuk::ResourceManagerPrivate::allResourceDataOfType( const QUrl& type ) -{ - QList l; - - if( !type.isEmpty() ) { - mutex.lock(); - QSet rdl = m_uriKickoffData.values().toSet(); - mutex.unlock(); - for( QSet::iterator rdIt = rdl.begin(); - rdIt != rdl.end(); ++rdIt ) { - ResourceData* rd = *rdIt; - // - // make sure we do not trigger a load here since - // 1. that could result in the deletion of values from the iterated list (m_cache.clear() in ResourceData::load) - // 2. We only need to check non-existing resources anyway, since the rest is queried from the db below - // - if( rd->constHasType( type ) ) { - l.append( rd ); - } - } - } - - return l; -} - - -QList Nepomuk::ResourceManagerPrivate::allResourceDataWithProperty( const QUrl& uri, const Variant& v ) -{ - QList l; - - // - // We need to cache m_uriKickoffData since it might be changed - // in the loop by ResourceData::load() - // - mutex.lock(); - QSet rdl = m_uriKickoffData.values().toSet(); - mutex.unlock(); - - // - // make sure none of the ResourceData objects are deleted by ResourceData::load below - // which would result in a crash since we have them cached. - // - QList tmp; - foreach( ResourceData* rd, rdl ) { - tmp << Resource( rd ); - } - - for( QSet::iterator rdIt = rdl.begin(); - rdIt != rdl.end(); ++rdIt ) { - ResourceData* rd = *rdIt; - if( rd->hasProperty( uri ) && - rd->property( uri ) == v ) { - l.append( rd ); - } - } - - return l; -} - - -QList Nepomuk::ResourceManagerPrivate::allResourceData() -{ - return m_uriKickoffData.values().toSet().toList(); -} - - -void Nepomuk::ResourceManagerPrivate::cleanupCache( int num ) -{ - QMutexLocker lock( &mutex ); - - QSet rdl = m_uriKickoffData.values().toSet() + m_initializedData.values().toSet(); - for( QSet::iterator rdIt = rdl.begin(); - rdIt != rdl.end(); ++rdIt ) { - ResourceData* data = *rdIt; - if ( !data->cnt() ) { - delete data; - if( num > 0 && --num == 0 ) - break; - } - } -} - - -bool Nepomuk::ResourceManagerPrivate::shouldBeDeleted( ResourceData * rd ) const -{ - // We only delete ResourceData objects if no other Resource is accessing them - return !rd->cnt(); -} - - -void Nepomuk::ResourceManagerPrivate::addToKickOffList( ResourceData* rd, const QSet & uris ) -{ - Q_FOREACH( const KUrl& uri, uris ) - m_uriKickoffData.insert( uri, rd ); -} - - -void Nepomuk::ResourceManagerPrivate::_k_storageServiceInitialized( bool success ) -{ - if( success ) { - kDebug() << "Nepomuk Storage service up and initialized."; - cleanupCache(-1); - m_manager->init(); - emit m_manager->nepomukSystemStarted(); - } -} - - -void Nepomuk::ResourceManagerPrivate::_k_dbusServiceUnregistered( const QString& serviceName ) -{ - if( serviceName == QLatin1String("org.kde.NepomukStorage") ) { - kDebug() << "Nepomuk Storage service went down."; - cleanupCache(-1); - if( m_manager->d->mainModel && m_manager->d->mainModel->isValid() ){ - m_manager->d->mainModel->disconnect(); - } - emit m_manager->nepomukSystemStopped(); - } -} - - - -Nepomuk::ResourceData* Nepomuk::ResourceManagerPrivate::findData( const QUrl& uri ) -{ - if ( !uri.isEmpty() ) { - QMutexLocker lock( &mutex ); - - // look for the URI in the initialized and in the URI kickoff data - ResourceDataHash::iterator end = m_initializedData.end(); - ResourceDataHash::iterator it = m_initializedData.find( uri ); - if( it == end ) { - end = m_uriKickoffData.end(); - it = m_uriKickoffData.find( uri ); - } - - if( it != end ) { - return it.value(); - } - } - - return 0; -} - - -Nepomuk::ResourceManager::ResourceManager() - : QObject(), - d( new ResourceManagerPrivate( this ) ) -{ - // connect to the storage service's initialized signal to be able to emit - // the nepomukSystemStarted signal - QDBusConnection::sessionBus().connect( QLatin1String("org.kde.NepomukStorage"), - QLatin1String("/servicecontrol"), - QLatin1String("org.kde.nepomuk.ServiceControl"), - QLatin1String("serviceInitialized"), - this, - SLOT(_k_storageServiceInitialized(bool)) ); - - // connect to the serviceUnregistered signal to be able to connect the nepomukSystemStopped - // signal once the storage service goes away - QDBusServiceWatcher *watcher = new QDBusServiceWatcher( QLatin1String("org.kde.NepomukStorage"), - QDBusConnection::sessionBus(), - QDBusServiceWatcher::WatchForUnregistration, - this ); - connect( watcher, SIGNAL(serviceUnregistered(QString)), - this, SLOT(_k_dbusServiceUnregistered(QString)) ); - - init(); -} - - -Nepomuk::ResourceManager::~ResourceManager() -{ - clearCache(); - delete d->mainModel; - delete d; - - if(s_instance == this) { - s_instance = 0; - } -} - - -void Nepomuk::ResourceManager::deleteInstance() -{ - delete this; -} - - -Nepomuk::ResourceManager* Nepomuk::ResourceManager::instance() -{ - if(!s_instance) { - s_instance = new ResourceManager(); - s_instance->setParent(QCoreApplication::instance()); - } - return s_instance; -} - - -int Nepomuk::ResourceManager::init() -{ - QMutexLocker lock( &d->initMutex ); - - if( !d->mainModel ) { - d->mainModel = new MainModel( this ); - } - - d->mainModel->init(); - - return d->mainModel->isValid() ? 0 : -1; -} - - -bool Nepomuk::ResourceManager::initialized() const -{ - QMutexLocker lock( &d->initMutex ); - return d->mainModel && d->mainModel->isValid(); -} - - -#ifndef KDE_NO_DEPRECATED -Nepomuk::Resource Nepomuk::ResourceManager::createResourceFromUri( const QString& uri ) -{ - return Resource( uri, QUrl() ); -} -#endif - -void Nepomuk::ResourceManager::removeResource( const QString& uri ) -{ - Resource res( uri ); - res.remove(); -} - -void Nepomuk::ResourceManager::notifyError( const QString& uri, int errorCode ) -{ - kDebug() << "(Nepomuk::ResourceManager) error: " << uri << " " << errorCode; - emit error( uri, errorCode ); -} - - -#ifndef KDE_NO_DEPRECATED -QList Nepomuk::ResourceManager::allResourcesOfType( const QString& type ) -{ - return allResourcesOfType( QUrl(type) ); -} -#endif - - -QList Nepomuk::ResourceManager::allResourcesOfType( const QUrl& type ) -{ - QSet set; - - if( !type.isEmpty() ) { - // check local data - QList localData = d->allResourceDataOfType( type ); - for( QList::iterator rdIt = localData.begin(); - rdIt != localData.end(); ++rdIt ) { - Resource res( *rdIt ); - set.insert(res); - } - -// kDebug() << " added local resources: " << l.count(); - - Soprano::Model* model = mainModel(); - Soprano::StatementIterator it = model->listStatements( Soprano::Statement( Soprano::Node(), Soprano::Vocabulary::RDF::type(), type ) ); - - while( it.next() ) { - Statement s = *it; - Resource res( s.subject().uri() ); - set.insert(res); - } - -// kDebug() << " added remote resources: " << l.count(); - } - - return set.toList(); -} - - -QList Nepomuk::ResourceManager::allResources() -{ - QList l; - Q_FOREACH( ResourceData* data, d->allResourceData()) { - l << Resource( data ); - } - - Soprano::QueryResultIterator it = mainModel()->executeQuery( QLatin1String("select distinct ?r where { ?r a ?t . FILTER(?t != rdf:Property && ?t != rdfs:Class) . }"), - Soprano::Query::QueryLanguageSparql ); - while( it.next() ) { - Resource r( it[0].uri() ); - l << r; - } - - return l; -} - - -#ifndef KDE_NO_DEPRECATED -QList Nepomuk::ResourceManager::allResourcesWithProperty( const QString& uri, const Variant& v ) -{ - return allResourcesWithProperty( QUrl(uri), v ); -} -#endif - - -QList Nepomuk::ResourceManager::allResourcesWithProperty( const QUrl& uri, const Variant& v ) -{ - QSet set; - - if( v.isList() ) { - kDebug() << "(ResourceManager::allResourcesWithProperty) list values not supported."; - } - else { - // check local data - QList localData = d->allResourceDataWithProperty( uri, v ); - for( QList::iterator rdIt = localData.begin(); - rdIt != localData.end(); ++rdIt ) { - set.insert( Resource( *rdIt ) ); - } - - // check remote data - Soprano::Model* model = mainModel(); - Soprano::StatementIterator it = model->listStatements( Soprano::Statement( Soprano::Node(), uri, v.toNode() ) ); - - while( it.next() ) { - Statement s = *it; - Resource res( s.subject().uri() ); - set.insert( res ); - } - } - - return set.toList(); -} - - -void Nepomuk::ResourceManager::clearCache() -{ - d->cleanupCache( -1 ); -} - - -#ifndef KDE_NO_DEPRECATED -QString Nepomuk::ResourceManager::generateUniqueUri() -{ - return generateUniqueUri( QString() ).toString(); -} -#endif - - -QUrl Nepomuk::ResourceManager::generateUniqueUri( const QString& name ) -{ - // default to res URIs - QString type = QLatin1String("res"); - - // ctx is the only used value for name - if(name == QLatin1String("ctx")) { - type = name; - } - - Soprano::Model* model = mainModel(); - - while( 1 ) { - QString uuid = QUuid::createUuid().toString(); - uuid = uuid.mid(1, uuid.length()-2); - QUrl uri = QUrl( QLatin1String("nepomuk:/") + type + QLatin1String("/") + uuid ); - if ( !model->executeQuery( QString::fromLatin1("ask where { " - "{ <%1> ?p1 ?o1 . } " - "UNION " - "{ ?s2 <%1> ?o2 . } " - "UNION " - "{ ?s3 ?p3 <%1> . } " - "UNION " - "{ graph <%1> { ?s4 ?4 ?o4 . } . } " - "}") - .arg( QString::fromLatin1( uri.toEncoded() ) ), Soprano::Query::QueryLanguageSparql ).boolValue() ) { - return uri; - } - } -} - - -Soprano::Model* Nepomuk::ResourceManager::mainModel() -{ - // make sure we are initialized - if ( !d->overrideModel && !initialized() ) { - init(); - } - - return d->mainModel; -} - - -void Nepomuk::ResourceManager::slotPropertyAdded(const Resource &res, const Types::Property &prop, const QVariant &value) -{ - ResourceDataHash::iterator it = d->m_initializedData.find(res.resourceUri()); - if(it != d->m_initializedData.end()) { - ResourceData* data = *it; - data->m_cache[prop.uri()].append(Variant(value)); - data->updateKickOffLists(prop.uri(), Variant(value)); - } -} - -void Nepomuk::ResourceManager::slotPropertyRemoved(const Resource &res, const Types::Property &prop, const QVariant &value_) -{ - ResourceDataHash::iterator it = d->m_initializedData.find(res.resourceUri()); - if(it != d->m_initializedData.end()) { - ResourceData* data = *it; - - - QHash::iterator cacheIt = data->m_cache.find(prop.uri()); - if(cacheIt != data->m_cache.end()) { - Variant v = *cacheIt; - const Variant value(value_); - QList vl = v.toVariantList(); - if(vl.contains(value)) { - vl.removeAll(value); - data->updateKickOffLists(prop.uri(), Variant()); - if(vl.isEmpty()) { - data->m_cache.erase(cacheIt); - } - else { - cacheIt.value() = vl; - } - } - } - } -} - -void Nepomuk::ResourceManager::setOverrideMainModel( Soprano::Model* model ) -{ - QMutexLocker lock( &d->mutex ); - - if( model != d->mainModel ) { - d->overrideModel = model; - - // clear cache to make sure we do not mix data - Q_FOREACH( ResourceData* data, d->allResourceData()) { - data->invalidateCache(); - } - } -} - - -Nepomuk::ResourceManager* Nepomuk::ResourceManager::createManagerForModel( Soprano::Model* model ) -{ - ResourceManager* manager = new ResourceManager(); - manager->setOverrideMainModel( model ); - return manager; -} - -#include "resourcemanager.moc" diff --git a/nepomuk/core/resourcemanager.h b/nepomuk/core/resourcemanager.h deleted file mode 100644 index 6b23b8f4..00000000 --- a/nepomuk/core/resourcemanager.h +++ /dev/null @@ -1,289 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2009 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_RESOURCE_MANAGER_H_ -#define _NEPOMUK_RESOURCE_MANAGER_H_ - -#include "nepomuk_export.h" - -#include -#include - - -namespace Soprano { - class Model; -} - -namespace Nepomuk { - class Resource; - class Variant; - class ResourceManagerHelper; - class ResourceManagerPrivate; - namespace Types { - class Class; - class Property; - } - - /** - * \class ResourceManager resourcemanager.h Nepomuk/ResourceManager - * - * \brief The ResourceManager is the central \a %Nepomuk configuration point. - * - * Use the initialized() method to check the availabity of the %Nepomuk system. - * Signals nepomukSystemStarted() and nepomukSystemStopped() can be used to - * enable or disable Nepomuk-specific GUI elements. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT ResourceManager : public QObject - { - Q_OBJECT - - public: - static ResourceManager* instance(); - - /** - * In KDE 4.3 support for multiple ResourceManager instances - * has been introduced. To keep binary compatibility both the constructor's - * and destructor's access visibility could not be changed. Thus, instead of deleting - * a custom ResourceManager instance the standard way, one has to call this - * method or use QObject::deleteLater. - * - * \since 4.3 - */ - void deleteInstance(); - - /** - * Initialize the Nepomuk framework. This method will initialize the communication with - * the local Nepomuk-KDE services, ie. the data repository. It will trigger a reconnect - * to the %Nepomuk database. - * - * There is normally no reason to call this method manually except when using multiple - * threads. In that case it is highly recommended to call this method in the main thread - * before doing anything else. - * - * \return 0 if all necessary components could be found and -1 otherwise. - */ - int init(); - - /** - * \return true if init() has been called successfully, ie. the KMetaData system is connected - * to the local RDF repository service and ready to work. - */ - bool initialized() const; - - /** - * Retrieve the main data storage model. - */ - Soprano::Model* mainModel(); - - /** - * Override the main model used for all storage. By default the main model - * used is the Nepomuk server main model. - * - * \param model The model to use instead of the Nepomuk server or 0 to reset. - * - * \since 4.1 - */ - void setOverrideMainModel( Soprano::Model* model ); - - /** - * \deprecated Use the Resource constructor directly. - * - * Creates a Resource object representing the data referenced by \a uri. - * The result is the same as from using the Resource::Resource( const QString&, const QString& ) - * constructor with an empty type. - * - * \return The Resource representing the data at \a uri or an invalid Resource object if the local - * NEPOMUK RDF store does not contain an object with URI \a uri. - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED Resource createResourceFromUri( const QString& uri ); -#endif - - /** - * Remove the resource denoted by \a uri completely. - * - * This method is just a wrapper around Resource::remove. The result - * is the same. - */ - void removeResource( const QString& uri ); - - /** - * Retrieve a list of all resource managed by this manager. - * - * \warning This list will be very big. Usage of this method is - * discouraged. Use Query::QueryServiceClient in combination with an - * empty Query::Query instead. - * - * \since 4.3 - */ - QList allResources(); - - /** - * Retrieve a list of all resources of the specified \a type. - * - * This includes Resources that are not synced yet so it might - * not represent exactly the state as in the RDF store. - * - * \warning This list can be very big. Usage of this method is - * discouraged. Use Query::QueryServiceClient in combination with - * a Query::Query containing one Query::ResourceTypeTerm instead. - */ - QList allResourcesOfType( const QUrl& type ); - - /** - * \deprecated Use allResourcesOfType( const QString& type ) - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED QList allResourcesOfType( const QString& type ); -#endif - - /** - * Retrieve a list of all resources that have property \a uri defined with a value of \a v. - * - * This includes Resources that are not synced yet so it might - * not represent exactly the state as in the RDF store. - * - * \param uri The URI identifying the property. If this URI does - * not include a namespace the default namespace is - * prepended. - * \param v The value all returned resources should have set as properts \a uri. - * - * \warning This list can be very big. Usage of this method is - * discouraged. Use Query::QueryServiceClient in combination with - * a Query::Query containing one Query::ComparisonTerm instead. - */ - QList allResourcesWithProperty( const QUrl& uri, const Variant& v ); - - /** - * \deprecated Use allResourcesWithProperty( const QString& type ) - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED QList allResourcesWithProperty( const QString& uri, const Variant& v ); -#endif - - /** - * %ResourceManager caches resource locally so subsequent access is faster. - * This method clears this cache, deleting any Resource that is not used. - * - * \since 4.4 - */ - void clearCache(); - - /** - * \deprecated Use generateUniqueUri(const QString&) - * - * Generates a unique URI that is not used in the store yet. This method ca be used to - * generate URIs for virtual types such as Tag. - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED QString generateUniqueUri(); -#endif - - /** - * Generates a unique URI that is not used in the store yet. This method can be used to - * generate URIs for virtual types such as Tag. - * - * \param label A label that the algorithm should use to try to create a more readable URI. - * - * \return A new unique URI which can be used to define a new resource. - * - * \since 4.2 - */ - QUrl generateUniqueUri( const QString& label ); - - /** - * \internal Non-public API. Used by Resource to signalize errors. - */ - void notifyError( const QString& uri, int errorCode ); - - /** - * Create a new ResourceManager instance which uses model as its - * override model. This allows to use multiple instances of ResourceManager - * at the same time. Normally one does not need this method as the singleton - * accessed via instance() should be enough. - * - * \param model The model to read and write data from and to. - * - * \since 4.3 - */ - static ResourceManager* createManagerForModel( Soprano::Model* model ); - - Q_SIGNALS: - /** - * This signal gets emitted whenever a Resource changes due to a sync procedure. - * Be aware that modifying resources locally via the Resource::setProperty method - * does not result in a resourceModified signal being emitted. - * - * \param uri The URI of the modified resource. - * - * NOT IMPLEMENTED YET - */ - void resourceModified( const QString& uri ); - - /** - * Whenever a problem occurs (like for example failed resource syncing) this - * signal is emitted. - * - * \param uri The resource related to the error. - * \param errorCode The type of the error (Resource::ErrorCode) - */ - void error( const QString& uri, int errorCode ); - - /** - * Emitted once the Nepomuk system is up and can be used. - * - * \warning This signal will not be emitted if the Nepomuk - * system is running when the ResourceManager is created. - * Use initialized() to check the status. - * - * \since 4.4 - */ - void nepomukSystemStarted(); - - /** - * Emitted once the Nepomuk system goes down. - * - * \since 4.4 - */ - void nepomukSystemStopped(); - - private Q_SLOTS: - void slotPropertyAdded(const Nepomuk::Resource &res, const Nepomuk::Types::Property &prop, const QVariant &value); - void slotPropertyRemoved(const Nepomuk::Resource &res, const Nepomuk::Types::Property &prop, const QVariant &value); - - private: - friend class Nepomuk::Resource; - friend class Nepomuk::ResourceManagerPrivate; - - ResourceManager(); - ~ResourceManager(); - - static ResourceManager* s_instance; - - ResourceManagerPrivate* const d; - - Q_PRIVATE_SLOT( d, void _k_storageServiceInitialized(bool) ) - Q_PRIVATE_SLOT( d, void _k_dbusServiceUnregistered(QString) ) - }; -} - -#endif diff --git a/nepomuk/core/resourcemanager_p.h b/nepomuk/core/resourcemanager_p.h deleted file mode 100644 index 9e61300c..00000000 --- a/nepomuk/core/resourcemanager_p.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2009 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_RESOURCE_MANAGER_P_H_ -#define _NEPOMUK_RESOURCE_MANAGER_P_H_ - -#include - -#include - -#include // for qHash(QUrl) - -#include "resourcedata.h" - - -namespace Soprano { - class Model; -} - - -namespace Nepomuk { - - class ResourceManager; - class MainModel; - class ResourceWatcher; - - typedef QHash ResourceDataHash; - - class ResourceManagerPrivate - { - public: - ResourceManagerPrivate( ResourceManager* manager ); - - Nepomuk::MainModel* mainModel; - Soprano::Model* overrideModel; - - /// used to protect the initialization - QMutex initMutex; - - /// used to protect all data in ResourceManager - QMutex mutex; - - /// contains all initialized ResourceData object, i.e. all those which - /// successfully ran determineUri() - ResourceDataHash m_initializedData; - - /// contains all non-initialized ResourceData objects created in data(QUrl) - ResourceDataHash m_uriKickoffData; - - QAtomicInt dataCnt; - - ResourceManager* m_manager; - - ResourceWatcher* m_watcher; - - /** - * The Nepomuk lib is based on the fact that for each uri only one ResourceData object is - * created at all times. This method searches for an existing data object to reuse or creates - * a new one if none exists. - * - * \param uriOrId The URI or identifier of the resource is question. - * \type The type of the resource. - * - * The Resource constructors use this method in combination with ref() - */ - ResourceData* data( const QString& uriOrId, const QUrl& type ); - - /** - * The Nepomuk lib is based on the fact that for each uri only one ResourceData object is - * created at all times. This method searches for an existing data object to reuse or creates - * a new one if none exists. - * - * \param uri The URI of the resource is question or it's nie:url or even its identified stored in - * a QUrl object. - * \type The type of the resource. - * - * The Resource constructors use this method in combination with ref() - */ - ResourceData* data( const QUrl& uri, const QUrl& type ); - - /** - * In contrast to data(QUrl,QUrl) this method avoids the overhead of determining the resource URI - * via ResourceData::determineUri() and simply uses \p uri as the resource URI. - */ - ResourceData* dataForResourceUri( const QUrl& uri, const QUrl& type ); - - /** - * Delete unused ResourceData objects from the cache. - * \param num The number of needed slots. The ResourceData constructor - * uses this to make room for itself. Use < 0 to free the complete cache. - * - * Does NOT lock the mutex. - */ - void cleanupCache( int num = 1 ); - - bool shouldBeDeleted( ResourceData* rd ) const; - - void addToKickOffList( ResourceData* rd, const QSet& uris ); - - QList allResourceData(); - QList allResourceDataOfType( const QUrl& type ); - QList allResourceDataWithProperty( const QUrl& _uri, const Variant& v ); - - void _k_storageServiceInitialized( bool ); - void _k_dbusServiceUnregistered( const QString& serviceName ); - - private: - ResourceData* findData( const QUrl& uri ); - - QUrl m_mainContext; - }; -} - -#endif diff --git a/nepomuk/core/resourcewatcher.cpp b/nepomuk/core/resourcewatcher.cpp deleted file mode 100644 index 453be8f7..00000000 --- a/nepomuk/core/resourcewatcher.cpp +++ /dev/null @@ -1,307 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2011 Vishesh Handa - Copyright (C) 2011 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -*/ - - -#include "resourcewatcher.h" -#include "resourcewatcherconnectioninterface.h" -#include "resourcewatchermanagerinterface.h" -#include "resourcemanager.h" - -#include - -#include "resource.h" - -#include "kurl.h" -#include "kdebug.h" - -namespace { - QString convertUri(const QUrl& uri) { - return KUrl(uri).url(); - } - - QStringList convertUris(const QList& uris) { - QStringList cs; - foreach(const QUrl& uri, uris) { - cs << convertUri(uri); - } - return cs; - } - - QList convertUris(const QStringList& uris) { - QList us; - foreach(const QString& uri, uris) { - us << KUrl(uri); - } - return us; - } -} - -class Nepomuk::ResourceWatcher::Private { -public: - QList m_types; - QList m_resources; - QList m_properties; - - org::kde::nepomuk::ResourceWatcherConnection * m_connectionInterface; - org::kde::nepomuk::ResourceWatcher * m_watchManagerInterface; -}; - -Nepomuk::ResourceWatcher::ResourceWatcher(QObject* parent) - : QObject(parent), - d(new Private) -{ - d->m_watchManagerInterface - = new org::kde::nepomuk::ResourceWatcher( "org.kde.NepomukStorage", - "/resourcewatcher", - QDBusConnection::sessionBus() ); - d->m_connectionInterface = 0; -} - -Nepomuk::ResourceWatcher::~ResourceWatcher() -{ - stop(); - delete d; -} - -bool Nepomuk::ResourceWatcher::start() -{ - stop(); - - // - // Convert to list of strings - // - QList uris = convertUris(d->m_resources); - QList props = convertUris(d->m_properties); - QList types_ = convertUris(d->m_types); - - // - // Watch for the RW service to (re-)appear and then re-connect to make sure we always get updates - // We create this watcher even if we fail to connect below. Thus, once the rw service comes up we - // can re-attach. - // - connect(ResourceManager::instance(), SIGNAL(nepomukSystemStarted()), this, SLOT(start())); - - // - // Create the dbus object to watch - // - QDBusPendingReply reply = d->m_watchManagerInterface->watch( uris, props, types_ ); - QDBusObjectPath path = reply.value(); - - if(!path.path().isEmpty()) { - d->m_connectionInterface = new org::kde::nepomuk::ResourceWatcherConnection( "org.kde.NepomukStorage", - path.path(), - QDBusConnection::sessionBus() ); - connect( d->m_connectionInterface, SIGNAL(propertyAdded(QString,QString,QVariantList)), - this, SLOT(slotPropertyAdded(QString,QString,QVariantList)) ); - connect( d->m_connectionInterface, SIGNAL(propertyRemoved(QString,QString,QVariantList)), - this, SLOT(slotPropertyRemoved(QString,QString,QVariantList)) ); - connect( d->m_connectionInterface, SIGNAL(resourceCreated(QString,QStringList)), - this, SLOT(slotResourceCreated(QString,QStringList)) ); - connect( d->m_connectionInterface, SIGNAL(propertyChanged(QString,QString,QVariantList,QVariantList)), - this, SLOT(slotPropertyChanged(QString,QString,QVariantList,QVariantList)) ); - connect( d->m_connectionInterface, SIGNAL(resourceRemoved(QString,QStringList)), - this, SLOT(slotResourceRemoved(QString,QStringList)) ); - connect( d->m_connectionInterface, SIGNAL(resourceTypeAdded(QString,QString)), - this, SLOT(slotResourceTypeAdded(QString,QString)) ); - connect( d->m_connectionInterface, SIGNAL(resourceTypeRemoved(QString,QString)), - this, SLOT(slotResourceTypeRemoved(QString,QString)) ); - return true; - } - else { - return false; - } -} - -void Nepomuk::ResourceWatcher::stop() -{ - if (d->m_connectionInterface) { - d->m_connectionInterface->close(); - delete d->m_connectionInterface; - d->m_connectionInterface = 0; - } - - disconnect(ResourceManager::instance(), SIGNAL(nepomukSystemStarted()), this, SLOT(start())); -} - -void Nepomuk::ResourceWatcher::addProperty(const Nepomuk::Types::Property& property) -{ - d->m_properties << property.uri(); - if(d->m_connectionInterface) { - d->m_connectionInterface->addProperty(convertUri(property.uri())); - } -} - -void Nepomuk::ResourceWatcher::addResource(const Nepomuk::Resource& res) -{ - d->m_resources << res.resourceUri(); - if(d->m_connectionInterface) { - d->m_connectionInterface->addResource(convertUri(res.resourceUri())); - } -} - -void Nepomuk::ResourceWatcher::addType(const Nepomuk::Types::Class& type) -{ - d->m_types << type.uri(); - if(d->m_connectionInterface) { - d->m_connectionInterface->addType(convertUri(type.uri())); - } -} - -void Nepomuk::ResourceWatcher::removeProperty(const Nepomuk::Types::Property& property) -{ - d->m_properties.removeAll(property.uri()); - if(d->m_connectionInterface) { - d->m_connectionInterface->removeProperty(convertUri(property.uri())); - } -} - -void Nepomuk::ResourceWatcher::removeResource(const Nepomuk::Resource& res) -{ - d->m_resources.removeAll(res.resourceUri()); - if(d->m_connectionInterface) { - d->m_connectionInterface->removeResource(convertUri(res.resourceUri())); - } -} - -void Nepomuk::ResourceWatcher::removeType(const Nepomuk::Types::Class& type) -{ - d->m_types.removeAll(type.uri()); - if(d->m_connectionInterface) { - d->m_connectionInterface->removeType(convertUri(type.uri())); - } -} - -QList< Nepomuk::Types::Property > Nepomuk::ResourceWatcher::properties() const -{ - QList< Nepomuk::Types::Property > props; - foreach(const QUrl& uri, d->m_properties) - props << Types::Property(uri); - return props; -} - -QList Nepomuk::ResourceWatcher::resources() const -{ - QList resources; - foreach(const QUrl& uri, d->m_resources) - resources << Resource::fromResourceUri(uri); - return resources; -} - -QList< Nepomuk::Types::Class > Nepomuk::ResourceWatcher::types() const -{ - QList types; - foreach(const QUrl& uri, d->m_types) - types << Types::Class(uri); - return types; -} - -int Nepomuk::ResourceWatcher::propertyCount() const -{ - return d->m_properties.size(); -} - -int Nepomuk::ResourceWatcher::resourceCount() const -{ - return d->m_resources.size(); -} - -int Nepomuk::ResourceWatcher::typeCount() const -{ - return d->m_types.size(); -} - -void Nepomuk::ResourceWatcher::setProperties(const QList< Nepomuk::Types::Property >& properties_) -{ - d->m_properties.clear(); - foreach(const Nepomuk::Types::Property& p, properties_) { - d->m_properties << p.uri(); - } - - if(d->m_connectionInterface) { - d->m_connectionInterface->setProperties(convertUris(d->m_properties)); - } -} - -void Nepomuk::ResourceWatcher::setResources(const QList< Nepomuk::Resource >& resources_) -{ - d->m_resources.clear(); - foreach(const Nepomuk::Resource& res, resources_) { - d->m_resources << res.resourceUri(); - } - - if(d->m_connectionInterface) { - d->m_connectionInterface->setResources(convertUris(d->m_resources)); - } -} - -void Nepomuk::ResourceWatcher::setTypes(const QList< Nepomuk::Types::Class >& types_) -{ - d->m_types.clear(); - foreach(const Nepomuk::Types::Class& t, types_) { - d->m_types << t.uri(); - } - - if(d->m_connectionInterface) { - d->m_connectionInterface->setTypes(convertUris(d->m_types)); - } -} - -void Nepomuk::ResourceWatcher::slotResourceCreated(const QString &res, const QStringList &types) -{ - emit resourceCreated(Nepomuk::Resource::fromResourceUri(KUrl(res)), convertUris(types)); -} - -void Nepomuk::ResourceWatcher::slotResourceRemoved(const QString &res, const QStringList &types) -{ - emit resourceRemoved(KUrl(res), convertUris(types)); -} - -void Nepomuk::ResourceWatcher::slotResourceTypeAdded(const QString &res, const QString &type) -{ - emit resourceTypeAdded(KUrl(res), KUrl(type)); -} - -void Nepomuk::ResourceWatcher::slotResourceTypeRemoved(const QString &res, const QString &type) -{ - emit resourceTypeRemoved(KUrl(res), KUrl(type)); -} - -void Nepomuk::ResourceWatcher::slotPropertyAdded(const QString& res, const QString& prop, const QVariantList &objects) -{ - foreach(const QVariant& v, objects) { - emit propertyAdded( Resource::fromResourceUri(KUrl(res)), Types::Property( KUrl(prop) ), v ); - } -} - -void Nepomuk::ResourceWatcher::slotPropertyRemoved(const QString& res, const QString& prop, const QVariantList &objects) -{ - foreach(const QVariant& v, objects) { - emit propertyRemoved( Resource::fromResourceUri(KUrl(res)), Types::Property( KUrl(prop) ), v ); - } -} - -void Nepomuk::ResourceWatcher::slotPropertyChanged(const QString& res, const QString& prop, const QVariantList& oldObjs, const QVariantList& newObjs) -{ - emit propertyChanged( Resource::fromResourceUri(KUrl(res)), Types::Property( KUrl(prop) ), - oldObjs, newObjs ); -} - -#include "resourcewatcher.moc" - diff --git a/nepomuk/core/resourcewatcher.h b/nepomuk/core/resourcewatcher.h deleted file mode 100644 index 718cbb08..00000000 --- a/nepomuk/core/resourcewatcher.h +++ /dev/null @@ -1,342 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2011 Vishesh Handa - Copyright (C) 2011 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -*/ - - -#ifndef RESOURCEWATCHER_H -#define RESOURCEWATCHER_H - -#include "../types/class.h" -#include "../types/property.h" -#include "resource.h" - -#include -#include - -namespace Nepomuk { - - /** - * \class ResourceWatcher resourcewatcher.h - * - * \brief Selectively monitor the nepomuk repository for changes. - * - * Resources may be monitored on the basis of types, properties, and uris. - * - * Changes may be monitored in one of the following ways: - * -# By resources - - * Specify the exact resources that should be watched. Any changes made to the specified resources - * (Excluding \ref nepomuk_dms_metadata) will be notified through the propertyAdded() and propertyRemoved() - * signals. Notifications will also be sent if any of the watched resources is deleted. - * -# By resources and properties - - * Specify the exact resources and their properties. Any changes made to the specified resources - * which touch one of the specified properties will be notified through the propertyAdded() and propertyRemoved() - * signals. - * -# By types - - * Specific types may be specified via add/setType. If types are set, then notifications will be - * sent for all new resources of that type. This includes property changes and resource creation and removal. - * TODO: add flags that allow to only watch for resource creation and removal. - * -# By types and properties - - * Both the types and properties may be specified. Notifications will be sent for property changes - * in resource with the specified types. - * - * \section nepomuk_rw_examples Resource Watcher Usage Example - * - * The following code creates a new ResourceWatcher, configures it to listen to changes on the \c nmm:performer - * property on one specific resource \c res. - * - * \code - * Nepomuk::ResourceWatcher* watcher = new Nepomuk::ResourceWatcher(this); - * watcher->addResource(res); - * watcher->addProperty(NMM:performer()); - * connect(watcher, SIGNAL(propertyAdded(Nepomuk::Resource, Nepomuk::Types::Property, QVariant)), - * this, SLOT(slotPropertyChanged())); - * connect(watcher, SIGNAL(propertyRemoved(Nepomuk::Resource, Nepomuk::Types::Property, QVariant)), - * this, SLOT(slotPropertyChanged())); - * rwatcher->start(); - * \endcode - * - * \author Vishesh Handa , Sebastian Trueg - * - * \ingroup nepomuk_datamanagement - */ - class ResourceWatcher : public QObject - { - Q_OBJECT - - public: - /** - * \brief Create a new %ResourceWatcher instance. - * - * This instance will not emit any signals before it has been configured - * and started. - */ - ResourceWatcher( QObject* parent = 0 ); - - /** - * \brief Destructor. - */ - virtual ~ResourceWatcher(); - - public Q_SLOTS: - /** - * \brief Add a type to be watched. - * - * Every resource of this type will be watched for changes. - * - * \sa setTypes() - */ - void addType( const Types::Class & type ); - - /** - * \brief Add a resource to be watched. - * - * Every change to this resource will be - * signalled, depending on the configured properties(). - * - * \sa setResources() - */ - void addResource( const Nepomuk::Resource & res ); - - /** - * \brief Add a property to be watched. - * - * Every change to a value of this property - * will be signalled, depending on the configured resources() or types(). - * - * \sa setProperties() - */ - void addProperty( const Types::Property & property ); - - /** - * \brief Remove a type to be watched. - * - * Every resource of this type will be watched for changes. - * - * \sa setTypes() - */ - void removeType( const Types::Class & type ); - - /** - * \brief Remove a resource to be watched. - * - * Every change to this resource will be - * signalled, depending on the configured properties(). - * - * \sa setResources() - */ - void removeResource( const Nepomuk::Resource & res ); - - /** - * \brief Remove a property to be watched. - * - * Every change to a value of this property - * will be signalled, depending on the configured resources() or types(). - * - * \sa setProperties() - */ - void removeProperty( const Types::Property & property ); - - /** - * \brief Set the types to be watched. - * - * Every resource having one of these types will be watched for changes. - * - * \sa addType() - */ - void setTypes( const QList & types_ ); - - /** - * \brief Set the resources to be watched. - * - * Every change to one of these resources will be - * signalled, depending on the configured properties(). - * - * \sa addResource() - */ - void setResources( const QList & resources_ ); - - /** - * \brief Set the properties to be watched. - * - * Every change to a value of any of these properties - * will be signalled, depending on the configured resources() or types(). - * - * \sa addProperty() - */ - void setProperties( const QList & properties_ ); - - /** - * \brief The types that have been configured via addType() and setTypes(). - * - * Every resource having one of these types will be watched - * for changes. - */ - QList types() const; - - /** - * \brief Return the number of types that are being watched - * - * This method is slightly faster than called types().count() - * - * \sa types addType setType - */ - int typeCount() const; - - /** - * \brief The resources that have been configured via addResource() and setResources(). - * - * Every change to one of these resources will be - * signalled, depending on the configured properties(). - */ - QList resources() const; - - /** - * \brief Return the number of resources that are being watched - * - * This method is slightly faster than called resources().count() - * - * \sa resources addResource setResources - */ - int resourceCount() const; - - /** - * \brief The properties that have been configured via addProperty() and setProperties(). - * - * Every change to a value of any of these properties - * will be signalled, depending on the configured resources() or types(). - */ - QList properties() const; - - /** - * \brief Return the number of properties that are being watched - * - * This method is slightly faster than called properties().count() - * - * \sa properties addProperty setProperty - */ - int propertyCount() const; - - /** - * \brief Start the signalling of changes. - * - * Before calling this method no signal will be emitted. In - * combination with stop() this allows to suspend the watching. - * Calling start() multiple times has no effect. - */ - bool start(); - - /** - * \brief Stop the signalling of changes. - * - * Allows to stop the watcher which has been started - * via start(). Calling stop() multiple times has no effect. - */ - void stop(); - - Q_SIGNALS: - /** - * \brief This signal is emitted when a new resource is created. - * \param resource The newly created resource. - * \param types The types the new resource has. If types() have been configured this list will always - * contain one of the configured types. - */ - void resourceCreated( const Nepomuk::Resource & resource, const QList& types ); //FIXME: Use either Resource or uri, not a mix - - /** - * \brief This signal is emitted when a resource is deleted. - * \param uri The resource URI of the removed resource. - * \param types The types the removed resource had. If types() have been configured this list will always - * contain one of the configured types. - */ - void resourceRemoved( const QUrl & uri, const QList& types ); - - /** - * \brief This signal is emitted when a type has been added to a resource. This does not include creation which - * is signalled via resourceCreated(). It only applies to changes in a resource's types. - * \param res The changed resource. - * \param type The newly added type. If types() have been configured it will be one of them. - */ - void resourceTypeAdded( const Nepomuk::Resource & res, const Types::Class & type ); - - /** - * \brief This signal is emitted when a type has been removed from a resource. - * - * This does not include removal of entire resources which is signalled via resourceRemoved(). - * It only applies to changes in a resource's types. - * \param res The changed resource. - * \param type The removed type. If types() have been configured it will be one of them. - */ - void resourceTypeRemoved( const Nepomuk::Resource & res, const Types::Class & type ); - - /** - * \brief This signal is emitted when a property value is added. - * \param resource The changed resource. - * \param property The property which has a new value. - * \param value The newly added property value. - */ - void propertyAdded( const Nepomuk::Resource & resource, - const Nepomuk::Types::Property & property, - const QVariant & value ); - - /** - * \brief This signal is emitted when a property value is removed. - * \param resource The changed resource. - * \param property The property which was changed. - * \param value The removed property value. - */ - void propertyRemoved( const Nepomuk::Resource & resource, - const Nepomuk::Types::Property & property, - const QVariant & value ); - - /** - * \brief This signal is emitted when a property value is changed. - * - * This signal cannot be emitted for all changes. It doesn't work if a property is first - * removed and then set, cause the Data Mangement Service does not maintain an internal - * cache for the purpose of emitting the propertyChanged signal. - * - * Specially, since one could theoretically take forever between the removal and the - * setting of the property. - * - * \param resource The changed resource. - * \param property The property which was changed. - * \param oldValue The removed property value. - */ - void propertyChanged( const Nepomuk::Resource & resource, - const Nepomuk::Types::Property & property, - const QVariantList & oldValue, - const QVariantList & newValue ); - - private Q_SLOTS: - void slotResourceCreated(const QString& res, const QStringList& types); - void slotResourceRemoved(const QString& res, const QStringList& types); - void slotResourceTypeAdded(const QString& res, const QString& type); - void slotResourceTypeRemoved(const QString& res, const QString& type); - void slotPropertyAdded(const QString& res, const QString& prop, const QVariantList& objects); - void slotPropertyRemoved(const QString& res, const QString& prop, const QVariantList& objects); - void slotPropertyChanged(const QString& res, const QString& prop, - const QVariantList & oldObjs, - const QVariantList & newObjs); - private: - class Private; - Private * d; - }; -} - -#endif // RESOURCEWATCHER_H diff --git a/nepomuk/core/tag.cpp b/nepomuk/core/tag.cpp deleted file mode 100644 index b056f760..00000000 --- a/nepomuk/core/tag.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2007-2009 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "tag.h" - -#include "tools.h" -#include "variant.h" -#include "resourcemanager.h" -#include "resource.h" - -#include - - -Nepomuk::Tag::Tag() - : Resource() -{ -} - - -Nepomuk::Tag::Tag( ResourceManager* manager ) - : Resource( manager ) -{ -} - - -Nepomuk::Tag::Tag( const Tag& res ) - : Resource( res ) -{ -} - - -Nepomuk::Tag::Tag( const Nepomuk::Resource& res ) - : Resource( res ) -{ -} - - -Nepomuk::Tag::Tag( const QString& uri ) - : Resource( uri, Soprano::Vocabulary::NAO::Tag() ) -{ -} - - -Nepomuk::Tag::Tag( const QString& uri, ResourceManager* manager ) - : Resource( uri, Soprano::Vocabulary::NAO::Tag(), manager ) -{ -} - - -Nepomuk::Tag::Tag( const QUrl& uri ) - : Resource( uri, Soprano::Vocabulary::NAO::Tag() ) -{ -} - - -Nepomuk::Tag::Tag( const QUrl& uri, ResourceManager* manager ) - : Resource( uri, Soprano::Vocabulary::NAO::Tag(), manager ) -{ -} - - -Nepomuk::Tag::Tag( const QString& uri, const QUrl& type ) - : Resource( uri, type ) -{ -} - - -Nepomuk::Tag::Tag( const QString& uri, const QUrl& type, ResourceManager* manager ) - : Resource( uri, type, manager ) -{ -} - - -Nepomuk::Tag::Tag( const QUrl& uri, const QUrl& type ) - : Resource( uri, type ) -{ -} - - -Nepomuk::Tag::Tag( const QUrl& uri, const QUrl& type, ResourceManager* manager ) - : Resource( uri, type, manager ) -{ -} - - -Nepomuk::Tag::~Tag() -{ -} - - -Nepomuk::Tag& Nepomuk::Tag::operator=( const Tag& res ) -{ - Resource::operator=( res ); - return *this; -} - - -QString Nepomuk::Tag::resourceTypeUri() -{ - return Soprano::Vocabulary::NAO::Tag().toString(); -} - - -QList Nepomuk::Tag::tagOf() const -{ - return convertResourceList( manager()->allResourcesWithProperty( Soprano::Vocabulary::NAO::hasTag(), *this ) ); -} - - -// static -QList Nepomuk::Tag::allTags() -{ - return Nepomuk::convertResourceList( ResourceManager::instance()->allResourcesOfType( Soprano::Vocabulary::NAO::Tag() ) ); -} diff --git a/nepomuk/core/tag.h b/nepomuk/core/tag.h deleted file mode 100644 index 3a7ba30b..00000000 --- a/nepomuk/core/tag.h +++ /dev/null @@ -1,148 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2007-2009 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _TAG_H_ -#define _TAG_H_ - -#include "resource.h" -#include "nepomuk_export.h" - -namespace Nepomuk { - - /** - * \class Tag tag.h Nepomuk/Tag - * - * A Tag can be assigned to any Thing. This allows simple grouping - * of resources. Each Tag is identifed by its label which should - * be unique. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT Tag : public Resource - { - public: - /** - * Create a new empty and invalid Tag instance - */ - Tag(); - - /** - * Create a new empty and invalid Tag instance - * - * \param manager The resource manager to use. This allows to mix resources from different - * managers and, thus, different models. - * - * \since 4.3 - */ - Tag( ResourceManager* manager ); - - /** - * Default copy constructor - */ - Tag( const Tag& ); - - /** - * \overload - */ - Tag( const Resource& ); - - /** - * Create a new Tag instance representing the resource - * referenced by \a uriOrIdentifier. - */ - Tag( const QString& uriOrIdentifier ); - - /** - * Create a new Tag instance representing the resource - * referenced by \a uriOrIdentifier. - * - * \param manager The resource manager to use. This allows to mix resources from different - * managers and, thus, different models. - * - * \since 4.3 - */ - Tag( const QString& uriOrIdentifier, ResourceManager* manager ); - - /** - * Create a new Tag instance representing the resource - * referenced by \a uri. - */ - Tag( const QUrl& uri ); - - /** - * Create a new Tag instance representing the resource - * referenced by \a uri. - * - * \param manager The resource manager to use. This allows to mix resources from different - * managers and, thus, different models. - * - * \since 4.3 - */ - Tag( const QUrl& uri, ResourceManager* manager ); - - /** - * Destructor - */ - ~Tag(); - - Tag& operator=( const Tag& ); - - /** - * Get all resources that have this resource set as property 'Tag'. - * Each Resource can be tagged with an arbitrary number of Tags. - * This allows a simple grouping of resources. \sa ResourceManager::allResourcesWithProperty - */ - QList tagOf() const; - - /** - * Retrieve a list of all available Tag resources. This list consists - * of all resource of type Tag that are stored in the local Nepomuk - * meta data storage and any changes made locally. Be aware that - * in some cases this list can get very big. - * - * In those cases it might be better to use the asyncronous approach - * via Query::QueryServiceClient and a Query::ResourceTypeTerm with - * type Soprano::Vocabulary::NAO::Tag(). - */ - static QList allTags(); - - - /** - * \return The URI of the resource type that is used in Tag instances. - */ - static QString resourceTypeUri(); - - protected: - Tag( const QString& uri, const QUrl& type ); - Tag( const QUrl& uri, const QUrl& type ); - - /** - * \since 4.3 - */ - Tag( const QString& uri, const QUrl& type, ResourceManager* manager ); - - /** - * \since 4.3 - */ - Tag( const QUrl& uri, const QUrl& type, ResourceManager* manager ); - }; -} - -#endif diff --git a/nepomuk/core/thing.cpp b/nepomuk/core/thing.cpp deleted file mode 100644 index 157c0045..00000000 --- a/nepomuk/core/thing.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2008-2009 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "thing.h" -#include "pimo.h" -#include "variant.h" - -Nepomuk::Thing::Thing( const QUrl& uri, const QUrl& pimoType ) - : Resource( uri, pimoType.isEmpty() ? Vocabulary::PIMO::Thing() : pimoType ) -{ - // FIXME: somehow ensure that pimoType is actually a pimo:Thing. Maybe - // use operator= instead of the contructor and check the value beforehand -} - - -Nepomuk::Thing::Thing( const QUrl& uri, const QUrl& pimoType, ResourceManager* manager ) - : Resource( uri, pimoType.isEmpty() ? Vocabulary::PIMO::Thing() : pimoType, manager ) -{ - // FIXME: somehow ensure that pimoType is actually a pimo:Thing. Maybe - // use operator= instead of the contructor and check the value beforehand -} - - -Nepomuk::Thing::Thing( const QString& uriOrName, const QUrl& pimoType ) - : Resource( uriOrName, pimoType.isEmpty() ? Vocabulary::PIMO::Thing() : pimoType ) -{ - // FIXME: s.o. -} - - -Nepomuk::Thing::Thing( const QString& uriOrName, const QUrl& pimoType, ResourceManager* manager ) - : Resource( uriOrName, pimoType.isEmpty() ? Vocabulary::PIMO::Thing() : pimoType, manager ) -{ - // FIXME: s.o. -} - - -Nepomuk::Thing::Thing( const Thing& other ) - : Resource( other ) -{ - // FIXME: s.o. -} - - -Nepomuk::Thing::Thing( const Resource& other ) - : Resource( other ) -{ - // FIXME: s.o. -} - - -Nepomuk::Thing::Thing( Nepomuk::ResourceData* data ) - : Resource( data ) -{ -} - - -Nepomuk::Thing& Nepomuk::Thing::operator=( const Thing& res ) -{ - Resource::operator=( res ); - return *this; -} - - -Nepomuk::Thing& Nepomuk::Thing::operator=( const Resource& res ) -{ - Resource::operator=( res ); - return *this; -} - - -Nepomuk::Thing& Nepomuk::Thing::operator=( const QUrl& res ) -{ - Resource::operator=( res ); - return *this; -} - - -Nepomuk::Thing::~Thing() -{ -} - - -QList Nepomuk::Thing::groundingOccurrences() const -{ - return property( Vocabulary::PIMO::groundingOccurrence() ).toResourceList(); -} - - -QList Nepomuk::Thing::referencingOccurrences() const -{ - return property( Vocabulary::PIMO::referencingOccurrence() ).toResourceList(); -} - - -QList Nepomuk::Thing::occurrences() const -{ - return property( Vocabulary::PIMO::occurrence() ).toResourceList(); -} - - -void Nepomuk::Thing::addGroundingOccurrence( const Nepomuk::Resource &res ) -{ - addProperty(Nepomuk::Vocabulary::PIMO::groundingOccurrence(), res); -} - - -// void Nepomuk::Thing::merge( Thing other ) -// { -// } diff --git a/nepomuk/core/thing.h b/nepomuk/core/thing.h deleted file mode 100644 index b5167619..00000000 --- a/nepomuk/core/thing.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2008-2009 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_THING_H_ -#define _NEPOMUK_THING_H_ - -#include "resource.h" -#include "nepomuk_export.h" - -// FIXME: (Would it even make sense to check in Nepomuk::Resource if a resource is a pimo:Thing and if so, -// use the PIMO context? Or should we handle that through the Nepomuk::PimoThing class?) - -namespace Nepomuk { - /** - * \class Thing thing.h Nepomuk/Thing - * - * \brief A Nepomuk PIMO Thing resource. - * - * A Thing represents a unique abstract concept/idea or real-world - * entity which can have multiple representations or occurrences. - * - * A typical example for a Thing is a unique person resource - * which identifies the person itself, not any representation - * such as an addressbook entry. - * - * Things are typically grounded via application resources, - * i.e. those resources that are created or handled by applications. - * Again the typical example is the addressbook entry. - * - * In general it is recommended to alway use the Thing instead of the - * grounding resource to annotate, i.e. to add tags, or relate to other - * resources. The advantage is its uniqueness. While there can be many - * occurrences of one concept there is only one Thing, identifying - * uniquely. - * - * \author Sebastian Trueg - * - * \since 4.2 - */ - class NEPOMUK_EXPORT Thing : public Resource - { - public: - /** - * Create a Thing object with URI \p uri. If the Thing does not - * exist in the Nepomuk storage yet, it will be created once - * a writing method is called (such as Resource::setProperty). - * - * \param uri The URI of the Thing. If empty, a new random one - * will be created. - * \param pimoType The type of this Thing. Needs to be a subtype - * of pimo:Thing. If empty defaults to pimo:Thing. - */ - Thing( const QUrl& uri = QUrl(), const QUrl& pimoType = QUrl() ); - - /** - * \overload - * - * \param manager The resource manager to use. This allows to mix resources from different - * managers and, thus, different models. - * - * \since 4.3 - */ - Thing( const QUrl& uri, const QUrl& pimoType, ResourceManager* manager ); - - /** - * Create a new Thing with label or URI \p uriOrName - * - * \param uriOrName The URI or the label of the Thing. The constructor - * tries hard to find the Thing associated. If it is not found, a new - * Thing will be created. - * \param pimoType The type of this Thing. Needs to be a subtype - * of pimo:Thing. If empty defaults to pimo:Thing. - * - * Be aware that using the other constructor is always faster in case - * the URI of the Thing is known. - */ - Thing( const QString& uriOrName, const QUrl& pimoType = QUrl() ); - - /** - * \overload - * - * \param manager The resource manager to use. This allows to mix resources from different - * managers and, thus, different models. - * - * \since 4.3 - */ - Thing( const QString& uriOrName, const QUrl& pimoType, ResourceManager* manager ); - - /** - * Copy constructor. - */ - Thing( const Thing& other ); - - /** - * Copy constructor. - * - * \param other the resoruce to construct the Thing from. - */ - Thing( const Resource& other ); - - /** - * Constructor used internally. - */ - Thing( ResourceData* ); - - /** - * Desctructor - */ - ~Thing(); - - /** - * Assignment operator. - */ - Thing& operator=( const Thing& res ); - - /** - * Assignment operator. - */ - Thing& operator=( const Resource& res ); - - /** - * Assignment operator. - */ - Thing& operator=( const QUrl& res ); - - /** - * Get the grounding occurrences for this Thing. - * Grounding resources are physical representations - * of the Thing. - * - * An example is an mp3 file which represents an audio track - * or a website which represents a company or a person. Or the - * addressbook entry for an abstract person thing. - * - * \sa pimo:groundingResource - */ - QList groundingOccurrences() const; - - QList referencingOccurrences() const; - - QList occurrences() const; - - /** - * Add a grounding occurrence for this Thing. - * Grounding resources are physical representations - * of the Thing. - * - * An example is an mp3 file which represents an audio track - * or a website which represents a company or a person. Or the - * addressbook entry for an abstract person thing. - * - * \sa pimo:groundingResource - */ - void addGroundingOccurrence( const Resource &res ); - - /** - * Merges two Things that represent the same real-world - * entity. - * - * \param other The Thing that should be merged into this - * Thing. - * - * All properties of \p other will be merged into this - * Thing and all references to \p other will be replaced - * with references to this Thing. - */ -// void merge( Thing other ); - }; -} - -#endif diff --git a/nepomuk/core/tools.cpp b/nepomuk/core/tools.cpp deleted file mode 100644 index c03e32fe..00000000 --- a/nepomuk/core/tools.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2008 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "tools.h" -#include "resourcemanager.h" - -#include -#include -#include - -#include - -#include -#include -#include -#include - - - -void Nepomuk::setDefaultRepository( const QString& ) -{ - // deprecated - do nothing -} - - -QString Nepomuk::defaultGraph() -{ - return QLatin1String("main"); -} - - -QString Nepomuk::typePredicate() -{ - return Soprano::Vocabulary::RDF::type().toString(); -} - - -Soprano::Node Nepomuk::valueToRDFNode( const Nepomuk::Variant& v ) -{ - return v.toNode(); -} - - -QList Nepomuk::valuesToRDFNodes( const Nepomuk::Variant& v ) -{ - return v.toNodeList(); -} - - -Nepomuk::Variant Nepomuk::RDFLiteralToValue( const Soprano::Node& node ) -{ - return Variant::fromNode( node ); -} - - -QString Nepomuk::rdfNamepace() -{ - return Soprano::Vocabulary::RDF::rdfNamespace().toString(); -} - - -QString Nepomuk::rdfsNamespace() -{ - return Soprano::Vocabulary::RDFS::rdfsNamespace().toString(); -} - - -QString Nepomuk::nrlNamespace() -{ - return Soprano::Vocabulary::NRL::nrlNamespace().toString(); -} - - -QString Nepomuk::naoNamespace() -{ - return Soprano::Vocabulary::NAO::naoNamespace().toString(); -} diff --git a/nepomuk/core/tools.h b/nepomuk/core/tools.h deleted file mode 100644 index f7b4317f..00000000 --- a/nepomuk/core/tools.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2008 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_TOOLS_H_ -#define _NEPOMUK_TOOLS_H_ - -#include -#include - -#include "variant.h" -#include "nepomuk_export.h" - -#include - -#include - -namespace Nepomuk { - /** - * Used internally by Resource. - * Converts a Variant into a literal value to be used in the RDF store. - * - * \deprecated Use Nepomuk::Varaint::toNodeList() - */ - KDE_DEPRECATED NEPOMUK_EXPORT QList valuesToRDFNodes( const Variant& ); - - /** - * Used internally by Resource. - * Converts a non-list Variant into a Soprano::Node. - * - * \deprecated Use Nepomuk::Varaint::toNode() - */ - KDE_DEPRECATED NEPOMUK_EXPORT Soprano::Node valueToRDFNode( const Variant& ); - - /** - * Used internally by Resource. - * Convert a list of resources to a list of Ts where T needs to be a subclass - * of Resource. - * - * \return A list containing all resources in \p l represented as a T. - */ - template QList convertResourceList( const QList& l ) { - QList rl; - for( QList::const_iterator it = l.constBegin(); - it != l.constEnd(); ++it ) - rl.append( T( *it ) ); - return rl; - } - - /** - * Used internally by Resource. - * Convert a list of Ts to a list of Resources where T needs to be a subclass - * of Resource. - * - * \return A list containing all resources in \p l. - */ - template QList convertResourceList( const QList& l ) { - QList rl; - Q_FOREACH( const T& r, l ) - rl.append( Resource( r ) ); - return rl; - } - - /** - * \deprecated Use Variant::fromNode() instead. - */ - KDE_DEPRECATED NEPOMUK_EXPORT Variant RDFLiteralToValue( const Soprano::Node& node ); - - /** - * \deprecated Has no effect anymore. - */ - KDE_DEPRECATED NEPOMUK_EXPORT void setDefaultRepository( const QString& s ); - - /** - * \return The name of the default Nepomuk repository ("main"). - * - * \deprecated Use Nepomuk::ResourceManager::mainModel() - */ - KDE_DEPRECATED NEPOMUK_EXPORT QString defaultGraph(); - - /** - * \deprecated Use Soprano::Vocabulary::RDF::type() - */ - KDE_DEPRECATED NEPOMUK_EXPORT QString typePredicate(); - - /** - * \deprecated Use Soprano::Vocabulary::RDF::rdfNamepace() - */ - KDE_DEPRECATED NEPOMUK_EXPORT QString rdfNamepace(); - - /** - * \deprecated Use Soprano::Vocabulary::RDFS::rdfsNamepace() - */ - KDE_DEPRECATED NEPOMUK_EXPORT QString rdfsNamespace(); - - /** - * \deprecated Use Soprano::Vocabulary::NRL::nrlNamepace() - */ - KDE_DEPRECATED NEPOMUK_EXPORT QString nrlNamespace(); - - /** - * \deprecated Use Soprano::Vocabulary::NAO::naoNamepace() - */ - KDE_DEPRECATED NEPOMUK_EXPORT QString naoNamespace(); -} - -#endif diff --git a/nepomuk/core/variant.cpp b/nepomuk/core/variant.cpp deleted file mode 100644 index 4e64d837..00000000 --- a/nepomuk/core/variant.cpp +++ /dev/null @@ -1,1475 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2009 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "variant.h" -#include "resource.h" -#include "tools.h" - -#include -#include - -#include - -#include - - -namespace { - template QList convertList( const QList& l ) { - QList il; - for( int i = 0; i < l.count(); ++i ) { - il.append( static_cast( l[i] ) ); - } - return il; - } -} - - -class Nepomuk::Variant::Private -{ -public: - QVariant value; -}; - - -Nepomuk::Variant::Variant() - : d( new Private ) -{ -} - - -Nepomuk::Variant::~Variant() -{ - delete d; -} - - -Nepomuk::Variant::Variant( const Variant& other ) - : d( new Private ) -{ - operator=( other ); -} - - -Nepomuk::Variant::Variant( const QVariant& other ) - : d( new Private ) -{ - if ( other.userType() == QVariant::Int || - other.userType() == QVariant::LongLong || - other.userType() == QVariant::UInt || - other.userType() == QVariant::ULongLong || - other.userType() == QVariant::Bool || - other.userType() == QVariant::Double || - other.userType() == QVariant::String || - other.userType() == QVariant::Date || - other.userType() == QVariant::Time || - other.userType() == QVariant::DateTime || - other.userType() == QVariant::Url || - other.userType() == qMetaTypeId() || - other.userType() == qMetaTypeId >() || - other.userType() == qMetaTypeId >() || - other.userType() == qMetaTypeId >() || - other.userType() == qMetaTypeId >() || - other.userType() == qMetaTypeId >() || - other.userType() == qMetaTypeId >() || - other.userType() == QVariant::StringList || - other.userType() == qMetaTypeId >() || - other.userType() == qMetaTypeId >() || - other.userType() == qMetaTypeId >() || - other.userType() == qMetaTypeId >() || - other.userType() == qMetaTypeId >() ) { - d->value = other; - } -} - - -Nepomuk::Variant::Variant( int i ) - : d( new Private ) -{ - d->value.setValue( i ); -} - - -Nepomuk::Variant::Variant( qlonglong i ) - : d( new Private ) -{ - d->value.setValue( i ); -} - - -Nepomuk::Variant::Variant( uint i ) - : d( new Private ) -{ - d->value.setValue( i ); -} - - -Nepomuk::Variant::Variant( qulonglong i ) - : d( new Private ) -{ - d->value.setValue( i ); -} - - -Nepomuk::Variant::Variant( bool b ) - : d( new Private ) -{ - d->value.setValue( b ); -} - - -Nepomuk::Variant::Variant( double v ) - : d( new Private ) -{ - d->value.setValue( v ); -} - - -Nepomuk::Variant::Variant( const char* string ) - : d( new Private ) -{ - d->value.setValue( QString::fromLatin1(string) ); -} - - -Nepomuk::Variant::Variant( const QString& string ) - : d( new Private ) -{ - d->value.setValue( string ); -} - - -Nepomuk::Variant::Variant( const QDate& date ) - : d( new Private ) -{ - d->value.setValue( date ); -} - - -Nepomuk::Variant::Variant( const QTime& time ) - : d( new Private ) -{ - d->value.setValue( time ); -} - - -Nepomuk::Variant::Variant( const QDateTime& datetime ) - : d( new Private ) -{ - d->value.setValue( datetime ); -} - - -Nepomuk::Variant::Variant( const QUrl& url ) - : d( new Private ) -{ - d->value.setValue( url ); -} - - -Nepomuk::Variant::Variant( const Nepomuk::Resource& r ) - : d( new Private ) -{ - d->value.setValue( r ); -} - - -Nepomuk::Variant::Variant( const QList& i ) - : d( new Private ) -{ - d->value.setValue( i ); -} - - -Nepomuk::Variant::Variant( const QList& i ) - : d( new Private ) -{ - d->value.setValue( i ); -} - - -Nepomuk::Variant::Variant( const QList& i ) - : d( new Private ) -{ - d->value.setValue( i ); -} - - -Nepomuk::Variant::Variant( const QList& i ) - : d( new Private ) -{ - d->value.setValue( i ); -} - - -Nepomuk::Variant::Variant( const QList& b ) - : d( new Private ) -{ - d->value.setValue( b ); -} - - -Nepomuk::Variant::Variant( const QList& v ) - : d( new Private ) -{ - d->value.setValue( v ); -} - - -Nepomuk::Variant::Variant( const QStringList& stringlist ) - : d( new Private ) -{ - d->value.setValue( stringlist ); -} - - -Nepomuk::Variant::Variant( const QList& date ) - : d( new Private ) -{ - d->value.setValue( date ); -} - - -Nepomuk::Variant::Variant( const QList& time ) - : d( new Private ) -{ - d->value.setValue( time ); -} - - -Nepomuk::Variant::Variant( const QList& datetime ) - : d( new Private ) -{ - d->value.setValue( datetime ); -} - - -Nepomuk::Variant::Variant( const QList& url ) - : d( new Private ) -{ - d->value.setValue( url ); -} - - - -Nepomuk::Variant::Variant( const QList& r ) - : d( new Private ) -{ - d->value.setValue( r ); -} - - -Nepomuk::Variant::Variant( const QList& vl ) - : d( new Private ) -{ - foreach( const Variant& v, vl ) { - append( v ); - } -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const Variant& v ) -{ - d->value = v.d->value; - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( int i ) -{ - d->value.setValue( i ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( qlonglong i ) -{ - d->value.setValue( i ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( uint i ) -{ - d->value.setValue( i ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( qulonglong i ) -{ - d->value.setValue( i ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( bool b ) -{ - d->value.setValue( b ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( double v ) -{ - d->value.setValue( v ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QString& string ) -{ - d->value.setValue( string ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QDate& date ) -{ - d->value.setValue( date ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QTime& time ) -{ - d->value.setValue( time ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QDateTime& datetime ) -{ - d->value.setValue( datetime ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QUrl& url ) -{ - d->value.setValue( url ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const Resource& r ) -{ - d->value.setValue( r ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& i ) -{ - d->value.setValue( i ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& i ) -{ - d->value.setValue( i ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& i ) -{ - d->value.setValue( i ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& i ) -{ - d->value.setValue( i ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& b ) -{ - d->value.setValue( b ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& v ) -{ - d->value.setValue( v ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QStringList& stringlist ) -{ - d->value.setValue( stringlist ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& date ) -{ - d->value.setValue( date ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& time ) -{ - d->value.setValue( time ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& datetime ) -{ - d->value.setValue( datetime ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& url ) -{ - d->value.setValue( url ); - return *this; -} - - -Nepomuk::Variant& Nepomuk::Variant::operator=( const QList& r ) -{ - d->value.setValue( r ); - return *this; -} - - -void Nepomuk::Variant::append( int i ) -{ - QList l = toIntList(); - l.append( i ); - operator=( l ); -} - - -void Nepomuk::Variant::append( qlonglong i ) -{ - QList l = toInt64List(); - l.append( i ); - operator=( l ); -} - - -void Nepomuk::Variant::append( uint i ) -{ - QList l = toUnsignedIntList(); - l.append( i ); - operator=( l ); -} - - -void Nepomuk::Variant::append( qulonglong i ) -{ - QList l = toUnsignedInt64List(); - l.append( i ); - operator=( l ); -} - - -void Nepomuk::Variant::append( bool b ) -{ - QList l = toBoolList(); - l.append( b ); - operator=( l ); -} - - -void Nepomuk::Variant::append( double d ) -{ - QList l = toDoubleList(); - l.append( d ); - operator=( l ); -} - - -void Nepomuk::Variant::append( const QString& string ) -{ - QStringList l = toStringList(); - l.append( string ); - operator=( l ); -} - - -void Nepomuk::Variant::append( const QDate& date ) -{ - QList l = toDateList(); - l.append( date ); - operator=( l ); -} - - -void Nepomuk::Variant::append( const QTime& time ) -{ - QList l = toTimeList(); - l.append( time ); - operator=( l ); -} - - -void Nepomuk::Variant::append( const QDateTime& datetime ) -{ - QList l = toDateTimeList(); - l.append( datetime ); - operator=( l ); -} - - -void Nepomuk::Variant::append( const QUrl& url ) -{ - QList l = toUrlList(); - l.append( url ); - operator=( l ); -} - - -void Nepomuk::Variant::append( const Resource& r ) -{ - QList l = toResourceList(); - if ( !l.contains( r ) ) { - l.append( r ); - operator=( l ); - } -} - - -void Nepomuk::Variant::append( const Variant& v ) -{ - if ( !isValid() ) { - operator=( v ); - } - else { - if( v.simpleType() == QVariant::Int ) { - operator=( toIntList() += v.toIntList() ); - } - else if( v.simpleType() == QVariant::UInt ) { - operator=( toUnsignedIntList() += v.toUnsignedIntList() ); - } - else if( v.simpleType() == QVariant::LongLong ) { - operator=( toInt64List() += v.toInt64List() ); - } - else if( v.simpleType() == QVariant::ULongLong ) { - operator=( toUnsignedInt64List() += v.toUnsignedInt64List() ); - } - else if( v.simpleType() == QVariant::Bool ) { - operator=( toBoolList() += v.toBoolList() ); - } - else if( v.simpleType() == QVariant::Double ) { - operator=( toDoubleList() += v.toDoubleList() ); - } - else if( v.simpleType() == QVariant::String ) { - operator=( toStringList() += v.toStringList() ); - } - else if( v.simpleType() == QVariant::Date ) { - operator=( toDateList() += v.toDateList() ); - } - else if( v.simpleType() == QVariant::Time ) { - operator=( toTimeList() += v.toTimeList() ); - } - else if( v.simpleType() == QVariant::DateTime ) { - operator=( toDateTimeList() += v.toDateTimeList() ); - } - else if( v.simpleType() == QVariant::Url ) { - operator=( toUrlList() += v.toUrlList() ); - } - else if( v.simpleType() == qMetaTypeId() ) { - operator=( toResourceList() += v.toResourceList() ); - } - else - kDebug() << "(Variant::append) unknown type: " << v.simpleType(); - } -} - - -bool Nepomuk::Variant::isInt() const -{ - return( type() == QVariant::Int ); -} - - -bool Nepomuk::Variant::isInt64() const -{ - return( type() == QVariant::LongLong ); -} - - -bool Nepomuk::Variant::isUnsignedInt() const -{ - return( type() == QVariant::UInt ); -} - - -bool Nepomuk::Variant::isUnsignedInt64() const -{ - return( type() == QVariant::ULongLong ); -} - - -bool Nepomuk::Variant::isBool() const -{ - return( type() == QVariant::Bool ); -} - - -bool Nepomuk::Variant::isDouble() const -{ - return( type() == QVariant::Double ); -} - - -bool Nepomuk::Variant::isString() const -{ - return( type() == QVariant::String ); -} - - -bool Nepomuk::Variant::isDate() const -{ - return( type() == QVariant::Date ); -} - - -bool Nepomuk::Variant::isTime() const -{ - return( type() == QVariant::Time ); -} - - -bool Nepomuk::Variant::isDateTime() const -{ - return( type() == QVariant::DateTime ); -} - - -bool Nepomuk::Variant::isUrl() const -{ - return( type() == QVariant::Url ); -} - - -bool Nepomuk::Variant::isResource() const -{ - return( type() == qMetaTypeId() || - isUrl() ); -} - - -bool Nepomuk::Variant::isIntList() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isUnsignedIntList() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isInt64List() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isUnsignedInt64List() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isBoolList() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isDoubleList() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isStringList() const -{ - return( type() == QVariant::StringList ); -} - - -bool Nepomuk::Variant::isDateList() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isTimeList() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isDateTimeList() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isUrlList() const -{ - return( type() == qMetaTypeId >() ); -} - - -bool Nepomuk::Variant::isResourceList() const -{ - return( type() == qMetaTypeId >() || - isUrlList() ); -} - - - -int Nepomuk::Variant::toInt() const -{ - if(isList()) { - QList l = toIntList(); - if(!l.isEmpty()) - return l.first(); - } - - return d->value.toInt(); -} - - -qlonglong Nepomuk::Variant::toInt64() const -{ - if(isList()) { - QList l = toInt64List(); - if(!l.isEmpty()) - return l.first(); - } - - return d->value.toLongLong(); -} - - -uint Nepomuk::Variant::toUnsignedInt() const -{ - if(isList()) { - QList l = toUnsignedIntList(); - if(!l.isEmpty()) - return l.first(); - } - - return d->value.toUInt(); -} - - -qulonglong Nepomuk::Variant::toUnsignedInt64() const -{ - if(isList()) { - QList l = toUnsignedInt64List(); - if(!l.isEmpty()) - return l.first(); - } - - return d->value.toULongLong(); -} - - -bool Nepomuk::Variant::toBool() const -{ - if(isList()) { - QList l = toBoolList(); - if(!l.isEmpty()) - return l.first(); - } - - return d->value.toBool(); -} - - -double Nepomuk::Variant::toDouble() const -{ - if(isList()) { - QList l = toDoubleList(); - if(!l.isEmpty()) - return l.first(); - } - - return d->value.toDouble(); -} - - -QString Nepomuk::Variant::toString() const -{ -// kDebug() << "(Variant::toString() converting... " << QMetaType::typeName(type()); - if( isList() ) - return toStringList().join( "," ); - - else if( isInt() ) - return QString::number( toInt() ); - else if( isInt64() ) - return QString::number( toInt64() ); - else if( isUnsignedInt() ) - return QString::number( toUnsignedInt() ); - else if( isUnsignedInt64() ) - return QString::number( toUnsignedInt64() ); - else if( isBool() ) - return ( toBool() ? QString("true") : QString("false" ) ); - else if( isDouble() ) - return QString::number( toDouble(), 'e', 10 ); - else if( isDate() ) - return Soprano::LiteralValue( toDate() ).toString(); - else if( isTime() ) - return Soprano::LiteralValue( toTime() ).toString(); - else if( isDateTime() ) - return Soprano::LiteralValue( toDateTime() ).toString(); - else if( isUrl() ) - return KUrl(toUrl()).pathOrUrl(); - else if( isResource() ) - return toResource().genericLabel(); - else - return d->value.toString(); -} - - -QDate Nepomuk::Variant::toDate() const -{ - if(isList()) { - QList l = toDateList(); - if(!l.isEmpty()) - return l.first(); - } - return d->value.toDate(); -} - - -QTime Nepomuk::Variant::toTime() const -{ - if(isList()) { - QList l = toTimeList(); - if(!l.isEmpty()) - return l.first(); - } - return d->value.toTime(); -} - - -QDateTime Nepomuk::Variant::toDateTime() const -{ - if(isList()) { - QList l = toDateTimeList(); - if(!l.isEmpty()) - return l.first(); - } - return d->value.toDateTime(); -} - - -QUrl Nepomuk::Variant::toUrl() const -{ - if(isList()) { - QList l = toUrlList(); - if(!l.isEmpty()) - return l.first(); - } - else if(type() == qMetaTypeId()) { - return toResource().resourceUri(); - } - - return d->value.toUrl(); -} - - -Nepomuk::Resource Nepomuk::Variant::toResource() const -{ - if(isResourceList() || isUrlList()) { - QList l = toResourceList(); - if(!l.isEmpty()) - return l.first(); - } - else if(type() == QVariant::Url) { - return Resource(toUrl()); - } - - return d->value.value(); -} - - - -QList Nepomuk::Variant::toIntList() const -{ - if( isUnsignedInt() || - isInt() || - isUnsignedInt64() || - isInt64() ) { - QList l; - l.append( toInt() ); - return l; - } - else if ( isUnsignedIntList() ) { - return convertList( d->value.value >() ); - } - else if ( isUnsignedInt64List() ) { - return convertList( d->value.value >() ); - } - else if ( isInt64List() ) { - return convertList( d->value.value >() ); - } - else { - return d->value.value >(); - } -} - - -QList Nepomuk::Variant::toInt64List() const -{ - if( isUnsignedInt() || - isInt() || - isUnsignedInt64() || - isInt64() ) { - QList l; - l.append( toInt64() ); - return l; - } - else if ( isIntList() ) { - return convertList( d->value.value >() ); - } - else if ( isUnsignedIntList() ) { - return convertList( d->value.value >() ); - } - else if ( isUnsignedInt64List() ) { - return convertList( d->value.value >() ); - } - else { - return d->value.value >(); - } -} - - -QList Nepomuk::Variant::toUnsignedIntList() const -{ - if( isUnsignedInt() || - isInt() || - isUnsignedInt64() || - isInt64() ) { - QList l; - l.append( toUnsignedInt() ); - return l; - } - else if ( isIntList() ) { - return convertList( d->value.value >() ); - } - else if ( isUnsignedInt64List() ) { - return convertList( d->value.value >() ); - } - else if ( isInt64List() ) { - return convertList( d->value.value >() ); - } - else { - return d->value.value >(); - } -} - - -QList Nepomuk::Variant::toUnsignedInt64List() const -{ - if( isUnsignedInt() || - isInt() || - isUnsignedInt64() || - isInt64() ) { - QList l; - l.append( toUnsignedInt() ); - return l; - } - else if ( isIntList() ) { - return convertList( d->value.value >() ); - } - else if ( isUnsignedIntList() ) { - return convertList( d->value.value >() ); - } - else if ( isInt64List() ) { - return convertList( d->value.value >() ); - } - else { - return d->value.value >(); - } -} - - -QList Nepomuk::Variant::toBoolList() const -{ - if( isBool() ) { - QList l; - l.append( toBool() ); - return l; - } - else - return d->value.value >(); -} - - -QList Nepomuk::Variant::toDoubleList() const -{ - if( isDouble() ) { - QList l; - l.append( toDouble() ); - return l; - } - else - return d->value.value >(); -} - - -template QStringList convertToStringList( const QList& l ) -{ - QStringList sl; - QListIterator it( l ); - while( it.hasNext() ) - sl.append( Nepomuk::Variant( it.next() ).toString() ); -// for( QList::const_iterator it = l.constBegin(); it != l.constEnd(); ++it ) -// sl.append( Nepomuk::Variant( *it ).toString() ); - return sl; -} - -QStringList Nepomuk::Variant::toStringList() const -{ - // kDebug() << "(Variant::toStringList() converting... " << QMetaType::typeName(simpleType()); - if( !d->value.isValid() ) - return QStringList(); - - if( !isList() ) - return QStringList( toString() ); - - else if( isIntList() ) - return convertToStringList( toIntList() ); - else if( isInt64List() ) - return convertToStringList( toInt64List() ); - else if( isUnsignedIntList() ) - return convertToStringList( toUnsignedIntList() ); - else if( isUnsignedInt64List() ) - return convertToStringList( toUnsignedInt64List() ); - else if( isBoolList() ) - return convertToStringList( toBoolList() ); - else if( isDoubleList() ) - return convertToStringList( toDoubleList() ); - else if( isDateList() ) - return convertToStringList( toDateList() ); - else if( isTimeList() ) - return convertToStringList( toTimeList() ); - else if( isDateTimeList() ) - return convertToStringList( toDateTimeList() ); - else if( isUrlList() ) - return convertToStringList( toUrlList() ); - else if( isResourceList() ) - return convertToStringList( toResourceList() ); - else - return d->value.value(); -} - - -QList Nepomuk::Variant::toDateList() const -{ - if( isDate() ) { - QList l; - l.append( toDate() ); - return l; - } - else - return d->value.value >(); -} - - -QList Nepomuk::Variant::toTimeList() const -{ - if( isTime() ) { - QList l; - l.append( toTime() ); - return l; - } - else - return d->value.value >(); -} - - -QList Nepomuk::Variant::toDateTimeList() const -{ - if( isDateTime() ) { - QList l; - l.append( toDateTime() ); - return l; - } - else - return d->value.value >(); -} - - -QList Nepomuk::Variant::toUrlList() const -{ - if( type() == qMetaTypeId() || - type() == QVariant::Url ) { - QList l; - l.append( toUrl() ); - return l; - } - else if( type() == qMetaTypeId >() ) { - QList l; - QList rl = toResourceList(); - foreach(const Resource& r, rl) - l << r.resourceUri(); - return l; - } - else { - return d->value.value >(); - } -} - - -QList Nepomuk::Variant::toResourceList() const -{ - if( type() == qMetaTypeId() || - type() == QVariant::Url ) { - QList l; - l.append( toResource() ); - return l; - } - else if( type() == qMetaTypeId >() ) { - QList urls = toUrlList(); - QList l; - foreach(const QUrl& url, urls) - l << Resource(url); - return l; - } - else { - return d->value.value >(); - } -} - - -QList Nepomuk::Variant::toVariantList() const -{ - QList l; - - switch( simpleType() ) { - case QVariant::Int: - foreach( int i, toIntList() ) { - l.append( Variant(i) ); - } - break; - - case QVariant::LongLong: - foreach( qlonglong i, toInt64List() ) { - l.append( Variant(i) ); - } - break; - - case QVariant::UInt: - foreach( uint i, toUnsignedIntList() ) { - l.append( Variant(i) ); - } - break; - - case QVariant::ULongLong: - foreach( qulonglong i, toUnsignedInt64List() ) { - l.append( Variant(i) ); - } - break; - - case QVariant::Bool: - foreach( bool i, toBoolList() ) { - l.append( Variant(i) ); - } - break; - - case QVariant::Double: - foreach( double i, toDoubleList() ) { - l.append( Variant(i) ); - } - break; - - case QVariant::Date: - foreach( const QDate& i, toDateList() ) { - l.append( Variant(i) ); - } - break; - - case QVariant::Time: - foreach( const QTime& i, toTimeList() ) { - l.append( Variant(i) ); - } - break; - - case QVariant::DateTime: - foreach( const QDateTime& i, toDateTimeList() ) { - l.append( Variant(i) ); - } - break; - - case QVariant::Url: - foreach( const QUrl& i, toUrlList() ) { - l.append( Variant(i) ); - } - break; - - default: - if( simpleType() == qMetaTypeId()) { - foreach( const Resource& i, toResourceList() ) { - l.append( Variant(i) ); - } - } - else { - foreach( const QString& i, toStringList() ) { - l.append( Variant(i) ); - } - break; - } - } - - return l; -} - - -Soprano::Node Nepomuk::Variant::toNode() const -{ - if( !isValid() || isList() ) - return Soprano::Node(); - else if( isResource() ) - return Soprano::Node( toUrl() ); - else - return Soprano::Node( Soprano::LiteralValue( variant() ) ); -} - - -QList Nepomuk::Variant::toNodeList() const -{ - QList nl; - - if ( isResourceList() ) { - QList urls = toUrlList(); - for ( QList::const_iterator it = urls.constBegin(); it != urls.constEnd(); ++it ) { - nl.append( Soprano::Node( *it ) ); - } - } - else if( isList() ) { - QStringList vl = toStringList(); - for( QStringList::const_iterator it = vl.constBegin(); it != vl.constEnd(); ++it ) { - nl.append( Soprano::Node( Soprano::LiteralValue::fromString( *it, ( QVariant::Type )simpleType() ) ) ); - } - } - else if( isValid() ) { - nl.append( toNode() ); - } - - return nl; -} - - -bool Nepomuk::Variant::isList() const -{ - return( isIntList() || - isInt64List() || - isUnsignedIntList() || - isUnsignedInt64List() || - isBoolList() || - isDoubleList() || - isStringList() || - isDateList() || - isTimeList() || - isDateTimeList() || - isUrlList() || - isResourceList() ); -} - - -int Nepomuk::Variant::type() const -{ - return d->value.userType(); -} - - -int Nepomuk::Variant::simpleType() const -{ - if( isIntList() ) - return QVariant::Int; - else if( isInt64List() ) - return QVariant::LongLong; - else if( isUnsignedIntList() ) - return QVariant::UInt; - else if( isUnsignedInt64List() ) - return QVariant::ULongLong; - else if( isBoolList() ) - return QVariant::Bool; - else if( isDoubleList() ) - return QVariant::Double; - else if( isStringList() ) - return QVariant::String; - else if( isDateList() ) - return QVariant::Date; - else if( isTimeList() ) - return QVariant::Time; - else if( isDateTimeList() ) - return QVariant::DateTime; - else if( isUrlList() ) - return QVariant::Url; - else if( isResourceList() ) - return qMetaTypeId(); - else - return d->value.userType(); -} - - -// static -Nepomuk::Variant Nepomuk::Variant::fromString( const QString& value, int type ) -{ - // first check the types that are not supported by Soprano since they are not literal types - if( type == qMetaTypeId() ) { - return Variant( Resource( value ) ); - } - else if ( type == int( QVariant::Url ) ) { - return Variant( QUrl( value ) ); - } - - // let Soprano do the rest - else { - return Variant( Soprano::LiteralValue::fromString( value, ( QVariant::Type )type ).variant() ); - } -} - - -// static -Nepomuk::Variant Nepomuk::Variant::fromNode( const Soprano::Node& node ) -{ - // - // We cannot put in Resource objects here since then nie:url file:/ URLs would - // get converted back to the actual resource URIs which would be useless. - // That is why Variant treats QUrl and Resource pretty much as similar. - // - if ( node.isResource() ) { - return Nepomuk::Variant( node.uri() ); - } - else if ( node.isLiteral() ) { - return Nepomuk::Variant( node.literal().variant() ); - } - else { - return Nepomuk::Variant(); - } -} - - -// static -Nepomuk::Variant Nepomuk::Variant::fromNodeList( const QList& valueNodes ) -{ - if( valueNodes.size() == 1 ) { - return Nepomuk::Variant::fromNode( valueNodes.first() ); - } - else { - if( valueNodes.first().isResource() ) { - QList resList; - Q_FOREACH( const Soprano::Node & n, valueNodes ) { - if( n.isResource() ) - resList << Nepomuk::Resource( n.uri() ); - } - return Nepomuk::Variant( resList ); - } - else if( valueNodes.first().isLiteral() ) { - QList varList; - Q_FOREACH( const Soprano::Node & n, valueNodes ) { - if( n.isLiteral() ) - varList << Nepomuk::Variant( n.literal().variant() ); - } - return Nepomuk::Variant( varList ); - } - return Nepomuk::Variant(); - } -} - - -bool Nepomuk::Variant::operator==( const Variant& other ) const -{ - // we handle the special case of Urls and Resources before - // comparing the simple type - if( isUrl() || isUrlList() ) - return other.toUrlList() == toUrlList(); - else if( isResource() || isResourceList() ) - return other.toResourceList() == toResourceList(); - - if( other.simpleType() != this->simpleType() ) - return false; - - if( isInt() || isIntList() ) - return other.toIntList() == toIntList(); - else if( isInt64() || isInt64List() ) - return other.toInt64List() == toInt64List(); - else if( isUnsignedInt() || isUnsignedIntList() ) - return other.toUnsignedIntList() == toUnsignedIntList(); - else if( isUnsignedInt64() || isUnsignedInt64List() ) - return other.toUnsignedInt64List() == toUnsignedInt64List(); - else if( isBool() || isBoolList() ) - return other.toBoolList() == toBoolList(); - else if( isDouble() || isDoubleList() ) - return other.toDoubleList() == toDoubleList(); - else if( isString() || isStringList() ) - return other.d->value.value() == d->value.value(); - else if( isDate() || isDateList() ) - return other.toDateList() == toDateList(); - else if( isTime() || isTimeList() ) - return other.toTimeList() == toTimeList(); - else if( isDateTime() || isDateTimeList() ) - return other.toDateTimeList() == toDateTimeList(); - else - return ( d->value == other.d->value ); -} - - -bool Nepomuk::Variant::operator!=( const Variant& other ) const -{ - return !operator==( other ); -} - - -QVariant Nepomuk::Variant::variant() const -{ - return d->value; -} - - -bool Nepomuk::Variant::isValid() const -{ - return d->value.isValid(); -} - - -QDebug operator<<( QDebug dbg, const Nepomuk::Variant& v ) -{ - if( v.isList() ) - dbg.nospace() << "Nepomuk::Variant(" << v.toStringList() << "@list)"; - else if( v.isResource() ) - dbg.nospace() << "Nepomuk::Variant(Nepomuk::Resource(" << v.toString() << "))"; - else - dbg.nospace() << "Nepomuk::Variant(" << v.variant() << ")"; - return dbg; -} diff --git a/nepomuk/core/variant.h b/nepomuk/core/variant.h deleted file mode 100644 index 98ee136e..00000000 --- a/nepomuk/core/variant.h +++ /dev/null @@ -1,405 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2009 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_VARIANT_H_ -#define _NEPOMUK_VARIANT_H_ - -#include "nepomuk_export.h" -#include "resource.h" - -#include -#include -#include - -namespace Soprano { - class Node; -} - -namespace Nepomuk { - - class Resource; - - /** - * \class Variant variant.h Nepomuk/Variant - * - * \brief The %Nepomuk Variant extends over QVariant by introducing - * direct support for Resource embedding, automatic list conversion - * and a restricted set of supported types. - * - * Important differences are: - * \li No new types can be added other than the ones that have defined - * constructors and get-methods - * \li Variant supports automatic list generation. For example a Variant - * containing an int also can produce an int-list via the toIntList - * method. - * \li toString and toStringList always return a valid list and do automatic - * conversion from the actual type used in the Variant. Thus, if one only - * needs to display the value in a Variant toString and toStringList - * do the job. - * \li Variant comes with direct support for Resource. There is one special - * thing about QUrl Variants though: for both isUrl() and - * isResource() return \p true. However, toUrl() will return different - * values for Resource and for QUrl Variants: in the former case the - * actual Resource::resourceUri() is returned which can be different - * in case of file:/ URLs. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT Variant - { - public: - Variant(); - ~Variant(); - Variant( const Variant& other ); - - /** - * Will create an invalid Variant if other has an unsupported type. - */ - explicit Variant( const QVariant& other ); - Variant( int i ); - Variant( qlonglong i ); - Variant( uint i ); - Variant( qulonglong i ); - Variant( bool b ); - Variant( double d ); - Variant( const char* string ); - Variant( const QString& string ); - Variant( const QDate& date ); - Variant( const QTime& time ); - Variant( const QDateTime& datetime ); - Variant( const QUrl& url ); - Variant( const Resource& r ); - Variant( const QList& i ); - Variant( const QList& i ); - Variant( const QList& i ); - Variant( const QList& i ); - Variant( const QList& b ); - Variant( const QList& d ); - Variant( const QStringList& stringlist ); - Variant( const QList& date ); - Variant( const QList& time ); - Variant( const QList& datetime ); - Variant( const QList& url ); - Variant( const QList& r ); - - /** - * Create a new Variant from a list of Variants. - * - * \since 4.3 - */ - Variant( const QList& vl ); - - Variant& operator=( const Variant& ); - Variant& operator=( int i ); - Variant& operator=( qlonglong i ); - Variant& operator=( uint i ); - Variant& operator=( qulonglong i ); - Variant& operator=( bool b ); - Variant& operator=( double d ); - Variant& operator=( const QString& string ); - Variant& operator=( const QDate& date ); - Variant& operator=( const QTime& time ); - Variant& operator=( const QDateTime& datetime ); - Variant& operator=( const QUrl& url ); - Variant& operator=( const Resource& r ); - Variant& operator=( const QList& i ); - Variant& operator=( const QList& i ); - Variant& operator=( const QList& i ); - Variant& operator=( const QList& i ); - Variant& operator=( const QList& b ); - Variant& operator=( const QList& d ); - Variant& operator=( const QStringList& stringlist ); - Variant& operator=( const QList& date ); - Variant& operator=( const QList& time ); - Variant& operator=( const QList& datetime ); - Variant& operator=( const QList& url ); - Variant& operator=( const QList& r ); - - /** - * Append \a i to this variant. If the variant already - * contains an int it will be converted to a list of int. - */ - void append( int i ); - void append( qlonglong i ); - void append( uint i ); - void append( qulonglong i ); - void append( bool b ); - void append( double d ); - void append( const QString& string ); - void append( const QDate& date ); - void append( const QTime& time ); - void append( const QDateTime& datetime ); - void append( const QUrl& url ); - void append( const Resource& r ); - - /** - * Appends the value stored in \a v to the list in this - * Variant. If this Variant contains a value with the same - * simple type as \a v they are merged into a list. Otherwise - * this Variant will contain one list of simple type v.simpleType() - */ - void append( const Variant& v ); - - /** - * Does compare two Variant objects. single-valued lists are treated - * as the single value itself. For example a QStringList variant with - * one element "x" equals a QString variant with value "x". - */ - bool operator==( const Variant& other ) const; - - /** - * Inverse of operator== - */ - bool operator!=( const Variant& other ) const; - - bool isValid() const; - - /** - * \return the QT Meta type id of the type - */ - int type() const; - - /** - * \return the type of the simple value, i.e. with - * the list stripped. - */ - int simpleType() const; - - /** - * This methods does not handle all list types. - * It checks the following: - * \li QList - * \li QList - * \li QList - * \li QList - * \li QList - * \li QList - * \li QList - * \li QList - * \li QList (QStringList) - */ - bool isList() const; - - bool isInt() const; - bool isInt64() const; - bool isUnsignedInt() const; - bool isUnsignedInt64() const; - bool isBool() const; - bool isDouble() const; - bool isString() const; - bool isDate() const; - bool isTime() const; - bool isDateTime() const; - bool isUrl() const; - bool isResource() const; - - bool isIntList() const; - bool isInt64List() const; - bool isUnsignedIntList() const; - bool isUnsignedInt64List() const; - bool isBoolList() const; - bool isDoubleList() const; - bool isStringList() const; - bool isDateList() const; - bool isTimeList() const; - bool isDateTimeList() const; - bool isUrlList() const; - bool isResourceList() const; - - QVariant variant() const; - - /** - * Convert into an int value. Returns a valid value for - * all decimal types. - * - * Will return the first value of an int list. - */ - int toInt() const; - - /** - * Convert into a qlonglong value. Returns a valid value for - * all decimal types. - * - * Will return the first value of a qlonglong list. - */ - qlonglong toInt64() const; - - /** - * Convert into a uint value. Returns a valid value for - * all decimal types. - * - * Will return the first value of a uint list. - */ - uint toUnsignedInt() const; - - /** - * Convert into a qulonglong value. Returns a valid value for - * all decimal types. - * - * Will return the first value of a qulonglong list. - */ - qulonglong toUnsignedInt64() const; - - /** - * Convert into a bool value. - * - * Will return the first value of a bool list. - */ - bool toBool() const; - - /** - * Convert into a double value. - * - * Will return the first value of a double list. - */ - double toDouble() const; - - /** - * The toString() method is a little more powerful than other - * toXXX methods since it actually converts all values to string. - * Thus, toString should work always (even list variants are converted - * to a comma-separated list) - * - * Resources are converted to a string representation of their URI. - */ - QString toString() const; - - /** - * Convert into a QDate value. - * - * Will return the first value of a QDate list. - */ - QDate toDate() const; - - /** - * Convert into a QTime value. - * - * Will return the first value of a QTime list. - */ - QTime toTime() const; - - /** - * Convert into a QDateTime value. - * - * Will return the first value of a QDateTime list. - */ - QDateTime toDateTime() const; - - /** - * Convert into a QUrl value. Can handle both QUrl and Resource variants. - * The latter will be converted into its resource URI - * - * Will return the first value of a QUrl list. - * - * \sa Resource::resourceUri - */ - QUrl toUrl() const; - - /** - * Convert into a Resource value. - * - * Will return the first value of a Resource list. Will also convert QUrl - * variants. - */ - Resource toResource() const; - - QList toIntList() const; - QList toInt64List() const; - QList toUnsignedIntList() const; - QList toUnsignedInt64List() const; - QList toBoolList() const; - QList toDoubleList() const; - - /** - * Just like the toString method toStringList is able to convert all - * supported types into a list of strings. - */ - QStringList toStringList() const; - QList toDateList() const; - QList toTimeList() const; - QList toDateTimeList() const; - QList toUrlList() const; - QList toResourceList() const; - - /** - * Convert a Variant to a list of Variants. - * - * \since 4.3 - */ - QList toVariantList() const; - - /** - * Convert a Variant to a Node. - * - * \since 4.6 - */ - Soprano::Node toNode() const; - - /** - * Convert a Variant to a a list of Nodes. - * - * \since 4.6 - */ - QList toNodeList() const; - - /** - * Create a Variant object by parsing string \a value based on \a type. - * If \a type is unknown a simple string Variant object is returned - * containing the plain string \a value. - */ - static Variant fromString( const QString& value, int type ); - - /** - * Create a Variant object from a Soprano::Node. - * - * \since 4.5 - */ - static Variant fromNode( const Soprano::Node& node ); - - /** - * Create a Variant object from a list of Soprano::Node. - * - * \since 4.6 - */ - static Variant fromNodeList( const QList& node ); - - private: - class Private; - Private* const d; - }; -} - - -NEPOMUK_EXPORT QDebug operator<<( QDebug dbg, const Nepomuk::Variant& ); - -Q_DECLARE_METATYPE(Nepomuk::Resource) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(QList) - -#endif diff --git a/nepomuk/nepomuk_export.h b/nepomuk/nepomuk_export.h deleted file mode 100644 index b94f4b41..00000000 --- a/nepomuk/nepomuk_export.h +++ /dev/null @@ -1,39 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 David Faure - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef NEPOMUK_EXPORT_H -#define NEPOMUK_EXPORT_H - -/* needed for KDE_EXPORT and KDE_IMPORT macros */ -#include - -#ifndef NEPOMUK_EXPORT -# if defined(KDELIBS_STATIC_LIBS) - /* No export/import for static libraries */ -# define NEPOMUK_EXPORT -# elif defined(MAKE_NEPOMUK_LIB) - /* We are building this library */ -# define NEPOMUK_EXPORT KDE_EXPORT -# else - /* We are using this library */ -# define NEPOMUK_EXPORT KDE_IMPORT -# endif -#endif - -#endif diff --git a/nepomuk/query/CMakeLists.txt b/nepomuk/query/CMakeLists.txt deleted file mode 100644 index 5591b4a3..00000000 --- a/nepomuk/query/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -project(nepomukquery) - -include_directories( - ${QT_INCLUDES} - ${KDE4_KDECORE_INCLUDES} - ${CMAKE_SOURCE_DIR} - ${SOPRANO_INCLUDE_DIR} - ${NEPOMUK_INCLUDE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/.. - ${CMAKE_CURRENT_SOURCE_DIR}/../core - ${CMAKE_CURRENT_SOURCE_DIR}/../types - ${CMAKE_CURRENT_BINARY_DIR}/.. -) - -add_definitions (${QT_DEFINITIONS} ${KDE4_DEFINITIONS}) -add_definitions(-DDISABLE_NEPOMUK_LEGACY=1) - -set(nepomukquery_SRC - term.cpp - negationterm.cpp - orterm.cpp - andterm.cpp - comparisonterm.cpp - simpleterm.cpp - groupterm.cpp - resourceterm.cpp - literalterm.cpp - resourcetypeterm.cpp - optionalterm.cpp - query.cpp - filequery.cpp - queryparser.cpp - dateparser.cpp - result.cpp - queryserviceclient.cpp - dbusoperators.cpp - ../core/dbusconnectionpool.cpp - queryserializer.cpp - standardqueries.cpp -) - -set_source_files_properties( - org.kde.nepomuk.QueryService.xml - PROPERTIES INCLUDE "dbusoperators_p.h") -set_source_files_properties( - org.kde.nepomuk.Query.xml - PROPERTIES INCLUDE "result.h") - -qt4_add_dbus_interface(nepomukquery_SRC - org.kde.nepomuk.QueryService.xml - queryserviceinterface) -qt4_add_dbus_interface(nepomukquery_SRC - org.kde.nepomuk.Query.xml - queryinterface) - -kde4_add_library(nepomukquery ${LIBRARY_TYPE} ${nepomukquery_SRC}) - -set_target_properties(nepomukquery PROPERTIES VERSION ${GENERIC_LIB_VERSION} SOVERSION ${GENERIC_LIB_SOVERSION}) - -target_link_libraries(nepomukquery - ${QT_QTCORE_LIBRARY} - ${SOPRANO_LIBRARIES} - kdecore - nepomuk - ) - -install(TARGETS nepomukquery EXPORT kdelibsLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS}) -install(FILES - andterm.h - comparisonterm.h - filequery.h - groupterm.h - literalterm.h - negationterm.h - nepomukquery_export.h - optionalterm.h - orterm.h - query.h - queryparser.h - queryserviceclient.h - resourceterm.h - resourcetypeterm.h - result.h - simpleterm.h - standardqueries.h - term.h - DESTINATION ${INCLUDE_INSTALL_DIR}/nepomuk COMPONENT Devel -) diff --git a/nepomuk/query/andterm.cpp b/nepomuk/query/andterm.cpp deleted file mode 100644 index bc384c7c..00000000 --- a/nepomuk/query/andterm.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "andterm.h" -#include "andterm_p.h" -#include "querybuilderdata_p.h" - -#include - -QString Nepomuk::Query::AndTermPrivate::toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString &additionalFilters, QueryBuilderData *qbd ) const -{ - Q_UNUSED(parentTerm); - - QStringList pattern; - - const bool haveRealPattern = hasRealPattern(); - - qbd->pushGroupTerm(this); - foreach( const Nepomuk::Query::Term &t, m_subTerms ) { - pattern += t.d_ptr->toSparqlGraphPattern( resourceVarName, this, haveRealPattern ? QString() : additionalFilters, qbd ); - } - qbd->popGroupTerm(); - - if(haveRealPattern && !additionalFilters.isEmpty()) { - pattern += additionalFilters; - } - - return QLatin1String( "{ " ) + pattern.join(QString()) + QLatin1String( "} . " ); -} - - -bool Nepomuk::Query::AndTermPrivate::hasRealPattern() const -{ - Q_FOREACH( const Nepomuk::Query::Term& term, m_subTerms ) { - if( term.isComparisonTerm() || - term.isResourceTypeTerm() ) { - return true; - } - } - return false; -} - - -Nepomuk::Query::AndTerm::AndTerm() - : GroupTerm( new AndTermPrivate() ) -{ -} - - -Nepomuk::Query::AndTerm::AndTerm( const AndTerm& term ) - : GroupTerm( term ) -{ -} - - -Nepomuk::Query::AndTerm::AndTerm( const Term& term1, - const Term& term2, - const Term& term3, - const Term& term4, - const Term& term5, - const Term& term6 ) - : GroupTerm( new AndTermPrivate(), - term1, - term2, - term3, - term4, - term5, - term6 ) -{ -} - - -Nepomuk::Query::AndTerm::AndTerm( const QList& terms ) - : GroupTerm( new AndTermPrivate() ) -{ - setSubTerms( terms ); -} - - -Nepomuk::Query::AndTerm::~AndTerm() -{ -} - - -Nepomuk::Query::AndTerm& Nepomuk::Query::AndTerm::operator=( const AndTerm& term ) -{ - d_ptr = term.d_ptr; - return *this; -} diff --git a/nepomuk/query/andterm.h b/nepomuk/query/andterm.h deleted file mode 100644 index 8e5a46fa..00000000 --- a/nepomuk/query/andterm.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_AND_TERM_H_ -#define _NEPOMUK_QUERY_AND_TERM_H_ - -#include "groupterm.h" - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class AndTerm andterm.h Nepomuk/Query/AndTerm - * - * \brief Match resource that match all sub terms. - * - * This class - like OrTerm - is derived from GroupTerm which - * handles the sub terms. - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT AndTerm : public GroupTerm - { - public: - /** - * Default constructor: creates an invalid and-term. - */ - AndTerm(); - - /** - * Copy constructor. - */ - AndTerm( const AndTerm& term ); - - /** - * Convinience constructor which allows - * to combine several terms in one line. - */ - AndTerm( const Term& term1, - const Term& term2, - const Term& term3 = Term(), - const Term& term4 = Term(), - const Term& term5 = Term(), - const Term& term6 = Term() ); - - /** - * Combine \p terms into one and-term. - */ - AndTerm( const QList& terms ); - - /** - * Destructor. - */ - ~AndTerm(); - - /** - * Assignment operator. - */ - AndTerm& operator=( const AndTerm& term ); - }; - } -} - -#endif diff --git a/nepomuk/query/andterm_p.h b/nepomuk/query/andterm_p.h deleted file mode 100644 index 849885d7..00000000 --- a/nepomuk/query/andterm_p.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_AND_TERM_P_H_ -#define _NEPOMUK_QUERY_AND_TERM_P_H_ - -#include "groupterm_p.h" - -namespace Nepomuk { - namespace Query { - class AndTermPrivate : public GroupTermPrivate - { - public: - AndTermPrivate() { - m_type = Term::And; - } - - TermPrivate* clone() const { return new AndTermPrivate( *this ); } - - QString toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate*, const QString& additionalFilters, QueryBuilderData* qbd ) const; - - /** - * Since filters can only work on a "real" graph pattern - * we need to make sure that such a pattern exists. This can be done by searching one in a - * surrounding AndTerm. - * - * Why is that enough? - * Nested AndTerms are flattened before the SPARQL query is constructed in Query. Thus, an AndTerm can - * only be embedded in an OrTerm or as a child term to either a ComparisonTerm or an OptionalTerm. - * In both cases we need a real pattern inside the AndTerm. - * - * This method checks if the and term has a "real" non-filter subterm. - * - * This method is used by NegationTerm and ResourceTerm to check if they need to add an artificial "real" - * pattern. - */ - bool hasRealPattern() const; - }; - } -} - -#endif diff --git a/nepomuk/query/comparisonterm.cpp b/nepomuk/query/comparisonterm.cpp deleted file mode 100644 index 7b8a76a6..00000000 --- a/nepomuk/query/comparisonterm.cpp +++ /dev/null @@ -1,555 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "comparisonterm.h" -#include "comparisonterm_p.h" -#include "querybuilderdata_p.h" -#include "literalterm.h" -#include "literalterm_p.h" -#include "resourceterm.h" -#include "resource.h" -#include "query_p.h" - -#include -#include -#include - -#include "literal.h" -#include "class.h" - -#include - - -namespace { - - QString varInAggregateFunction( Nepomuk::Query::ComparisonTerm::AggregateFunction f, const QString& varName ) - { - switch( f ) { - case Nepomuk::Query::ComparisonTerm::Count: - return QString::fromLatin1("count(%1)").arg(varName); - case Nepomuk::Query::ComparisonTerm::DistinctCount: - return QString::fromLatin1("count(distinct %1)").arg(varName); - case Nepomuk::Query::ComparisonTerm::Max: - return QString::fromLatin1("max(%1)").arg(varName); - case Nepomuk::Query::ComparisonTerm::Min: - return QString::fromLatin1("min(%1)").arg(varName); - case Nepomuk::Query::ComparisonTerm::Sum: - return QString::fromLatin1("sum(%1)").arg(varName); - case Nepomuk::Query::ComparisonTerm::DistinctSum: - return QString::fromLatin1("sum(distinct %1)").arg(varName); - case Nepomuk::Query::ComparisonTerm::Average: - return QString::fromLatin1("avg(%1)").arg(varName); - case Nepomuk::Query::ComparisonTerm::DistinctAverage: - return QString::fromLatin1("avg(distinct %1)").arg(varName); - default: - return QString(); - } - } -} - -QString Nepomuk::Query::comparatorToString( Nepomuk::Query::ComparisonTerm::Comparator c ) -{ - switch( c ) { - case Nepomuk::Query::ComparisonTerm::Contains: - return QChar( ':' ); - case Nepomuk::Query::ComparisonTerm::Equal: - return QChar( '=' ); - case Nepomuk::Query::ComparisonTerm::Regexp: - return QLatin1String( "regex" ); - case Nepomuk::Query::ComparisonTerm::Greater: - return QChar( '>' ); - case Nepomuk::Query::ComparisonTerm::Smaller: - return QChar( '<' ); - case Nepomuk::Query::ComparisonTerm::GreaterOrEqual: - return QLatin1String( ">=" ); - case Nepomuk::Query::ComparisonTerm::SmallerOrEqual: - return QLatin1String( "<=" ); - default: - return QString(); - } -} - - -Nepomuk::Query::ComparisonTerm::Comparator Nepomuk::Query::stringToComparator( const QStringRef& c ) -{ - if( c == QChar( '=' ) ) - return Nepomuk::Query::ComparisonTerm::Equal; - else if( c == QLatin1String( "regex" ) ) - return Nepomuk::Query::ComparisonTerm::Regexp; - else if( c == QChar( '>' ) ) - return Nepomuk::Query::ComparisonTerm::Greater; - else if( c == QChar( '<' ) ) - return Nepomuk::Query::ComparisonTerm::Smaller; - else if( c == QLatin1String( ">=" ) ) - return Nepomuk::Query::ComparisonTerm::GreaterOrEqual; - else if( c == QLatin1String( "<=" ) ) - return Nepomuk::Query::ComparisonTerm::SmallerOrEqual; - else - return Nepomuk::Query::ComparisonTerm::Contains; -} - -QString Nepomuk::Query::ComparisonTermPrivate::toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString &additionalFilters, QueryBuilderData *qbd ) const -{ - Q_UNUSED(parentTerm); - - // - // 1. property range: literal - // 1.1. operator = - // use a single pattern like: ?r "value" - // 1.2. operator : - // use two patterns: ?r ?v . ?v bif:contains "'value'" - // 1.3. operator <,>,<=,>= - // use two patterns: ?r ?v . FILTER(?v < value) - // fail if subterm is not a literal term - // - // 2. property range is class - // 2.1. operator = - // 2.1.1. literal subterm - // use two patterns like: ?r ?v . ?v rdfs:label "value" - // 2.1.2. resource subterm - // use one pattern: ?r - // 2.1.3. subterm type and, or, comparision - // use one pattern and the subpattern: ?r ?v . subpattern(?v) - // 2.2. operator : - // 2.2.1. literal subterm - // use 3 pattern: ?r ?v . ?v rdfs:label ?l . ?l bif:contains "'value'" - // 2.2.2. resource subterm - // same as = - // 2.2.3. subterm type and, or, comparision - // same as = - // 2.3. operator <,>,<=,>= - // fail! - // - - if ( !m_subTerm.isValid() ) { - QString finalPattern; - QString prop = propertyToString( qbd ); - bool firstUse = false; - QString ov = getMainVariableName( qbd, &firstUse ); - if( m_inverted ) - finalPattern = QString::fromLatin1( "%1 %2 %3 . " ) - .arg( ov, prop, resourceVarName ); - else if( firstUse ) - finalPattern = QString::fromLatin1( "%1 %2 %3 . " ) - .arg( resourceVarName, prop, ov ); - else - return QString(); - - return finalPattern + additionalFilters; - } - - // when using Regexp comparator with a resource range property we match the resource URI to the regular expression - else if ( m_property.literalRangeType().isValid() || m_comparator == ComparisonTerm::Regexp ) { - QString finalPattern; - - if( !m_subTerm.isLiteralTerm() ) - kDebug() << "Incompatible subterm type:" << m_subTerm.type(); - if ( m_comparator == ComparisonTerm::Equal ) { - finalPattern = QString::fromLatin1( "%1 %2 %3 . " ) - .arg( resourceVarName, - propertyToString( qbd ), - Soprano::Node::literalToN3( m_subTerm.toLiteralTerm().value() ) ); - } - else if ( m_comparator == ComparisonTerm::Contains ) { - bool firstUse = false; - const QString v = getMainVariableName(qbd, &firstUse); - finalPattern = LiteralTermPrivate::createContainsPattern( v, m_subTerm.toLiteralTerm().value().toString(), qbd ); - if(firstUse) { - finalPattern.prepend(QString::fromLatin1( "%1 %2 %3 . " ) - .arg( resourceVarName, - propertyToString( qbd ), - v )); - } - } - else if ( m_comparator == ComparisonTerm::Regexp ) { - bool firstUse = false; - const QString v = getMainVariableName(qbd, &firstUse); - finalPattern = QString::fromLatin1( "FILTER(REGEX(STR(%1), '%2', 'i')) . " ) - .arg( v, m_subTerm.toLiteralTerm().value().toString() ); - if( firstUse ) { - finalPattern.prepend(QString::fromLatin1( "%1 %2 %3 . " ) - .arg( resourceVarName, - propertyToString( qbd ), - v )); - } - } - else { - bool firstUse = false; - const QString v = getMainVariableName(qbd, &firstUse); - finalPattern = QString::fromLatin1( "FILTER(%1%2%3) . " ) - .arg( v, - comparatorToString( m_comparator ), - Soprano::Node::literalToN3(m_subTerm.toLiteralTerm().value()) ); - if( firstUse ) { - finalPattern.prepend( QString::fromLatin1( "%1 %2 %3 . " ) - .arg( resourceVarName, - propertyToString( qbd ), - v ) ); - } - } - - return finalPattern + additionalFilters; - } - - else { // resource range - if( !(m_comparator == ComparisonTerm::Equal || - m_comparator == ComparisonTerm::Contains || - m_comparator == ComparisonTerm::Regexp )) { - kDebug() << "Incompatible property range:" << m_property.range().uri(); - } - - // - // The core pattern is always the same: we match to resources that have a certain - // property defined. The value of that property is filled in below. - // - QString corePattern; - QString subject; - QString object; - if( m_inverted && !m_subTerm.isLiteralTerm() ) { - subject = QLatin1String("%1"); // funny way to have a resulting string which takes only one arg - object = resourceVarName; - } - else { - subject = resourceVarName; - object = QLatin1String("%1"); - } - if( qbd->flags() & Query::HandleInverseProperties && - m_property.inverseProperty().isValid() ) { - corePattern = QString::fromLatin1("{ %1 %2 %3 . %5} UNION { %3 %4 %1 . %5} . ") - .arg( subject, - propertyToString( qbd ), - object, - Soprano::Node::resourceToN3( m_property.inverseProperty().uri() ), - additionalFilters ); - } - else { - corePattern = QString::fromLatin1("%1 %2 %3 . %4") - .arg( subject, - propertyToString( qbd ), - object, - additionalFilters ); - } - - if ( m_subTerm.isLiteralTerm() ) { - // - // the base of the pattern is always the same: match to resources related to X - // which has a label that we compare somehow. This label's value will be filled below - // - bool firstUse = true; - QString v1 = getMainVariableName(qbd, &firstUse); - QString pattern = QString::fromLatin1( "%1%2 %4 %3 . " ) - .arg( firstUse ? corePattern.arg(v1) : QString(), - v1, - QLatin1String("%1"), // funny way to have a resulting string which takes only one arg - Soprano::Node::resourceToN3( Soprano::Vocabulary::RDFS::label() ) ); - - if ( m_comparator == ComparisonTerm::Equal ) { - return pattern.arg( Soprano::Node::literalToN3( m_subTerm.toLiteralTerm().value() ) ); - } - else if ( m_comparator == ComparisonTerm::Contains ) { - QString v3 = qbd->uniqueVarName(); - // since this is not a "real" full text search but rather a match on resource "names" we do not call QueryBuilderData::addFullTextSearchTerm - return pattern.arg(v3) - + LiteralTermPrivate::createContainsPattern( v3, - m_subTerm.toLiteralTerm().value().toString(), - qbd ); - } - else if ( m_comparator == ComparisonTerm::Regexp ) { - QString v3 = qbd->uniqueVarName(); - return QString::fromLatin1( "%1FILTER(REGEX(STR(%2)), '%3', 'i') . " ) - .arg( pattern.arg(v3), - v3, - m_subTerm.toLiteralTerm().value().toString() ); - } - else { - kDebug() << QString( "Invalid Term: comparator %1 cannot be used for matching to a resource!" ).arg( comparatorToString( m_comparator ) ); - return QString(); - } - } - else if ( m_subTerm.isResourceTerm() ) { - // ?r - return corePattern.arg( Soprano::Node::resourceToN3(m_subTerm.toResourceTerm().resource().resourceUri()) ); - } - else { - // ?r ?v1 . ?v1 ... - bool firstUse = true; - QString v = getMainVariableName(qbd, &firstUse); - qbd->increaseDepth(); - QString subTermSparql = m_subTerm.d_ptr->toSparqlGraphPattern( v, this, QString(), qbd ); - qbd->decreaseDepth(); - if( firstUse ) - return corePattern.arg(v) + subTermSparql; - else - return subTermSparql; - } - } -} - - - -bool Nepomuk::Query::ComparisonTermPrivate::equals( const TermPrivate* other ) const -{ - if ( other->m_type == m_type ) { - const ComparisonTermPrivate* ctp = static_cast( other ); - return( ctp->m_property == m_property && - ctp->m_comparator == m_comparator && - ctp->m_subTerm == m_subTerm && - ctp->m_inverted == m_inverted && - ctp->m_sortOrder == m_sortOrder && - ctp->m_sortWeight == m_sortWeight && - ctp->m_variableName == m_variableName ); - } - else { - return false; - } -} - - -bool Nepomuk::Query::ComparisonTermPrivate::isValid() const -{ - // an invalid property will simply match all properties - // and an invalid subterm is a wildcard, too - // Thus, a ComparisonTerm is always valid - return true; -} - - -// -// Determines the main variable name, i.e. the variable representing the compared value, i.e. the one -// that can be set vie setVariableName. -// -// Thus, the basic scheme is: if a variable name has been set via setVariableName, return that name, -// otherwise create a random new one. -// -// But this method also handles AggregateFunction and sorting. The latter is a bit hacky. -// -// There a quite a few cases that are handled: -// -// 1. No variable name set -// 1.1 no aggregate function set -// 1.1.1 no sorting weight set -// -> return a new random variable -// 1.1.2 sorting weight set -// -> determine a new random variable, use it as sorting var (via QueryBuilderData::addOrderVariable), -// and return it -// 1.2 an aggregate function has been set -// 1.2.1 sorting weight set (no sorting weight is useless and behaves exactly as if no aggregate function was set) -// -> embed a new random variable in the aggregate expression, add that as sort variable, and -// return the new variable -// 2. A variable name has been set -// 2.1 no aggregate function set -// 2.1.1 no sorting weight set -// -> add the variable name as custom variable via QueryBuilderData::addCustomVariable and return the variable name -// 2.1.2 sorting weight set -// -> add the variable name as sort car via QueryBuilderData::addOrderVariable and return it -// 2.2 an aggregate function has been set -// 2.2.1 no sorting weight set -// -> Create a new random variable, embed it in the aggregate expression with the set variable name, -// use that expression as custom variable (this is the hacky part), and return the random one -// 2.2.2 sorting weight set -// -> Do the same as above only also add the set variable name as sort variable via QueryBuilderData::addOrderVariable -// -QString Nepomuk::Query::ComparisonTermPrivate::getMainVariableName( QueryBuilderData* qbd, bool* firstUse ) const -{ - QString v; - QString sortVar; - if( !m_variableName.isEmpty() ) { - qbd->registerVarName( m_property, QLatin1String("?") + m_variableName ); - *firstUse = true; - - sortVar = QLatin1String("?") + m_variableName; - if( m_aggregateFunction == ComparisonTerm::NoAggregateFunction ) { - v = sortVar; - qbd->addCustomVariable( v ); - } - else { - // this is a bit hacky as far as the method naming in QueryBuilderData is concerned. - // we add a select statement as a variable name. - v = qbd->uniqueVarName(); - QString selectVar = QString::fromLatin1( "%1 as ?%2") - .arg(varInAggregateFunction(m_aggregateFunction, v), - m_variableName ); - qbd->addCustomVariable( selectVar ); - } - } - else { - // - // for inverted terms we do not perform variable sharing as described in QueryBuilderData::uniqueVarName - // since we would have to check inverse properties and their cardinality and the former is rarely defined. - // - v = qbd->uniqueVarName( m_inverted ? Types::Property() : m_property, firstUse ); - if( m_aggregateFunction == ComparisonTerm::NoAggregateFunction ) - sortVar = v; - else - sortVar = varInAggregateFunction(m_aggregateFunction, v); - } - if( m_sortWeight != 0 ) { - qbd->addOrderVariable( sortVar, m_sortWeight, m_sortOrder ); - - // trueg: there seems to be a bug in Virtuoso which gives wrong search order if the sort variable is not in the select list. - if( m_aggregateFunction == ComparisonTerm::NoAggregateFunction ) - qbd->addCustomVariable( sortVar ); - } - return v; -} - - -QString Nepomuk::Query::ComparisonTermPrivate::propertyToString( QueryBuilderData* qbd ) const -{ - if( m_property.isValid() ) - return Soprano::Node::resourceToN3( m_property.uri() ); - else - return qbd->uniqueVarName(); -} - - -Nepomuk::Query::ComparisonTerm::ComparisonTerm() - : SimpleTerm( new ComparisonTermPrivate() ) -{ -} - - -Nepomuk::Query::ComparisonTerm::ComparisonTerm( const ComparisonTerm& term ) - : SimpleTerm( term ) -{ -} - - -Nepomuk::Query::ComparisonTerm::ComparisonTerm( const Types::Property& property, const Term& term, Comparator comparator ) - : SimpleTerm( new ComparisonTermPrivate() ) -{ - N_D( ComparisonTerm ); - d->m_property = property; - d->m_subTerm = term; - d->m_comparator = comparator; -} - - -Nepomuk::Query::ComparisonTerm::~ComparisonTerm() -{ -} - - -Nepomuk::Query::ComparisonTerm& Nepomuk::Query::ComparisonTerm::operator=( const ComparisonTerm& term ) -{ - d_ptr = term.d_ptr; - return *this; -} - - -Nepomuk::Query::ComparisonTerm::Comparator Nepomuk::Query::ComparisonTerm::comparator() const -{ - N_D_CONST( ComparisonTerm ); - return d->m_comparator; -} - - -Nepomuk::Types::Property Nepomuk::Query::ComparisonTerm::property() const -{ - N_D_CONST( ComparisonTerm ); - return d->m_property; -} - - -void Nepomuk::Query::ComparisonTerm::setComparator( Comparator comparator ) -{ - N_D( ComparisonTerm ); - d->m_comparator = comparator; -} - - -void Nepomuk::Query::ComparisonTerm::setProperty( const Types::Property& property ) -{ - N_D( ComparisonTerm ); - d->m_property = property; -} - - -void Nepomuk::Query::ComparisonTerm::setVariableName( const QString& name ) -{ - N_D( ComparisonTerm ); - d->m_variableName = name; -} - - -QString Nepomuk::Query::ComparisonTerm::variableName() const -{ - N_D_CONST( ComparisonTerm ); - return d->m_variableName; -} - - -void Nepomuk::Query::ComparisonTerm::setAggregateFunction( AggregateFunction function ) -{ - N_D( ComparisonTerm ); - d->m_aggregateFunction = function; -} - - -Nepomuk::Query::ComparisonTerm::AggregateFunction Nepomuk::Query::ComparisonTerm::aggregateFunction() const -{ - N_D_CONST( ComparisonTerm ); - return d->m_aggregateFunction; -} - - -void Nepomuk::Query::ComparisonTerm::setSortWeight( int weight, Qt::SortOrder sortOrder ) -{ - N_D( ComparisonTerm ); - d->m_sortWeight = weight; - d->m_sortOrder = sortOrder; -} - - -int Nepomuk::Query::ComparisonTerm::sortWeight() const -{ - N_D_CONST( ComparisonTerm ); - return d->m_sortWeight; -} - - -Qt::SortOrder Nepomuk::Query::ComparisonTerm::sortOrder() const -{ - N_D_CONST( ComparisonTerm ); - return d->m_sortOrder; -} - - -bool Nepomuk::Query::ComparisonTerm::isInverted() const -{ - N_D_CONST( ComparisonTerm ); - return d->m_inverted; -} - - -void Nepomuk::Query::ComparisonTerm::setInverted( bool invert ) -{ - N_D( ComparisonTerm ); - d->m_inverted = invert; -} - - -Nepomuk::Query::ComparisonTerm Nepomuk::Query::ComparisonTerm::inverted() const -{ - ComparisonTerm ct( *this ); - ct.setInverted( !isInverted() ); - return ct; -} diff --git a/nepomuk/query/comparisonterm.h b/nepomuk/query/comparisonterm.h deleted file mode 100644 index 0a5d934f..00000000 --- a/nepomuk/query/comparisonterm.h +++ /dev/null @@ -1,419 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_COMPARISON_TERM_H_ -#define _NEPOMUK_QUERY_COMPARISON_TERM_H_ - -#include "simpleterm.h" - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Types { - class Property; - } - - namespace Query { - /** - * \class ComparisonTerm comparisonterm.h Nepomuk/Query/ComparisonTerm - * - * \brief A term matching the value of a property. - * - * The %ComparisonTerm is the most important term in the query API. It can be - * used to match the values of properties. As such its core components are - * a property(), a comparator() (see Comparator for details) and a subTerm(). - * The latter can be any other term including AndTerm, OrTerm, or even an invalid - * term. The matching is done as follows: - * - * \li A LiteralTerm as subTerm() is directly matched to the value of a literal - * property (see also Nepomuk::Types::Property::literalRangeType()) or to the - * labels of related resources in case of a property that has a resource range. - * \li An invalid sub term simply matches any resource or value, effectively - * acting as a wildcard. - * \li Any other term type will be used as a sort of subquery to match the - * related resources. This means that the property() needs to have a resource - * range. - * - * In addition to these basic features %ComparisonTerm has a few tricks up its - * sleeve: - * - * \li By forcing the variable name via setVariableName() it is possible to - * include a value matched by the term in the resulting SPARQL query (Query::toSparqlQuery()) - * or accessing it via Result::additionalBinding(). - * \li It is possible to set an aggregate function via setAggregateFunction() - * to count or sum up the results instead of returning the actual values. - * \li Using setSortWeight() the sorting of the results in the final query - * can be influenced in a powerful way - especially when combined with setAggregateFunction(). - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT ComparisonTerm : public SimpleTerm - { - public: - /** - * %ComparisonTerm supports different ways to compare values. - */ - enum Comparator { - /** - * A LiteralTerm sub-term is matched against string literal values. - * Case is ignored. The literal value can contain wildcards like *. - */ - Contains, - - /** - * A LiteralTerm sub-term is matched against a string literal value - * using the literal term's value as a regular expression. - * It is highly recommended to prefer Contains over Regexp - * as the latter will result in much slower SPARQL REGEX filters. - */ - Regexp, - - /** - * A sub-term is matched one-to-one. Sub-terms can be any other term type. - */ - Equal, - - /** - * A LiteralTerm sub-term is matched to greater literal values. - */ - Greater, - - /** - * A LiteralTerm sub-term is matched to smaller literal values. - */ - Smaller, - - /** - * A LiteralTerm sub-term is matched to greater or equal literal values. - */ - GreaterOrEqual, - - /** - * A LiteralTerm sub-term is matched to smaller or equal literal values. - */ - SmallerOrEqual - }; - - /** - * Aggregate functions which can be applied to a comparison term to influence - * the value they return. - * - * \sa setAggregateFunction() - * - * \since 4.5 - */ - enum AggregateFunction { - /** - * Do not use any aggregate function. - */ - NoAggregateFunction = 0, - - /** - * Count the number of matching results instead - * of returning the results themselves. - * For counting the results of a complete query use - * Query::CreateCountQuery. - */ - Count, - - /** - * The same as Count except that no two similar results - * are counted twice. - */ - DistinctCount, - - /** - * Return the maximum value of all results instead - * of the results themselves. - * Does only make sense for numerical values. - */ - Max, - - /** - * Return the minimum value of all results instead - * of the results themselves. - * Does only make sense for numerical values. - */ - Min, - - /** - * Return the sum of all result values instead - * of the results themselves. - * Does only make sense for numerical values. - */ - Sum, - - /** - * The same as Sum except that no two similar results - * are added twice. - */ - DistinctSum, - - /** - * Return the average value of all results instead - * of the results themselves. - * Does only make sense for numerical values. - */ - Average, - - /** - * The same as Average except that no two similar results - * are counted twice. - */ - DistinctAverage - }; - - /** - * Default constructor: creates a comparison term that matches all properties. - */ - ComparisonTerm(); - - /** - * Copy constructor. - */ - ComparisonTerm( const ComparisonTerm& term ); - - /** - * Convinience constructor which covers most simple use cases. - * - * \param property The property that should be matched. An invalid property will act as a wildcard. - * \param term The sub term to match to. - * \param comparator The Comparator to use for comparison. Not all Comparators make sense - * with all sub term types. - */ - ComparisonTerm( const Types::Property& property, const Term& term, Comparator comparator = Contains ); - - /** - * Destructor. - */ - ~ComparisonTerm(); - - /** - * Assignment operator. - */ - ComparisonTerm& operator=( const ComparisonTerm& term ); - - /** - * The Comparator used by ComparisonTerm Terms. - * - * \sa setComparator - */ - Comparator comparator() const; - - /** - * A property used for ComparisonTerm Terms. - * An invalid property will act as a wildcard. - * - * \sa setProperty - */ - Types::Property property() const; - - /** - * Set the comparator - */ - void setComparator( Comparator ); - - /** - * Set the property for ComparisonTerm - * Terms. An invalid property will act as a wildcard. - * - * \sa property - */ - void setProperty( const Types::Property& ); - - /** - * Set the variable name that is to be used for the - * variable to match to. The variable will then be added - * to the set of variables returned in the results and can - * be read via Result::additionalBinding(). Setting - * the variable name can be seen as a less restricted variant - * of Query::addRequestProperty(). - * - * When manually setting the variable name on more - * than one ComparisonTerm there is no guarantee for the - * uniqueness of variable names anymore which can result - * in unwanted query results. However, this can also be - * used deliberately in case one needs to compare the - * same variable twice: - * - * \code - * ComparisonTerm ct1( prop1, Term() ); - * ComparisonTerm ct1( prop2, Term() ); - * ct1.setVariableName( "myvar" ); - * ct2.setVariableName( "myvar" ); - * \endcode - * - * The above example would result in a SPARQL query - * pattern along the lines of - * - * \code - * ?r ?myVar . - * ?r ?myVar . - * \endcode - * - * Be aware that the variable name does not apply - * to sub terms of types ResourceTerm or LiteralTerm. - * In those cases the value will be ignored. The only exception - * are LiteralTerm sub terms that are compared other than - * with equals. - * - * \param name The name of the variable to be used when requesting - * the binding via Result::additionalBinding() - * - * \sa Result::additionalBinding(), Query::HandleInverseProperties, \ref examples_query - * - * \since 4.5 - */ - void setVariableName( const QString& name ); - - /** - * The variable name set in setVariableName() or an empty - * string if none has been set. - * - * \sa setVariableName() - * - * \since 4.5 - */ - QString variableName() const; - - /** - * Set an aggregate function which changes the - * result. The typical usage is to count the results instead of actually - * returning them. For counting the results of a complete query use - * Query::CreateCountQuery. - * - * \sa aggregateFunction() - * - * \since 4.5 - */ - void setAggregateFunction( AggregateFunction function ); - - /** - * The aggregate function to be used with the additional binding set in - * setVariableName(). - * - * \sa setAggregateFunction() - * - * \since 4.5 - */ - AggregateFunction aggregateFunction() const; - - /** - * Set the sort weight of this property. By default all ComparisonTerms have - * a weight of 0 which means that they are ignored for sorting. By setting \p - * weight to a value different from 0 (typically higher than 0) the comparison - * subterm will be used for sorting. - * - * Be aware that as with the variableName() sorting does not apply to sub - * terms of types ResourceTerm or LiteralTerm. - * In those cases the value will be ignored. The only exception - * are LiteralTerm sub terms that are compared other than - * with equals. - * - * \param weight The new sort weight. If different from 0 this term will be - * used for sorting in the Query. - * \param sortOrder The sort order to use for this term. - * - * \sa sortWeight() - * - * \since 4.5 - */ - void setSortWeight( int weight, Qt::SortOrder sortOrder = Qt::AscendingOrder ); - - /** - * \return The sort weight as set in setSortWeight() or 0 if - * sorting is disabled for this term. - * - * \since 4.5 - */ - int sortWeight() const; - - /** - * \return The sort order as set in setSortWeight(). - * - * \since 4.5 - */ - Qt::SortOrder sortOrder() const; - - /** - * \return \p true if the comparison is inverted. - * \sa setInverted - * - * \since 4.5 - */ - bool isInverted() const; - - /** - * Invert the comparison, i.e. make the subterm the subject - * of the term and match to objects of the term. - * - * A typical example would be: - * - * \code - * ComparisonTerm term( Soprano::Vocabulary::NAO::hasTag(), - * ResourceTerm( somefile ) ); - * term.setInverted(true); - * \endcode - * - * which would yield a query like the following: - * - * \code - * select ?r where { nao:hasTag ?r . } - * \endcode - * - * to get all tags attached to a file. - * - * Be aware that this does only make sense with - * sub terms that match to resources. When using - * LiteralTerm as a sub term \p invert is ignored. - * - * \sa inverted() - * - * \since 4.5 - */ - void setInverted( bool invert ); - - /** - * Create an inverted copy of this %ComparisonTerm. - * This is a convenience method to allow inline creation of - * inverted comparison terms when creating queries in a - * single line of code. - * - * Be aware that calling this method twice wil result in - * a non-inverted comparison term: - * - * \code - * // always true: - * (term.inverted().inverted() == term); - * \endcode - * - * \sa setInverted() - * - * \since 4.5 - */ - ComparisonTerm inverted() const; - }; - } -} - -#endif diff --git a/nepomuk/query/comparisonterm_p.h b/nepomuk/query/comparisonterm_p.h deleted file mode 100644 index 33216f69..00000000 --- a/nepomuk/query/comparisonterm_p.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_COMPARISON_TERM_P_H_ -#define _NEPOMUK_QUERY_COMPARISON_TERM_P_H_ - -#include "simpleterm_p.h" -#include "comparisonterm.h" - -#include "property.h" - -namespace Nepomuk { - namespace Query { - - class QueryBuilderData; - - class ComparisonTermPrivate : public SimpleTermPrivate - { - public: - ComparisonTermPrivate() - : m_aggregateFunction(ComparisonTerm::NoAggregateFunction), - m_sortWeight(0), - m_sortOrder(Qt::AscendingOrder), - m_inverted(false) { - m_type = Term::Comparison; - } - - TermPrivate* clone() const { return new ComparisonTermPrivate( *this ); } - - bool equals( const TermPrivate* other ) const; - bool isValid() const; - QString toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString& additionalFilters, QueryBuilderData* qbd ) const; - - /** - * return m_variableName and register it with qbd - * or ask the latter to create a new variable. - */ - QString getMainVariableName( QueryBuilderData* qbd, bool* firstUse ) const; - - /** - * return the N3 form of m_property or a new variable - * in case m_property is invalid. - */ - QString propertyToString( QueryBuilderData* qbd ) const; - - Types::Property m_property; - ComparisonTerm::Comparator m_comparator; - - QString m_variableName; - ComparisonTerm::AggregateFunction m_aggregateFunction; - int m_sortWeight; - Qt::SortOrder m_sortOrder; - bool m_inverted; - }; - - QString comparatorToString( Nepomuk::Query::ComparisonTerm::Comparator c ); - Nepomuk::Query::ComparisonTerm::Comparator stringToComparator( const QStringRef& c ); - } -} - -#endif diff --git a/nepomuk/query/dateparser.cpp b/nepomuk/query/dateparser.cpp deleted file mode 100644 index 9bd2e1a7..00000000 --- a/nepomuk/query/dateparser.cpp +++ /dev/null @@ -1,357 +0,0 @@ -/* -* This file is part of the Nepomuk KDE project. -* Copyright (c) 2009 Adam Kidder -* Copyright (c) 2009 Sebastian Trueg -* -* This library is free software; you can redistribute it and/or -* modify it under the terms of the GNU Library General Public -* License as published by the Free Software Foundation; either -* version 2 of the License, or (at your option) any later version. -* -* This library 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 -* Library General Public License for more details. -* -* You should have received a copy of the GNU Library General Public License -* along with this library; see the file COPYING.LIB. If not, write to -* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -* Boston, MA 02110-1301, USA. -*/ - -#include "dateparser_p.h" - -#include - -#include -#include -#include -#include - - -namespace { - //represents a time difference from the current time, to represent relative dates - struct time_difference - { - time_difference() : seconds(0), minutes(0), hours(0), days(0), weeks(0), months(0), years(0) {} - int seconds, minutes, hours, days, weeks, months, years; - }; - - struct format - { - format() : pos(0) {} - format(const QRegExp& r, const QStringList& f) : regex(r), pos(0), useRelativeDate(false), formats(f) {} - format(const QRegExp& r, const time_difference& d, bool dr = false) : regex(r), pos(0), useRelativeDate(true), difference(d), dynamicRelative(dr) {} - QRegExp regex; - int pos; - - bool useRelativeDate; - time_difference difference; - bool dynamicRelative; - QStringList formats; - }; - - struct date_string - { - QDate date; - unsigned int pos; - unsigned int length; - }; -} - -class Nepomuk::Search::DateParser::Private -{ -public: - Private(const QString& text, unsigned int flags) : - m_text(text), m_locale(QLocale::English), m_flags(flags) { - //TODO: we are english-only here! - QStringList longMonthNames; - QStringList shortMonthNames; - for ( int i = 1; i <= 12; ++i ) { - longMonthNames << m_locale.monthName( i, QLocale::LongFormat ); - shortMonthNames << m_locale.monthName( i, QLocale::ShortFormat ); - } - - // DD.MM.YYYY - format date1( QRegExp( "\\b\\d{1,2}\\.\\d{1,2}\\.\\d{4,4}\\b" ), QStringList("d.M.yyyy") ); - - // DD.MM.YY - format date2( QRegExp( "\\b\\d{1,2}\\.\\d{1,2}\\.\\d{2,2}\\b" ), QStringList("d.M.yy") ); - - // MM/DD/YYYY - format date3( QRegExp( "\\b\\d{1,2}/\\d{1,2}/\\d{4,4}\\b" ), QStringList("M/d/yyyy") ); - - // YYYY-MM-DD - format date13(QRegExp( "\\b\\d{4,4}-\\d{1,2}-\\d{1,2}\\b" ), QStringList("yyyy-M-d") ); - - // MM/DD/YY - format date4( QRegExp( "\\b\\d{1,2}/\\d{1,2}/\\d{2,2}\\b" ), QStringList("M/d/yy") ); - - // January MM [YYYY] (no word boundry at the end for 'st' or 'nd' or 'th') (also excluding ranges) - format date5( QRegExp( QString( "\\b(%1)\\s\\d{1,2}(?!(\\d|\\s?-\\s?\\d))(\\s\\d{4,4})?" ).arg( longMonthNames.join( "|" ) ) ), - QStringList("MMMM d") << QString("MMMM d yyyy") ); - - // January, MM [YYYY] (no word boundry at the end for 'st' or 'nd' or 'th') (also excluding ranges) - format date6( QRegExp( QString( "\\b(%1),\\s?\\d{1,2}(?!(\\d|\\s?-\\s?\\d))(\\s\\d{4,4})?" ).arg( longMonthNames.join( "|" ) ) ), - QStringList("MMMM, d") << QString("MMMM,d") << QString("MMMM, d yyyy") << QString("MMMM,d yyyy") ); - - // FIXME: trueg: IMHO something like "yesterday" should result in a range if not used with < or >. - - //TODO: english only again! - time_difference days; - days.days = -1; - format date7( QRegExp( QString( "\\b(yesterday)\\b" ) ), days ); - - format date8( QRegExp( QString( "\\b(\\d{1,3}) (day)s? ago\\b" ) ), days, true ); - - time_difference weeks; - weeks.weeks = -1; - format date9( QRegExp( QString( "\\ba week ago\\b" ) ), weeks ); - - format date10( QRegExp( QString( "\\b(\\d{1,3}) (week)s? ago\\b" ) ), weeks, true ); - - time_difference months; - months.months = -1; - format date11( QRegExp( QString( "\\ba month ago\\b" ) ), months ); - - format date12( QRegExp( QString( "\\b(\\d{1,3}) (month)s? ago\\b" ) ), months, true ); - - m_regexes.reserve( 13 ); - m_regexes.push_back( date1 ); - m_regexes.push_back( date2 ); - m_regexes.push_back( date3 ); - m_regexes.push_back( date4 ); - m_regexes.push_back( date5 ); - m_regexes.push_back( date6 ); - m_regexes.push_back( date7 ); - m_regexes.push_back( date8 ); - m_regexes.push_back( date9 ); - m_regexes.push_back( date10); - m_regexes.push_back( date11); - m_regexes.push_back( date12); - m_regexes.push_back( date13); - } - - - bool hasDate() { - if(!m_dates.empty()) return true; - - while(m_dates.empty() && !finishedParsing()) - { - parseAllRegexes(); - } - - if(!m_dates.empty()) return true; - return false; - } - - - QDate getDate() { - if( !m_dates.isEmpty() ) - return m_dates.first().date; - else - return QDate(); - } - - void next() { - m_dates.pop_front(); - } - - unsigned int length() const { - if( !m_dates.isEmpty() ) - return m_dates.first().length; - else - return 0; - } - - unsigned int pos() const { - if( !m_dates.isEmpty() ) - return m_dates.first().pos; - else - return 0; - } - int dateObject; - -private: - bool finishedParsing() { - foreach(format r, m_regexes) { - if(r.pos != -1) return false; - } - return true; - } - - - void parseAllRegexes() { - QVector::iterator it ; - for(it = m_regexes.begin(); it != m_regexes.end(); ++it) { - it->pos = it->regex.indexIn(m_text, it->pos); - if( it->pos == -1 ) - continue; - if( !it->useRelativeDate && (m_flags & AbsoluteDates) ) { - foreach(QString format, it->formats) { - QDate date = m_locale.toDate( it->regex.cap( 0 ), format ); - if(date.isValid()) { - if(!format.contains( "yy" ) ) - date.setDate( QDate::currentDate().year(), date.month(), date.day() ); - kDebug() << "Found absolute date:" << date; - date_string dateObject; - dateObject.date = date; - dateObject.pos = it->pos; - dateObject.length = it->regex.matchedLength(); - m_dates.append( dateObject ); - break; - } - } - } - else if( m_flags & RelativeDates) { - int amount = 1; - if( it->dynamicRelative ) { - amount = it->regex.cap( 1 ).toInt(); - kDebug() << "dynamic relative date, amount is" << amount << it->regex.cap( 1 ); - } - QDate current( QDate::currentDate() ); - current = current.addDays( it->difference.days * amount ); - current = current.addDays( it->difference.weeks * 7 * amount ); - current = current.addMonths( it->difference.months * amount ); - current = current.addYears( it->difference.years * amount ); - - kDebug() << "Found relative date:" << current << it->regex.pattern(); - date_string dateObject; - dateObject.date = current; - dateObject.pos = it->pos; - dateObject.length = it->regex.matchedLength(); - m_dates.append( dateObject ); - } - } - } - - - const QString& m_text; - QLocale m_locale; - QVector m_regexes; - QList m_dates; - unsigned int m_flags; -}; - - - -Nepomuk::Search::DateParser::DateParser(const QString& text, unsigned int flags) : - d( new Private(text, flags) ) { -} - - -Nepomuk::Search::DateParser::~DateParser() { - delete d; -} - -bool Nepomuk::Search::DateParser::hasDate() { - return d->hasDate(); -} - -QDate Nepomuk::Search::DateParser::getDate() { - return d->getDate(); -} - -void Nepomuk::Search::DateParser::next() { - d->next(); -} - -unsigned int Nepomuk::Search::DateParser::pos() const { - return d->pos(); -} - -unsigned int Nepomuk::Search::DateParser::length() const { - return d->length(); -} - -class Nepomuk::Search::TimeParser::Private -{ -public: - Private(const QString& text) : m_text(text), m_locale(QLocale::English) { - // hh:mm[pm|am] - format time1( QRegExp( "\\b\\d{1,2}\\:\\d{2,2}\\s?(pm|am|AM|PM)?\\b" ), QStringList("h:map") << QString("h:m ap") ); - - // hh:mm - format time2( QRegExp( "\\b\\d{1,2}\\:\\d{2,2}\\b(?!\\s?(pm|am|AM|PM))\\b" ), QStringList("h:m") ); - - m_regexes.push_back( time1 ); - m_regexes.push_back( time2 ); - } - - - bool hasTime() { - if(!m_times.empty()) return true; - - while(m_times.empty() && !finishedParsing()) - { - parseAllRegexes(); - } - - if(!m_times.empty()) return true; - return false; - } - - - QTime next() { - return m_times.takeFirst(); - } -private: - bool finishedParsing() { - foreach(format r, m_regexes) { - if(r.pos != -1) return false; - } - return true; - } - - - void parseAllRegexes() { - QVector::iterator it ; - for(it = m_regexes.begin(); it != m_regexes.end(); ++it) { - it->pos = it->regex.indexIn(m_text, it->pos); - if( !it->useRelativeDate ) { - foreach(QString format, it->formats) { - QTime time = m_locale.toTime( it->regex.cap( 0 ), format ); - if(time.isValid()) { - kDebug() << "Found time:" << time; - m_times.append( time ); - break; - } - } - } - else { - QTime current( QTime::currentTime() ); - current.addSecs( it->difference.seconds ); - current.addSecs( it->difference.minutes * 60 ); - current.addSecs( it->difference.hours * 60 * 60 ); - - kDebug() << "Found time:" << current; - m_times.append( current ); - break; - } - } - } - - - const QString& m_text; - QLocale m_locale; - QVector m_regexes; - QList m_times; -}; - - - -Nepomuk::Search::TimeParser::TimeParser(const QString& text) : d( new Private(text) ) { -} - - -Nepomuk::Search::TimeParser::~TimeParser() { - delete d; -} - -bool Nepomuk::Search::TimeParser::hasTime() { - return d->hasTime(); -} - -QTime Nepomuk::Search::TimeParser::next() { - return d->next(); -} diff --git a/nepomuk/query/dateparser_p.h b/nepomuk/query/dateparser_p.h deleted file mode 100644 index 82513e20..00000000 --- a/nepomuk/query/dateparser_p.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef DATEPARSER_P_H -#define DATEPARSER_P_H - -/* -* This file is part of the Nepomuk KDE project. -* Copyright (c) 2009 Adam Kidder -* -* This library is free software; you can redistribute it and/or -* modify it under the terms of the GNU Library General Public -* License as published by the Free Software Foundation; either -* version 2 of the License, or (at your option) any later version. -* -* This library 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 -* Library General Public License for more details. -* -* You should have received a copy of the GNU Library General Public License -* along with this library; see the file COPYING.LIB. If not, write to -* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -* Boston, MA 02110-1301, USA. -*/ - -#include -#include - - -namespace Nepomuk { - namespace Search { - /*DateTimeParser parses a string to extract QDateTime object(s). It is (will be) capable of extracting: - * fully qualified date times - * times qualified using a specified date - * dates qualified with a specified time - */ - class DateTimeParser - { - public: - DateTimeParser(const QString& dateTimeString); - - - private: - const QString& text; - }; - - - class DateParser - { - public: - //flags - const static unsigned int AbsoluteDates = 0x1; - const static unsigned int RelativeDates = 0x2; - - DateParser(const QString& dateString, unsigned int flags = AbsoluteDates | RelativeDates); - ~DateParser(); - - //true if another date has been found - bool hasDate(); - //advances to the next date - void next(); - - //next 3 functions only valid if hasDate() - QDate getDate(); - //position of current extracted date - unsigned int pos() const; - //length of current extracted date string - unsigned int length() const; - private: - class Private; - Private* const d; - }; - - //FIXME: code duplication in DateParser and TimeParser - class TimeParser - { - public: - TimeParser(const QString& timeString); - ~TimeParser(); - - bool hasTime(); - QTime next(); - private: - class Private; - Private* const d; - }; - } -} -#endif diff --git a/nepomuk/query/dbusoperators.cpp b/nepomuk/query/dbusoperators.cpp deleted file mode 100644 index 844e7e65..00000000 --- a/nepomuk/query/dbusoperators.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* - Copyright (c) 2008-2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "dbusoperators_p.h" - -#include - -#include "resource.h" -#include "property.h" - -#include -#include - - -void Nepomuk::Query::registerDBusTypes() -{ - qDBusRegisterMetaType(); - qDBusRegisterMetaType >(); - qDBusRegisterMetaType(); - qDBusRegisterMetaType(); -} - - -QDBusArgument& operator<<( QDBusArgument& arg, const Nepomuk::Query::Result& result ) -{ - // - // Signature: (sda{s(isss)}a{s(isss)}s) - // - - arg.beginStructure(); - - // resource URI and score - arg << QString::fromLatin1( result.resource().resourceUri().toEncoded() ) << result.score(); - - // request properties - arg.beginMap( QVariant::String, qMetaTypeId() ); - QHash rp = result.requestProperties(); - for ( QHash::const_iterator it = rp.constBegin(); it != rp.constEnd(); ++it ) { - arg.beginMapEntry(); - arg << QString::fromLatin1( it.key().uri().toEncoded() ) << it.value(); - arg.endMapEntry(); - } - arg.endMap(); - - // additional bindings - arg.beginMap( QVariant::String, qMetaTypeId() ); - const Soprano::BindingSet additionalBindings = result.additionalBindings(); - foreach( const QString& binding, additionalBindings.bindingNames() ) { - arg.beginMapEntry(); - arg << binding << additionalBindings[binding]; - arg.endMapEntry(); - } - arg.endMap(); - - // full text search excerpt - arg << result.excerpt(); - - arg.endStructure(); - - return arg; -} - - -const QDBusArgument& operator>>( const QDBusArgument& arg, Nepomuk::Query::Result& result ) -{ - // - // Signature: (sda{s(isss)}s) - // - - arg.beginStructure(); - QString uri; - double score = 0.0; - - arg >> uri >> score; - result = Nepomuk::Query::Result( Nepomuk::Resource::fromResourceUri( QUrl::fromEncoded( uri.toLatin1() ) ), score ); - - arg.beginMap(); - while ( !arg.atEnd() ) { - QString rs; - Soprano::Node node; - arg.beginMapEntry(); - arg >> rs >> node; - arg.endMapEntry(); - result.addRequestProperty( QUrl::fromEncoded( rs.toLatin1() ), node ); - } - arg.endMap(); - - Soprano::BindingSet additionalBindings; - arg.beginMap(); - while ( !arg.atEnd() ) { - QString binding; - Soprano::Node node; - arg.beginMapEntry(); - arg >> binding >> node; - arg.endMapEntry(); - additionalBindings.insert( binding, node ); - } - arg.endMap(); - - QString excerpt; - arg >> excerpt; - result.setExcerpt( excerpt ); - - arg.endStructure(); - - result.setAdditionalBindings( additionalBindings ); - - return arg; -} - - -QDBusArgument& operator<<( QDBusArgument& arg, const Soprano::Node& node ) -{ - arg.beginStructure(); - arg << ( int )node.type(); - if ( node.type() == Soprano::Node::ResourceNode ) { - arg << QString::fromLatin1( node.uri().toEncoded() ); - } - else { - arg << node.toString(); - } - arg << node.language() << node.dataType().toString(); - arg.endStructure(); - return arg; -} - - -const QDBusArgument& operator>>( const QDBusArgument& arg, Soprano::Node& node ) -{ - // - // Signature: (isss) - // - arg.beginStructure(); - int type; - QString value, language, dataTypeUri; - arg >> type >> value >> language >> dataTypeUri; - if ( type == Soprano::Node::LiteralNode ) { - if ( dataTypeUri.isEmpty() ) - node = Soprano::Node( Soprano::LiteralValue::createPlainLiteral( value, language ) ); - else - node = Soprano::Node( Soprano::LiteralValue::fromString( value, QUrl::fromEncoded( dataTypeUri.toLatin1() ) ) ); - } - else if ( type == Soprano::Node::ResourceNode ) { - node = Soprano::Node( QUrl::fromEncoded( value.toLatin1() ) ); - } - else if ( type == Soprano::Node::BlankNode ) { - node = Soprano::Node( value ); - } - else { - node = Soprano::Node(); - } - arg.endStructure(); - return arg; -} diff --git a/nepomuk/query/dbusoperators_p.h b/nepomuk/query/dbusoperators_p.h deleted file mode 100644 index b1fb9743..00000000 --- a/nepomuk/query/dbusoperators_p.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - Copyright (c) 2008-2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_SEARCH_DBUS_OPERATORS_H_ -#define _NEPOMUK_SEARCH_DBUS_OPERATORS_H_ - -#include - -#include "result.h" -#include "query.h" -#include "term.h" -#include "nepomukquery_export.h" - -Q_DECLARE_METATYPE(Nepomuk::Query::Result) -Q_DECLARE_METATYPE(Soprano::Node) -Q_DECLARE_METATYPE(QList) -typedef QHash RequestPropertyMapDBus; -Q_DECLARE_METATYPE( RequestPropertyMapDBus ) - -namespace Nepomuk { - namespace Query { - /** - * Register the DBus types necessary for communication with the Nepomuk - * query service. This method is only made public for the query service - * itself which links to this library, too. - */ - NEPOMUKQUERY_EXPORT void registerDBusTypes(); - } -} - -// We export the non-public operators so that we do not need duplicated code in kdebase -NEPOMUKQUERY_EXPORT QDBusArgument& operator<<( QDBusArgument& arg, const Soprano::Node& ); -NEPOMUKQUERY_EXPORT const QDBusArgument& operator>>( const QDBusArgument& arg, Soprano::Node& ); - -NEPOMUKQUERY_EXPORT QDBusArgument& operator<<( QDBusArgument& arg, const Nepomuk::Query::Result& ); -NEPOMUKQUERY_EXPORT const QDBusArgument& operator>>( const QDBusArgument& arg, Nepomuk::Query::Result& ); - -#endif diff --git a/nepomuk/query/filequery.cpp b/nepomuk/query/filequery.cpp deleted file mode 100644 index a1e4edbc..00000000 --- a/nepomuk/query/filequery.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#include "filequery.h" -#include "query_p.h" - -Nepomuk::Query::FileQuery::FileQuery() - : Query() -{ - d->m_isFileQuery = true; -} - - -Nepomuk::Query::FileQuery::FileQuery( const Term& term ) - : Query( term ) -{ - d->m_isFileQuery = true; -} - - -Nepomuk::Query::FileQuery::FileQuery( const Query& query ) - : Query( query ) -{ - d->m_isFileQuery = true; -} - - -Nepomuk::Query::FileQuery::~FileQuery() -{ -} - - -Nepomuk::Query::FileQuery& Nepomuk::Query::FileQuery::operator=( const Query& query ) -{ - Query::operator=( query ); - d->m_isFileQuery = true; - return *this; -} - - -void Nepomuk::Query::FileQuery::addIncludeFolder( const KUrl& folder ) -{ - addIncludeFolder( folder, true ); -} - - -void Nepomuk::Query::FileQuery::addIncludeFolder( const KUrl& folder, bool recursive ) -{ - d->m_includeFolders[folder] = recursive; -} - - -void Nepomuk::Query::FileQuery::setIncludeFolders( const KUrl::List& folders ) -{ - d->m_includeFolders.clear(); - Q_FOREACH( const KUrl& url, folders ) { - d->m_includeFolders[url] = true; - } -} - - -void Nepomuk::Query::FileQuery::setIncludeFolders( const QHash& folders ) -{ - d->m_includeFolders = folders; -} - - -KUrl::List Nepomuk::Query::FileQuery::includeFolders() const -{ - return d->m_includeFolders.keys(); -} - - -QHash Nepomuk::Query::FileQuery::allIncludeFolders() const -{ - return d->m_includeFolders; -} - - -void Nepomuk::Query::FileQuery::addExcludeFolder( const KUrl& folder ) -{ - d->m_excludeFolders << folder; -} - - -void Nepomuk::Query::FileQuery::setExcludeFolders( const KUrl::List& folders ) -{ - d->m_excludeFolders = folders; -} - - -KUrl::List Nepomuk::Query::FileQuery::excludeFolders() const -{ - return d->m_excludeFolders; -} - - -void Nepomuk::Query::FileQuery::setFileMode( FileMode mode ) -{ - d->m_fileMode = mode; -} - - -Nepomuk::Query::FileQuery::FileMode Nepomuk::Query::FileQuery::fileMode() const -{ - return d->m_fileMode; -} diff --git a/nepomuk/query/filequery.h b/nepomuk/query/filequery.h deleted file mode 100644 index 2cdb53a5..00000000 --- a/nepomuk/query/filequery.h +++ /dev/null @@ -1,197 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_QUERY_FILE_QUERY_H_ -#define _NEPOMUK_QUERY_FILE_QUERY_H_ - -#include "query.h" -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class FileQuery filequery.h Nepomuk/Query/FileQuery - * - * \brief A Nepomuk desktop query specialized for file searches. - * - * FileQuery is an extension to Query which adds some syntactic sugar - * for dealing with file queries. This includes a restriction of the - * results to files and the possibility to restrict the search to - * specific folders via setIncludeFolders() and setExcludeFolders(). - * - * \warning %FileQuery does only return files and folders as results. - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT FileQuery : public Query - { - public: - /** - * Create an empty invalid file query object. - */ - FileQuery(); - - /** - * Create a file query with root term \a term. - * - * \since 4.6 - */ - explicit FileQuery( const Term& term ); - - /** - * Copy constructor. - */ - FileQuery( const Query& query ); - - /** - * Destructor - */ - ~FileQuery(); - - /** - * Assignment operator - */ - FileQuery& operator=( const Query& ); - - /** - * Add a folder to include in the search. If include folders are set the query - * will be restricted to files from that folders and their subfolders. - * - * \param folder The folder to include in the search. - * - * \sa setIncludeFolders, includeFolders, addExcludeFolder - */ - void addIncludeFolder( const KUrl& folder ); - - /** - * Add a folder to include in the search path. If include folders are set the query - * will be restricted to files from that folders and optionally their subfolders. - * - * \param folder The folder to include in the search. - * \param recursive If \p true subfolders of \p folder will be searched, too. - * - * \sa setIncludeFolders, includeFolders, addExcludeFolder - * - * \since 4.6 - */ - void addIncludeFolder( const KUrl& folder, bool recursive ); - - /** - * \overload - * - * \param folders The folders to include in the search. - * - * \sa addIncludeFolder, includeFolders, setExcludeFolders - */ - void setIncludeFolders( const KUrl::List& folders ); - - /** - * \overload - * - * \param folders A hash of the folders to include in the search and - * their recursive flag. - * - * \since 4.6 - */ - void setIncludeFolders( const QHash& folders ); - - /** - * The list of include folders set via addIncludeFolder() and - * setIncludeFolders(). - * - * \sa allIncludeFolders, addIncludeFolder, setIncludeFolders, excludeFolders - */ - KUrl::List includeFolders() const; - - /** - * The hash of include folders set via addIncludeFolder() and - * setIncludeFolders() including their recursive flag. - * - * \sa includeFolders, addIncludeFolder, setIncludeFolders, excludeFolders - * - * \since 4.6 - */ - QHash allIncludeFolders() const; - - /** - * Add a folder to exclude from the search. If exclude folders are set the query - * will be restricted to files that are not in that folder and its subfolders. - * - * \param folder The folder to exclude from the search. - * - * \sa setExcludeFolders, excludeFolders, addIncludeFolder - */ - void addExcludeFolder( const KUrl& folder ); - - /** - * \overload - * - * \param folders The folders to exclude from the search. - * - * \sa addExcludeFolder, excludeFolders, setIncludeFolders - */ - void setExcludeFolders( const KUrl::List& folders ); - - /** - * The list of exclude folders set via addExcludeFolder() and - * setExcludeFolders(). - * - * \sa addExcludeFolder, setExcludeFolders, includeFolders - */ - KUrl::List excludeFolders() const; - - /** - * An enumeration used in setFileMode() to state wether the query - * should return files and folders or only files or only folders. - * - * \since 4.5 - */ - enum FileModeFlags { - QueryFiles = 0x1, - QueryFolders = 0x2, - QueryFilesAndFolders = QueryFiles|QueryFolders - }; - Q_DECLARE_FLAGS( FileMode, FileModeFlags ) - - /** - * Set the file mode, i.e. wether the query should return - * files and folders or only files or only folders. - * By default both files and folders are returned. - * - * \sa fileMode() - * - * \since 4.5 - */ - void setFileMode( FileMode mode ); - - /** - * \return The file mode set in setFileMode() - * - * \since 4.5 - */ - FileMode fileMode() const; - }; - } -} - -Q_DECLARE_OPERATORS_FOR_FLAGS( Nepomuk::Query::FileQuery::FileMode ) - -#endif diff --git a/nepomuk/query/groupterm.cpp b/nepomuk/query/groupterm.cpp deleted file mode 100644 index 789e730f..00000000 --- a/nepomuk/query/groupterm.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "groupterm.h" -#include "groupterm_p.h" -#include "util.h" - -#include - -bool Nepomuk::Query::GroupTermPrivate::equals( const TermPrivate* other ) const -{ - if ( other->m_type == m_type ) { - const GroupTermPrivate* gtp = static_cast( other ); - return compareQList( gtp->m_subTerms, m_subTerms ); - } - else { - return false; - } -} - - -bool Nepomuk::Query::GroupTermPrivate::isValid() const -{ - if ( m_subTerms.count() ) { - foreach( const Term& t, m_subTerms ) { - if ( !t.isValid() ) - return false; - } - return true; - } - else { - return false; - } -} - - -Nepomuk::Query::GroupTerm::GroupTerm( const Term& term ) - : Term( term ) -{ -} - - -Nepomuk::Query::GroupTerm::GroupTerm( TermPrivate* d ) - : Term( d ) -{ -} - - -Nepomuk::Query::GroupTerm::GroupTerm( TermPrivate* d, - const Term& term1, - const Term& term2, - const Term& term3, - const Term& term4, - const Term& term5, - const Term& term6 ) - : Term( d ) -{ - addSubTerm( term1 ); - addSubTerm( term2 ); - if ( term3.isValid() ) - addSubTerm( term3 ); - if ( term4.isValid() ) - addSubTerm( term4 ); - if ( term5.isValid() ) - addSubTerm( term5 ); - if ( term6.isValid() ) - addSubTerm( term6 ); -} - - -Nepomuk::Query::GroupTerm::~GroupTerm() -{ -} - - -QList Nepomuk::Query::GroupTerm::subTerms() const -{ - N_D_CONST( GroupTerm ); - return d->m_subTerms; -} - - -void Nepomuk::Query::GroupTerm::setSubTerms( const QList& terms ) -{ - N_D( GroupTerm ); - d->m_subTerms = terms; -} - - -void Nepomuk::Query::GroupTerm::addSubTerm( const Term& term ) -{ - N_D( GroupTerm ); - d->m_subTerms << term; -} diff --git a/nepomuk/query/groupterm.h b/nepomuk/query/groupterm.h deleted file mode 100644 index 7fc290ae..00000000 --- a/nepomuk/query/groupterm.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_GROUP_TERM_H_ -#define _NEPOMUK_QUERY_GROUP_TERM_H_ - -#include "term.h" - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class GroupTerm groupterm.h Nepomuk/Query/GroupTerm - * - * \brief Abstract base class for AndTerm and OrTerm which - * maintains a list of sub-terms. - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT GroupTerm : public Term - { - public: - /** - * Destructor. - */ - ~GroupTerm(); - - /** - * The sub terms that are combined in this group. - * - * \sa setSubTerms() - */ - QList subTerms() const; - - /** - * Set the sub terms that are combined in this group. - * - * \sa subTerms() - */ - void setSubTerms( const QList& terms ); - - /** - * Add a sub term to the list of terms - * that are combined in this group. - * - * \sa setSubTerms(), subTerms() - */ - void addSubTerm( const Term& term ); - - protected: - /** \cond protected_error_members */ - GroupTerm( const Term& term ); - GroupTerm( TermPrivate* ); - GroupTerm( TermPrivate*, - const Term& term1, - const Term& term2, - const Term& term3 = Term(), - const Term& term4 = Term(), - const Term& term5 = Term(), - const Term& term6 = Term() ); - /** \endcond */ - }; - } -} - -#endif diff --git a/nepomuk/query/groupterm_p.h b/nepomuk/query/groupterm_p.h deleted file mode 100644 index 25f35593..00000000 --- a/nepomuk/query/groupterm_p.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_GROUP_TERM_P_H_ -#define _NEPOMUK_QUERY_GROUP_TERM_P_H_ - -#include "term_p.h" - -namespace Nepomuk { - namespace Query { - class GroupTermPrivate : public TermPrivate - { - public: - bool isValid() const; - bool equals( const TermPrivate* other ) const; - - QList m_subTerms; - }; - } -} - -#endif diff --git a/nepomuk/query/literalterm.cpp b/nepomuk/query/literalterm.cpp deleted file mode 100644 index 4f7557f9..00000000 --- a/nepomuk/query/literalterm.cpp +++ /dev/null @@ -1,271 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "literalterm.h" -#include "literalterm_p.h" -#include "querybuilderdata_p.h" -#include "query_p.h" - -#include -#include - -Nepomuk::Query::LiteralTermPrivate::LiteralTermPrivate() -{ - m_type = Term::Literal; -} - - -bool Nepomuk::Query::LiteralTermPrivate::equals( const TermPrivate* other ) const -{ - if ( other->m_type == m_type ) { - const LiteralTermPrivate* rtp = static_cast( other ); - return rtp->m_value == m_value; - } - else { - return false; - } -} - - -// -// A LiteralTerm not used in a ComparisonTerm is a "classical" plain text search term. That would mean "?r ?p ?v . ?v bif:contains 'foobar' . " -// But since many relations like nao:hasTag or nmm:performer or similar are considered as plain text fields we extend the pattern by adding -// relations to resources that have labels containing the query text. -// -QString Nepomuk::Query::LiteralTermPrivate::toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString &additionalFilters, QueryBuilderData *qbd ) const -{ - Q_UNUSED(parentTerm); - - if( m_value.toString().isEmpty() ) - return QString(); - - const QString p1 = qbd->uniqueVarName(); - const QString v1 = qbd->uniqueVarName(); - const QString r2 = qbd->uniqueVarName(); - const QString containsPattern = createContainsPattern( v1, m_value.toString(), qbd ); - - // { ?r ?p1 ?v1 . containsPattern(v1) } - // UNION - // { ?r ?p1 ?r2 . ?r2 rdfs:label ?v1 . containsPattern(v1) } . - return QString::fromLatin1( "{ %1 %2 %3 . %4 } " - "UNION " - "{ %1 %2 %5 . %5 %6 %3 . %4 } . " ) - .arg( resourceVarName, - p1, - v1, - containsPattern + additionalFilters, - r2, - Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::label()) ); -} - - -namespace { -QString prepareRegexText( const QString& text ) -{ - QString filterRxStr = QRegExp::escape( text ); - filterRxStr.replace( "\\*", QLatin1String( ".*" ) ); - filterRxStr.replace( "\\?", QLatin1String( "." ) ); - filterRxStr.replace( '\\',"\\\\" ); - return filterRxStr; -} -} - - -QString Nepomuk::Query::LiteralTermPrivate::createContainsPattern( const QString& varName, const QString& text, Nepomuk::Query::QueryBuilderData* qbd ) -{ - if( text.isEmpty() ) - return QString(); - - // each token with a negation flag - QList > containsTokens; - QList > regexTokens; - - // we only support AND or OR, not both at the same time - // TODO: Fix this. Virtuoso supports a combination of both - bool isUnion = false; - - // gather all the tokens - bool inQuotes = false; - QString currentToken; - bool nextIsNegated = false; - int i = 0; - while( i < text.length() ) { - const QChar& c = text[i]; - bool tokenEnd = false; - - if( c == QChar('"') || c == QChar('\'') ) { - inQuotes = !inQuotes; - tokenEnd = !inQuotes; - } - else if( c.isSpace() && !inQuotes ) { - tokenEnd = true; - } - else { - currentToken.append(c); - } - - if( i == text.length()-1 ) { - tokenEnd = true; - } - - if( tokenEnd && !currentToken.isEmpty() ) { - // - // Handle the three special tokens supported in Virtuoso's full text search engine we support (there is also "near" which we do not handle yet) - // - if( currentToken.toLower() == QLatin1String("and") ) { - isUnion = false; - } - else if( currentToken.toLower() == QLatin1String("or") ) { - isUnion = true; - } - else if( currentToken.toLower() == QLatin1String("not") ) { - nextIsNegated = true; - } - else { - QPair currentTokenPair = qMakePair( currentToken, nextIsNegated ); - - // - // Virtuoso needs four leading chars when using wildcards. Thus, if there is less (this includes 0) we fall back to the slower regex filter - // - const QStringList subTokens = currentToken.split( QLatin1Char(' '), QString::SkipEmptyParts ); - bool needsRegex = false; - QRegExp regex(QLatin1String("[\\?\\*]")); // The regex used to check if we needs a regex - Q_FOREACH( const QString& subToken, subTokens ) { - const int i = subToken.indexOf( regex ); - if( i >= 0 && i < 4 ) { - needsRegex = true; - break; - } - } - if( !needsRegex ) { - containsTokens << currentTokenPair; - } - else { - regexTokens << currentTokenPair; - } - } - - nextIsNegated = false; - currentToken.clear(); - } - - ++i; - } - - // add optional NOT terms to the contains tokens and build the search excerpts terms - QStringList containsFilterTokens; - QStringList fullTextTerms; - for( int i = 0; i < containsTokens.count(); ++i ) { - QString containsFilterToken; - if( containsTokens[i].second ) - containsFilterToken += QLatin1String("NOT "); - containsFilterToken += QString::fromLatin1("'%1'").arg(containsTokens[i].first); - containsFilterTokens << containsFilterToken; - - // we only want to show excerpt with the actually searched terms - if( !containsTokens[i].second ) - fullTextTerms << containsTokens[i].first; - } - if( !fullTextTerms.isEmpty() ) { - qbd->addFullTextSearchTerms( varName, fullTextTerms ); - } - - const QString finalContainsToken = containsFilterTokens.join( isUnion ? QLatin1String(" OR ") : QLatin1String(" AND ")); - - // convert the regex tokens into SPARQL filters - QStringList filters; - for( int i = 0; i < regexTokens.count(); ++i ) { - QString regexFilter; - if( regexTokens[i].second ) - regexFilter += QLatin1Char('!'); - regexFilter += QString::fromLatin1( "REGEX(%1, \"%2\", 'i')" ) - .arg( varName, - prepareRegexText(regexTokens[i].first) ); - filters << regexFilter; - } - - // - // with the current filter design we can only support full-text scoring if we either - // only have contains pattern or if isUnion is false. In the latter case we can simply - // use a normal graph pattern and a FILTER. - // - QString containsPattern; - if( !containsFilterTokens.isEmpty() && - qbd->query()->m_fullTextScoringEnabled && - (regexTokens.isEmpty() || !isUnion) ) { - containsPattern = QString::fromLatin1("%1 bif:contains \"%2\" OPTION (score %3) . ") - .arg( varName, - finalContainsToken, - qbd->createScoringVariable() ); - } - - // - // The fallback is to add bif:contains as a filter. This syntax does not support scoring though. - // - else if( !containsFilterTokens.isEmpty() ) { - filters << QString::fromLatin1("bif:contains(%1, \"%2\")").arg( varName, finalContainsToken ); - } - - QString filterPattern; - if(!filters.isEmpty()) - filterPattern = QString( QLatin1String("FILTER(") + filters.join( isUnion ? QLatin1String(" || ") : QLatin1String(" && ") ) + QLatin1String(") . ") ); - - return filterPattern + containsPattern; -} - - -Nepomuk::Query::LiteralTerm::LiteralTerm( const LiteralTerm& term ) - : Term( term ) -{ -} - - -Nepomuk::Query::LiteralTerm::LiteralTerm( const Soprano::LiteralValue& value ) - : Term( new LiteralTermPrivate() ) -{ - setValue( value ); -} - - -Nepomuk::Query::LiteralTerm::~LiteralTerm() -{ -} - - -Nepomuk::Query::LiteralTerm& Nepomuk::Query::LiteralTerm::operator=( const LiteralTerm& term ) -{ - d_ptr = term.d_ptr; - return *this; -} - - -Soprano::LiteralValue Nepomuk::Query::LiteralTerm::value() const -{ - N_D_CONST( LiteralTerm ); - return d->m_value; -} - - -void Nepomuk::Query::LiteralTerm::setValue( const Soprano::LiteralValue& value ) -{ - N_D( LiteralTerm ); - d->m_value = value; -} diff --git a/nepomuk/query/literalterm.h b/nepomuk/query/literalterm.h deleted file mode 100644 index 9db78e68..00000000 --- a/nepomuk/query/literalterm.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_LITERAL_TERM_H_ -#define _NEPOMUK_QUERY_LITERAL_TERM_H_ - -#include "term.h" - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class LiteralTerm literalterm.h Nepomuk/Query/LiteralTerm - * - * \brief Match literal properties via full text. - * - * Other than the rest of the terms LiteralTerm has two uses: - * - * \section literalterm_comparison Usage in ComparisonTerm - * - * %LiteralTerm can be used in a ComparisonTerm with both properties - * with a literal range and a resource range. The former case is the simple - * one: the value() of the %LiteralTerm will simply be compared to the value - * of the ComparisonTerm::property(). In the latter case value() will be - * matched to rdfs:label of any resource. So in essence the following two - * examples are equal: - * - * \code - * ComparisonTerm( Vocabulary::NAO::hasTag(), LiteralTerm("nepomuk") ); - * ComparisonTerm( Vocabulary::NAO::hasTag(), ComparisonTerm( Vocabulary::RDFS::label(), LiteralTerm("nepomuk") ) ); - * \endcode - * - * - * \section literalterm_plain Usage as "stand-alone" term - * - * As a term by itself %LiteralTerm will act like a traditional full text query and - * match all resources that contain the string value in some property. - * - * \code - * LiteralTerm( "nepomuk" ); - * \endcode - * - * The example above will match all resources that have a property with a value containing - * the string "nepomuk". - * - * \section literalterm_examples Examples - * - *
LiteralTerm("nepomuk")
searches for the term "nepomuk". - * - *
LiteralTerm("'nepomuk*'")
searches for the terms starting with "nepomuk". - * - *
LiteralTerm("'nepomuk kde'")
searches for the term "nepomuk kde". - * - *
LiteralTerm("'nepomuk* kde'")
searches for terms matching "nepomuk* kde". - * - * %LiteralTerm always tries to normalize the query terms as best as possible. This includes - * automatically adding quotes as needed. - * - * \warning Be aware that the examples above apply to using %LiteralTerm as a stand-alone term - * or in a ComparisonTerm::Contains term. When using ComparisonTerm::Regexp the test as specified - * will be used as-is to create the regular expression. - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT LiteralTerm : public Term - { - public: - /** - * Copy constructor. - */ - LiteralTerm( const LiteralTerm& term ); - - /** - * Default constructor - * - * \param value The value this %LiteralTerm should match to. - */ - LiteralTerm( const Soprano::LiteralValue& value = Soprano::LiteralValue() ); - - /** - * Desctructor. - */ - ~LiteralTerm(); - - /** - * Assignment operator. - */ - LiteralTerm& operator=( const LiteralTerm& term ); - - /** - * The value this %LiteralTerm should match to. - * - * \sa setValue() - */ - Soprano::LiteralValue value() const; - - /** - * Set the value this %LiteralTerm should match to. - * - * \sa value() - */ - void setValue( const Soprano::LiteralValue& value ); - }; - } -} - -#endif diff --git a/nepomuk/query/literalterm_p.h b/nepomuk/query/literalterm_p.h deleted file mode 100644 index 87958934..00000000 --- a/nepomuk/query/literalterm_p.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_LITERAL_TERM_P_H_ -#define _NEPOMUK_QUERY_LITERAL_TERM_P_H_ - -#include "term_p.h" - -#include - -namespace Nepomuk { - namespace Query { - class LiteralTermPrivate : public TermPrivate - { - public: - LiteralTermPrivate(); - - TermPrivate* clone() const { return new LiteralTermPrivate( *this ); } - - bool equals( const TermPrivate* other ) const; - bool isValid() const { return m_value.isValid(); } - QString toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString& additionalFilters, QueryBuilderData* qbd ) const; - - static QString createContainsPattern( const QString& varName, const QString& text, QueryBuilderData* qbd ); - - Soprano::LiteralValue m_value; - }; - } -} - -#endif diff --git a/nepomuk/query/negationterm.cpp b/nepomuk/query/negationterm.cpp deleted file mode 100644 index 03e49a12..00000000 --- a/nepomuk/query/negationterm.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "negationterm.h" -#include "negationterm_p.h" -#include "querybuilderdata_p.h" -#include "andterm.h" -#include "andterm_p.h" -#include "comparisonterm.h" - -QString Nepomuk::Query::NegationTermPrivate::toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString &additionalFilters, QueryBuilderData *qbd ) const -{ - // - // A small optimization: we can negate filters very easily - // - if(m_subTerm.isComparisonTerm() && m_subTerm.toComparisonTerm().comparator() == ComparisonTerm::Regexp) { - QString term = m_subTerm.d_ptr->toSparqlGraphPattern( resourceVarName, parentTerm, additionalFilters, qbd ); - const int pos = term.indexOf(QLatin1String("FILTER")); - term.insert(pos+7, QLatin1Char('!')); - return term; - } - else { - // - // A negation is expressed via a filter. Since filters can only work on a "real" graph pattern - // we need to make sure that such a pattern exists. This can be done by searching one in a - // surrounding AndTerm. - // - // Why is that enough? - // Nested AndTerms are flattened before the SPARQL query is constructed in Query. Thus, an AndTerm can - // only be embedded in an OrTerm or as a child term to either a ComparisonTerm or an OptionalTerm. - // In both cases we need a real pattern inside the AndTerm. - // - // We use a type pattern for performance reasons. Thus, we assume that each resource has a type. This - // is not perfect but much faster than using a wildcard for the property. And in the end all Nepomuk - // resources should have a properly defined type. - // - // FIXME: remove the type pattern. Instead perform optimization before which copies the negation into all unions - bool haveRealTerm = false; - if( parentTerm && parentTerm->m_type == Term::And ) { - haveRealTerm = static_cast(parentTerm)->hasRealPattern(); - } - - QString term; - if( !haveRealTerm ) { - term += QString::fromLatin1("%1 a %2 . ") - .arg( resourceVarName, qbd->uniqueVarName() ); - } - - term += QString( "FILTER NOT EXISTS { %1 } . " ) - .arg( m_subTerm.d_ptr->toSparqlGraphPattern( resourceVarName, this, QString(), qbd ) ); - - term += additionalFilters; - - return term; - } -} - - -Nepomuk::Query::NegationTerm::NegationTerm() - : SimpleTerm( new NegationTermPrivate() ) -{ -} - - -Nepomuk::Query::NegationTerm::NegationTerm( const NegationTerm& term ) - : SimpleTerm( term ) -{ -} - - -Nepomuk::Query::NegationTerm::~NegationTerm() -{ -} - - -Nepomuk::Query::NegationTerm& Nepomuk::Query::NegationTerm::operator=( const NegationTerm& term ) -{ - d_ptr = term.d_ptr; - return *this; -} - - -Nepomuk::Query::Term Nepomuk::Query::NegationTerm::negateTerm( const Term& term ) -{ - if ( term.isNegationTerm() ) { - return term.toNegationTerm().subTerm(); - } - else { - NegationTerm nt; - nt.setSubTerm( term ); - return nt; - } -} diff --git a/nepomuk/query/negationterm.h b/nepomuk/query/negationterm.h deleted file mode 100644 index b176de07..00000000 --- a/nepomuk/query/negationterm.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_NEGATION_TERM_H_ -#define _NEPOMUK_QUERY_NEGATION_TERM_H_ - -#include "simpleterm.h" - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class NegationTerm negationterm.h Nepomuk/Query/NegationTerm - * - * \brief Negate an arbitrary term. - * - * %NegationTerm can be used to negate any other term. A typical example - * could be to match all resources that do not have a specific tag: - * - * \code - * NegationTerm::negateTerm( ComparisonTerm( Vocabulary::NAO::hasTag(), LiteralTerm("nepomuk") ) ); - * \endcode - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT NegationTerm : public SimpleTerm - { - public: - /** - * Default constructor: creates an invalid negation term. - */ - NegationTerm(); - - /** - * Copy constructor. - */ - NegationTerm( const NegationTerm& term ); - - /** - * Destructor. - */ - ~NegationTerm(); - - /** - * Assignment operator. - */ - NegationTerm& operator=( const NegationTerm& term ); - - /** - * Negate \p term. This method will either strip the first NegationTerm - * from \p term or add one. - * - * \return The negated term. - */ - static Term negateTerm( const Term& term ); - }; - } -} - -#endif diff --git a/nepomuk/query/negationterm_p.h b/nepomuk/query/negationterm_p.h deleted file mode 100644 index e0a0168d..00000000 --- a/nepomuk/query/negationterm_p.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_NEGATION_TERM_P_H_ -#define _NEPOMUK_QUERY_NEGATION_TERM_P_H_ - -#include "simpleterm_p.h" - -namespace Nepomuk { - namespace Query { - class NegationTermPrivate : public SimpleTermPrivate - { - public: - NegationTermPrivate() { - m_type = Term::Negation; - } - - TermPrivate* clone() const { return new NegationTermPrivate( *this ); } - - QString toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString& additionalFilters, QueryBuilderData* qbd ) const; - }; - } -} - -#endif diff --git a/nepomuk/query/nepomukquery_export.h b/nepomuk/query/nepomukquery_export.h deleted file mode 100644 index 14a051dd..00000000 --- a/nepomuk/query/nepomukquery_export.h +++ /dev/null @@ -1,43 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 David Faure - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef NEPOMUKQUERY_EXPORT_H -#define NEPOMUKQUERY_EXPORT_H - -/* needed for KDE_EXPORT and KDE_IMPORT macros */ -#include - -#ifndef NEPOMUKQUERY_EXPORT -# if defined(KDELIBS_STATIC_LIBS) - /* No export/import for static libraries */ -# define NEPOMUKQUERY_EXPORT -# elif defined(MAKE_NEPOMUKQUERY_LIB) - /* We are building this library */ -# define NEPOMUKQUERY_EXPORT KDE_EXPORT -# else - /* We are using this library */ -# define NEPOMUKQUERY_EXPORT KDE_IMPORT -# endif -#endif - -# ifndef NEPOMUKQUERY_EXPORT_DEPRECATED -# define NEPOMUKQUERY_EXPORT_DEPRECATED KDE_DEPRECATED NEPOMUKQUERY_EXPORT -# endif - -#endif diff --git a/nepomuk/query/optionalterm.cpp b/nepomuk/query/optionalterm.cpp deleted file mode 100644 index 1177747b..00000000 --- a/nepomuk/query/optionalterm.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "optionalterm.h" -#include "optionalterm_p.h" -#include "querybuilderdata_p.h" - -QString Nepomuk::Query::OptionalTermPrivate::toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString &additionalFilters, QueryBuilderData *qbd ) const -{ - Q_UNUSED(parentTerm); - - return QString( "OPTIONAL { %1} " ) - .arg( m_subTerm.d_ptr->toSparqlGraphPattern( resourceVarName, this, additionalFilters, qbd ) ); -} - - -Nepomuk::Query::OptionalTerm::OptionalTerm() - : SimpleTerm( new OptionalTermPrivate() ) -{ -} - - -Nepomuk::Query::OptionalTerm::OptionalTerm( const OptionalTerm& term ) - : SimpleTerm( term ) -{ -} - - -Nepomuk::Query::OptionalTerm::~OptionalTerm() -{ -} - - -Nepomuk::Query::OptionalTerm& Nepomuk::Query::OptionalTerm::operator=( const OptionalTerm& term ) -{ - d_ptr = term.d_ptr; - return *this; -} - - -Nepomuk::Query::Term Nepomuk::Query::OptionalTerm::optionalizeTerm( const Term& term ) -{ - if ( !term.isOptionalTerm() ) { - OptionalTerm ot; - ot.setSubTerm(term); - return ot; - } - else { - return term; - } -} diff --git a/nepomuk/query/optionalterm.h b/nepomuk/query/optionalterm.h deleted file mode 100644 index e34898a7..00000000 --- a/nepomuk/query/optionalterm.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_OPTIONAL_TERM_H_ -#define _NEPOMUK_QUERY_OPTIONAL_TERM_H_ - -#include "simpleterm.h" - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class OptionalTerm optionalterm.h Nepomuk/Query/OptionalTerm - * - * \brief Make a term optional. - * - * %OptionalTerm can be used to mark another term as optional. - * This is mostly useful with subterms of type ComparisonTerm - * (or an AndTerm combining ComparisonTerms) which either have - * additional bindings (ComparisonTerm::setVariableName()) or - * a specified sort weight (ComparisonTerm::setSortWeight()). - * - * \author Sebastian Trueg - * - * \since 4.5 - */ - class NEPOMUKQUERY_EXPORT OptionalTerm : public SimpleTerm - { - public: - /** - * Default constructor: creates an invalid optional term. - */ - OptionalTerm(); - - /** - * Copy constructor. - */ - OptionalTerm( const OptionalTerm& term ); - - /** - * Destructor. - */ - ~OptionalTerm(); - - /** - * Assignment operator. - */ - OptionalTerm& operator=( const OptionalTerm& term ); - - /** - * Mark \p term as optional. This method will encasulate - * \p term in an OptionalTerm except if \p term is already - * of type OptionalTerm. - * - * \return The optional term. - */ - static Term optionalizeTerm( const Term& term ); - }; - } -} - -#endif diff --git a/nepomuk/query/optionalterm_p.h b/nepomuk/query/optionalterm_p.h deleted file mode 100644 index 7efc7c05..00000000 --- a/nepomuk/query/optionalterm_p.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_OPTIONAL_TERM_P_H_ -#define _NEPOMUK_QUERY_OPTIONAL_TERM_P_H_ - -#include "simpleterm_p.h" - -namespace Nepomuk { - namespace Query { - class OptionalTermPrivate : public SimpleTermPrivate - { - public: - OptionalTermPrivate() { - m_type = Term::Optional; - } - - TermPrivate* clone() const { return new OptionalTermPrivate( *this ); } - - QString toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString& additionalFilters, QueryBuilderData* qbd ) const; - }; - } -} - -#endif diff --git a/nepomuk/query/org.kde.nepomuk.Query.xml b/nepomuk/query/org.kde.nepomuk.Query.xml deleted file mode 100644 index 96e131a8..00000000 --- a/nepomuk/query/org.kde.nepomuk.Query.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nepomuk/query/org.kde.nepomuk.QueryService.xml b/nepomuk/query/org.kde.nepomuk.QueryService.xml deleted file mode 100644 index 52d8e8fd..00000000 --- a/nepomuk/query/org.kde.nepomuk.QueryService.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/nepomuk/query/orterm.cpp b/nepomuk/query/orterm.cpp deleted file mode 100644 index 30cf081a..00000000 --- a/nepomuk/query/orterm.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "orterm.h" -#include "orterm_p.h" -#include "querybuilderdata_p.h" - -#include - -QString Nepomuk::Query::OrTermPrivate::toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString &additionalFilters, QueryBuilderData *qbd ) const -{ - Q_UNUSED(parentTerm); - - QStringList pattern; - - qbd->pushGroupTerm(this); - foreach( const Nepomuk::Query::Term &t, m_subTerms ) { - pattern += t.d_ptr->toSparqlGraphPattern( resourceVarName, this, additionalFilters, qbd ); - } - qbd->popGroupTerm(); - - return QLatin1String( "{ " ) + pattern.join( QLatin1String( "} UNION { ") ) + QLatin1String( "} . " ); -} - - -Nepomuk::Query::OrTerm::OrTerm() - : GroupTerm( new OrTermPrivate() ) -{ -} - - -Nepomuk::Query::OrTerm::OrTerm( const OrTerm& term ) - : GroupTerm( term ) -{ -} - - -Nepomuk::Query::OrTerm::OrTerm( const Term& term1, - const Term& term2, - const Term& term3, - const Term& term4, - const Term& term5, - const Term& term6 ) - : GroupTerm( new OrTermPrivate(), - term1, - term2, - term3, - term4, - term5, - term6 ) -{ -} - - -Nepomuk::Query::OrTerm::OrTerm( const QList& terms ) - : GroupTerm( new OrTermPrivate() ) -{ - setSubTerms( terms ); -} - - -Nepomuk::Query::OrTerm::~OrTerm() -{ -} - - -Nepomuk::Query::OrTerm& Nepomuk::Query::OrTerm::operator=( const OrTerm& term ) -{ - d_ptr = term.d_ptr; - return *this; -} diff --git a/nepomuk/query/orterm.h b/nepomuk/query/orterm.h deleted file mode 100644 index 85907cc0..00000000 --- a/nepomuk/query/orterm.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_OR_TERM_H_ -#define _NEPOMUK_QUERY_OR_TERM_H_ - -#include "groupterm.h" - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class OrTerm orterm.h Nepomuk/Query/OrTerm - * - * \brief Match resource that match at least one of the sub terms. - * - * This class - like AndTerm - is derived from GroupTerm which - * handles the sub terms. - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT OrTerm : public GroupTerm - { - public: - /** - * Default constructor: creates an invalid or-term. - */ - OrTerm(); - - /** - * Copy constructor. - */ - OrTerm( const OrTerm& term ); - - /** - * Convinience constructor which allows - * to combine several terms in one line. - */ - OrTerm( const Term& term1, - const Term& term2, - const Term& term3 = Term(), - const Term& term4 = Term(), - const Term& term5 = Term(), - const Term& term6 = Term() ); - - /** - * Combine \p terms into one and-term. - */ - OrTerm( const QList& terms ); - - /** - * Destructor. - */ - ~OrTerm(); - - /** - * Assignment operator. - */ - OrTerm& operator=( const OrTerm& term ); - }; - } -} - -#endif diff --git a/nepomuk/query/orterm_p.h b/nepomuk/query/orterm_p.h deleted file mode 100644 index a94f68de..00000000 --- a/nepomuk/query/orterm_p.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_OR_TERM_P_H_ -#define _NEPOMUK_QUERY_OR_TERM_P_H_ - -#include "groupterm_p.h" - -namespace Nepomuk { - namespace Query { - class OrTermPrivate : public GroupTermPrivate - { - public: - OrTermPrivate() { - m_type = Term::Or; - } - - TermPrivate* clone() const { return new OrTermPrivate( *this ); } - - QString toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate*, const QString& additionalFilters, QueryBuilderData* qbd ) const; - }; - } -} - -#endif diff --git a/nepomuk/query/query.cpp b/nepomuk/query/query.cpp deleted file mode 100644 index aca4fa43..00000000 --- a/nepomuk/query/query.cpp +++ /dev/null @@ -1,730 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#include "query.h" -#include "query_p.h" -#include "term.h" -#include "term_p.h" -#include "nie.h" -#include "nfo.h" -#include "querybuilderdata_p.h" -#include "literalterm.h" -#include "resourceterm.h" -#include "andterm.h" -#include "orterm.h" -#include "negationterm.h" -#include "comparisonterm.h" -#include "resourcetypeterm.h" -#include "resourcetypeterm_p.h" -#include "optionalterm.h" -#include "queryserializer.h" -#include "queryparser.h" -#include "util.h" -#include "filequery.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "resourcemanager.h" -#include "literal.h" -#include "property.h" -#include "class.h" - -#include - -/* -## Full Text Score -## Entity Rank -## Surfaced via SPARQL - -SELECT ?s ?sc ( (?s) ) as ?Rank -WHERE { ?s ?p ?o . -?o bif:contains 'NEW AND YOR' option (score ?sc). } -ORDER BY desc (? -*/ - - -Nepomuk::Query::Term Nepomuk::Query::QueryPrivate::createFolderFilter() const -{ - Term mainTerm; - - if ( !m_includeFolders.isEmpty() ) { - QStringList includeFilter; - for( QHash::ConstIterator it = m_includeFolders.constBegin(); - it != m_includeFolders.constEnd(); ++it ) { - const QString urlStr = it.key().url(KUrl::AddTrailingSlash); - if( it.value() ) - includeFilter.append( QString::fromLatin1("(^%1)").arg( urlStr ) ); - else - includeFilter.append( QString::fromLatin1("(^%1[^/]*$)").arg( urlStr ) ); - } - mainTerm = mainTerm && ComparisonTerm( - Nepomuk::Vocabulary::NIE::url(), - LiteralTerm(includeFilter.join( "|" )), - ComparisonTerm::Regexp); - } - - if ( !m_excludeFolders.isEmpty() ) { - mainTerm = mainTerm && NegationTerm::negateTerm( - ComparisonTerm( - Nepomuk::Vocabulary::NIE::url(), - LiteralTerm(QString::fromLatin1("^(%1)").arg( m_excludeFolders.toStringList(KUrl::AddTrailingSlash).join( "|" ) )), - ComparisonTerm::Regexp)); - } - return mainTerm; -} - - -Nepomuk::Query::Term Nepomuk::Query::QueryPrivate::optimizeEvenMore(const Nepomuk::Query::Term& term) const -{ - using namespace Nepomuk::Query; - - // - // Merge ResourceTypeTerms which are combined in an OrTerm - // - if(term.type() == Term::Or) { - QList subTerms = term.toOrTerm().subTerms(); - QList typeTerms; - QList::iterator it = subTerms.begin(); - while(it != subTerms.end()) { - if(it->type() == Term::ResourceType) { - typeTerms << it->toResourceTypeTerm(); - it = subTerms.erase(it); - } - else { - ++it; - } - } - - if(typeTerms.count() > 1) { - ResourceTypeTerm newTypeTerm; - foreach(const ResourceTypeTerm& rtt, typeTerms) { - static_cast(newTypeTerm.d_ptr.data())->m_types << rtt.type(); - } - subTerms << newTypeTerm; - } - else if(typeTerms.count() == 1) { - subTerms += typeTerms.first(); - } - - if(subTerms.count() > 1) - return OrTerm(subTerms); - else if(subTerms.count() == 1) - return subTerms.first(); - else - return OrTerm(); - } - - // - // For AndTerms we simply need to optimize the subterms - // - else if(term.type() == Term::And) { - AndTerm newAndTerm; - // - // Another small optimization: we sort all the ComparisonTerms which have a variable name set - // at the beginning. This allows to force this variable name in other ComparisonTerms that use - // the same property (for details see QueryBuilderData::uniqueVarName) - // - QList sortedSubTerms; - foreach( const Nepomuk::Query::Term &t, term.toAndTerm().subTerms() ) { - if(t.isComparisonTerm() && !t.toComparisonTerm().variableName().isEmpty()) { - sortedSubTerms.prepend(t); - } - else { - sortedSubTerms.append(t); - } - } - - foreach(const Term& subTerm, sortedSubTerms) { - newAndTerm.addSubTerm(optimizeEvenMore(subTerm)); - } - return newAndTerm; - } - - // - // For OptionalTerms we simply need to optimize the subterm - // - else if(term.type() == Term::Optional) { - return OptionalTerm::optionalizeTerm(optimizeEvenMore(term.toOptionalTerm().subTerm())); - } - - // - // For NegationTerms we simply need to optimize the subterm - // - else if(term.type() == Term::Negation) { - return NegationTerm::negateTerm(optimizeEvenMore(term.toNegationTerm().subTerm())); - } - - else { - return term; - } -} - - -class Nepomuk::Query::Query::RequestProperty::Private : public QSharedData -{ -public: - Nepomuk::Types::Property m_property; - bool m_optional; -}; - -Nepomuk::Query::Query::RequestProperty::RequestProperty( const Nepomuk::Types::Property& property, - bool optional ) - : d(new Private()) -{ - d->m_property = property; - d->m_optional = optional; -} - -Nepomuk::Query::Query::RequestProperty::RequestProperty( const RequestProperty& other ) -{ - d = other.d; -} - -Nepomuk::Query::Query::RequestProperty::~RequestProperty() -{ -} - -Nepomuk::Query::Query::RequestProperty& Nepomuk::Query::Query::RequestProperty::operator=( const RequestProperty& other ) -{ - d = other.d; - return *this; -} - -Nepomuk::Types::Property Nepomuk::Query::Query::RequestProperty::property() const -{ - return d->m_property; -} - -bool Nepomuk::Query::Query::RequestProperty::optional() const -{ - return d->m_optional; -} - -bool Nepomuk::Query::Query::RequestProperty::operator==( const RequestProperty& other ) const -{ - return d->m_property == other.d->m_property && d->m_optional == other.d->m_optional; -} - - -Nepomuk::Query::Query::Query() - : d( new QueryPrivate() ) -{ -} - - -Nepomuk::Query::Query::Query( const Query& other ) -{ - d = other.d; -} - - -Nepomuk::Query::Query::Query( const Term& term ) - : d ( new QueryPrivate() ) -{ - d->m_term = term; -} - - -Nepomuk::Query::Query::~Query() -{ -} - - -Nepomuk::Query::Query& Nepomuk::Query::Query::operator=( const Query& other ) -{ - d = other.d; - return *this; -} - - -Nepomuk::Query::Query& Nepomuk::Query::Query::operator=( const Term& term ) -{ - d->m_term = term; - return *this; -} - - -bool Nepomuk::Query::Query::isValid() const -{ - return( d->m_term.isValid() || isFileQuery() ); -} - - -bool Nepomuk::Query::Query::isFileQuery() const -{ - return d->m_isFileQuery; -} - - -Nepomuk::Query::FileQuery Nepomuk::Query::Query::toFileQuery() const -{ - return FileQuery( *this ); -} - - -Nepomuk::Query::Term Nepomuk::Query::Query::term() const -{ - return d->m_term; -} - - -int Nepomuk::Query::Query::limit() const -{ - return d->m_limit; -} - - -int Nepomuk::Query::Query::offset() const -{ - return d->m_offset; -} - - -void Nepomuk::Query::Query::setTerm( const Term& term ) -{ - d->m_term = term; -} - - -void Nepomuk::Query::Query::setLimit( int limit ) -{ - d->m_limit = limit; -} - - -void Nepomuk::Query::Query::setOffset( int offset ) -{ - d->m_offset = offset; -} - - -void Nepomuk::Query::Query::setFullTextScoringEnabled( bool enabled ) -{ - d->m_fullTextScoringEnabled = enabled; -} - - -void Nepomuk::Query::Query::setFullTextScoringSortOrder( Qt::SortOrder order ) -{ - d->m_fullTextScoringSortOrder = order; -} - - -bool Nepomuk::Query::Query::fullTextScoringEnabled() const -{ - return d->m_fullTextScoringEnabled; -} - - -Qt::SortOrder Nepomuk::Query::Query::fullTextScoringSortOrder() const -{ - return d->m_fullTextScoringSortOrder; -} - - -void Nepomuk::Query::Query::setQueryFlags( QueryFlags flags ) -{ - d->m_flags = flags; -} - - -Nepomuk::Query::Query::QueryFlags Nepomuk::Query::Query::queryFlags() const -{ - return d->m_flags; -} - - -void Nepomuk::Query::Query::addRequestProperty( const RequestProperty& property ) -{ - d->m_requestProperties.append( property ); -} - - -void Nepomuk::Query::Query::setRequestProperties( const QList& properties ) -{ - d->m_requestProperties = properties; -} - - -QList Nepomuk::Query::Query::requestProperties() const -{ - return d->m_requestProperties; -} - - -bool Nepomuk::Query::Query::operator==( const Query& other ) const -{ - return( d->m_limit == other.d->m_limit && - d->m_offset == other.d->m_offset && - d->m_term == other.d->m_term && - compareQList( d->m_requestProperties, other.d->m_requestProperties ) && - compareHash( d->m_includeFolders, other.d->m_includeFolders ) && - compareQList( d->m_excludeFolders, other.d->m_excludeFolders ) && - d->m_isFileQuery == other.d->m_isFileQuery && - d->m_fileMode == other.d->m_fileMode ); -} - - -bool Nepomuk::Query::Query::operator!=( const Query& other ) const -{ - return( d->m_limit != other.d->m_limit || - d->m_offset != other.d->m_offset || - d->m_term != other.d->m_term || - !compareQList( d->m_requestProperties, other.d->m_requestProperties ) || - !compareHash( d->m_includeFolders, other.d->m_includeFolders ) || - !compareQList( d->m_excludeFolders, other.d->m_excludeFolders ) || - d->m_isFileQuery != other.d->m_isFileQuery || - d->m_fileMode != other.d->m_fileMode ); -} - - -QString Nepomuk::Query::Query::toSparqlQuery( SparqlFlags sparqlFlags ) const -{ - Term term = d->m_term; - - // restrict to files if we are a file query - if( d->m_isFileQuery ) { - Term fileModeTerm; - ResourceTypeTerm fileTerm( Vocabulary::NFO::FileDataObject() ); - ResourceTypeTerm folderTerm( Vocabulary::NFO::Folder() ); - if( d->m_fileMode == FileQuery::QueryFiles ) - fileModeTerm = AndTerm( fileTerm, NegationTerm::negateTerm( folderTerm ) ); - else if( d->m_fileMode == FileQuery::QueryFolders ) - fileModeTerm = AndTerm( folderTerm, NegationTerm::negateTerm( fileTerm ) ); - else - fileModeTerm = OrTerm( fileTerm, folderTerm ); - term = AndTerm( term, fileModeTerm, d->createFolderFilter() ); - } - - - // convert request properties into ComparisonTerms - // in ask and count query mode we can omit the optional req props - for ( int i = 0; i < d->m_requestProperties.count(); ++i ) { - const RequestProperty& rp = d->m_requestProperties[i]; - ComparisonTerm rpt( rp.property(), Term() ); - rpt.setVariableName( QString::fromLatin1("reqProp%1").arg(i+1) ); - if( rp.optional() && !( sparqlFlags&(CreateAskQuery|CreateCountQuery) ) ) { - term = term && OptionalTerm::optionalizeTerm( rpt ); - } - else if( !rp.optional() ) { - term = term && rpt; - } - } - - - // optimize whatever we can - term = term.optimized(); - - // perform internal optimizations - term = d->optimizeEvenMore(term); - - // actually build the SPARQL query patterns - QueryBuilderData qbd( d.constData(), sparqlFlags ); - - - // - // We restrict results to user visible types only. There is no need for this with file queries as normally all files are visible. - // - QString userVisibilityRestriction; - if( !(queryFlags()&NoResultRestrictions) && !d->m_isFileQuery ) { - userVisibilityRestriction = QString::fromLatin1("FILTER EXISTS { ?r a [ %1 %2 ] . } . ") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::userVisible()), - Soprano::Node::literalToN3(Soprano::LiteralValue(true))); - } - - - QString termGraphPattern; - if( term.isValid() ) { - termGraphPattern = term.d_ptr->toSparqlGraphPattern( QLatin1String( "?r" ), 0, userVisibilityRestriction, &qbd ); - if( termGraphPattern.isEmpty() ) { - kDebug() << "Got no valid SPARQL pattern from" << term; - return QString(); - } - } - - // build the list of variables to select (in addition to the main result variable ?r) - QStringList selectVariables = qbd.customVariables(); - - // add additional scoring variable if requested - if( d->m_fullTextScoringEnabled ) { - const QString scoringExpression = qbd.buildScoringExpression(); - if( !scoringExpression.isEmpty() ) - selectVariables << scoringExpression; - } - - // build the core of the query - the part that never changes - QString queryBase = QString::fromLatin1( "where { %1 }" ) - .arg( termGraphPattern ); - - // build the final query - QString query; - if( sparqlFlags & CreateCountQuery ) { - if( selectVariables.isEmpty() ) { - // when there are no additional variables we can perfectly use count(distinct) - query = QString::fromLatin1("select count(distinct ?r) as ?cnt %1 %2") - .arg( selectVariables.join( QLatin1String(" " ) ), - queryBase ); - } - else { - // when there are additional variables we need to do some magic to count the - // number of rows instead of a list of counts - // we cannot simply leave out the additional variables since that would change - // the number of results. - query = QString::fromLatin1("select count(%1) as ?cnt %2 where { { select count(*) as %1 ?r %3 } }") - .arg(qbd.uniqueVarName(), - selectVariables.join( QLatin1String(" " ) ), - queryBase ); - } - } - else if( sparqlFlags & CreateAskQuery ) { - query = QLatin1String( "ask ") + queryBase; - } - else { - QString fullTextExcerptExpression; - if( !(queryFlags()&WithoutFullTextExcerpt) ) { - fullTextExcerptExpression = qbd.buildSearchExcerptExpression(); - } - query = QString::fromLatin1( "select distinct ?r %1 %2 %3" ) - .arg( selectVariables.join( QLatin1String(" " ) ), - fullTextExcerptExpression, - queryBase ); - query += qbd.buildOrderString(); - } - - // offset and limit - if ( d->m_offset > 0 ) - query += QString::fromLatin1( " OFFSET %1" ).arg( d->m_offset ); - if ( d->m_limit > 0 ) - query += QString::fromLatin1( " LIMIT %1" ).arg( d->m_limit ); - - return query.simplified(); -} - - -KUrl Nepomuk::Query::Query::toSearchUrl( SparqlFlags flags ) const -{ - return toSearchUrl( QString(), flags ); -} - - -// This is a bit dodgy: if there are sparql flags we encode the SPARQL query into the url -// otherwise the serialized query (which allows for more power in the kio slave). It would -// probably be nicer to somehow put the flags in the URL. But new query items in the URL -// would make the URL handling in the kio slave more complicated.... oh, well. -KUrl Nepomuk::Query::Query::toSearchUrl( const QString& customTitle, SparqlFlags flags ) const -{ - // the nepomuksearch:/ KIO slave does not handle count or ask queries - flags &= ~CreateCountQuery; - flags &= ~CreateAskQuery; - - Query q( *this ); - - // the nepomuksearch:/ KIO slave does not make use of full text scores. Thus, we avoid the - // overhead by disabling them - q.setFullTextScoringEnabled( false ); - - KUrl url( QLatin1String("nepomuksearch:/") ); - if( flags == NoFlags ) - url.addQueryItem( QLatin1String("encodedquery"), q.toString() ); - else - url.addQueryItem( QLatin1String("sparql"), q.toSparqlQuery( flags ) ); - - QString title(customTitle); - if( customTitle.isEmpty() ) { - title = titleFromQueryUrl( url ); - } - - // replace slashes with the "fraction slash" which is the same KIO::encodeFileName does. - // however, we do not want to link to KIO. - url.addPath( title.replace('/', QChar(0x2044)) ); - - return url; -} - - -Nepomuk::Query::RequestPropertyMap Nepomuk::Query::Query::requestPropertyMap() const -{ - RequestPropertyMap rpm; - for ( int i = 0; i < d->m_requestProperties.count(); ++i ) { - rpm.insert( QString( "reqProp%1" ).arg( i+1 ), d->m_requestProperties[i].property() ); - } - return rpm; -} - - -QString Nepomuk::Query::Query::toString() const -{ - return Nepomuk::Query::serializeQuery( *this ); -} - - -Nepomuk::Query::Query Nepomuk::Query::Query::optimized() const -{ - Query newQuery( *this ); - newQuery.setTerm( term().optimized() ); - return newQuery; -} - - -// static -Nepomuk::Query::Query Nepomuk::Query::Query::fromString( const QString& queryString ) -{ - return Nepomuk::Query::parseQuery( queryString ); -} - - -namespace { - /** - * Returns an empty string for sparql query URLs. - */ - inline QString extractPlainQuery( const KUrl& url ) { - if( url.queryItems().contains( "query" ) ) { - return url.queryItem( "query" ); - } - else if ( !url.hasQuery() ) { - return url.path().section( '/', 0, 0, QString::SectionSkipEmpty ); - } - else { - return QString(); - } - } -} - -// static -Nepomuk::Query::Query Nepomuk::Query::Query::fromQueryUrl( const KUrl& url ) -{ - if( url.protocol() != QLatin1String("nepomuksearch") ) { - kDebug() << "No nepomuksearch:/ URL:" << url; - return Query(); - } - - if ( url.queryItems().contains( "sparql" ) ) { - kDebug() << "Cannot parse SPARQL query from:" << url; - return Query(); - } - else if( url.queryItems().contains( "encodedquery" ) ) { - return fromString( url.queryItem( "encodedquery") ); - } - else { - Query query = QueryParser::parseQuery( extractPlainQuery(url) ); - query.setRequestProperties( QList() << Nepomuk::Query::Query::RequestProperty( Nepomuk::Vocabulary::NIE::url(), true ) ); - return query; - } -} - - -// static -QString Nepomuk::Query::Query::sparqlFromQueryUrl( const KUrl& url ) -{ - if( url.protocol() != QLatin1String("nepomuksearch") ) { - kDebug() << "No nepomuksearch:/ URL:" << url; - return QString(); - } - - if( url.queryItems().contains( "sparql" ) ) { - return url.queryItem( "sparql" ); - } - else { - Query query = fromQueryUrl( url ); - if( query.isValid() ) { - query.setRequestProperties( QList() << Nepomuk::Query::Query::RequestProperty( Nepomuk::Vocabulary::NIE::url(), true ) ); - return query.toSparqlQuery(); - } - else { - return QString(); - } - } -} - - -// static -QString Nepomuk::Query::Query::titleFromQueryUrl( const KUrl& url ) -{ - if( url.protocol() != QLatin1String("nepomuksearch") ) { - kDebug() << "No nepomuksearch:/ URL:" << url; - return QString(); - } - - // the title is the first section of the path, but only if we have a query - if( url.hasQuery() ) { - QString title = url.path().section( '/', 0, 0, QString::SectionSkipEmpty ); - if(!title.isEmpty()) - return title; - } - - // no title in the path, try to get the user query, i.e. a non-encoded and non-sparql query - QString userQuery = extractPlainQuery( url ); - if ( !userQuery.isEmpty() ) { - return i18nc( "@title UDS_DISPLAY_NAME for a KIO directory listing. %1 is the query the user entered.", - "Query Results from '%1'", - userQuery ); - } - - // fallback: generic query title - return i18nc( "@title UDS_DISPLAY_NAME for a KIO directory listing.", - "Query Results"); -} - - -Nepomuk::Query::Query Nepomuk::Query::operator&&( const Query& query, const Term& term ) -{ - Query newQuery( query ); - newQuery.setTerm( query.term() && term ); - return newQuery; -} - - -Nepomuk::Query::Query Nepomuk::Query::operator||( const Query& query, const Term& term ) -{ - Query newQuery( query ); - newQuery.setTerm( query.term() || term ); - return newQuery; -} - - -Nepomuk::Query::Query Nepomuk::Query::operator!( const Query& query ) -{ - Query newQuery( query ); - newQuery.setTerm( !query.term() ); - return newQuery; -} - - -QDebug operator<<( QDebug dbg, const Nepomuk::Query::Query& query ) -{ - return dbg << query.toString(); -} - - -uint Nepomuk::Query::qHash( const Nepomuk::Query::Query& query ) -{ - return qHash( query.term() ); -} diff --git a/nepomuk/query/query.h b/nepomuk/query/query.h deleted file mode 100644 index 2c375209..00000000 --- a/nepomuk/query/query.h +++ /dev/null @@ -1,608 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_QUERY_QUERY_H_ -#define _NEPOMUK_QUERY_QUERY_H_ - -#include -#include -#include -#include - -#include - -#include "property.h" - -#include "nepomukquery_export.h" - -class QTextStream; - -namespace Nepomuk { - namespace Query { - - class Term; - class QueryPrivate; - class FileQuery; - - /** - * \brief Convinience definition for request property mappings as used in - * QueryServiceClient::sparqlQuery() and QueryServiceClient::blockingSparqlQuery(). - */ - typedef QHash RequestPropertyMap; - - /** - * \class Query query.h Nepomuk/Query/Query - * - * \brief A Nepomuk desktop query. - * - * A Query consists or a combination of Terms that can be optionally - * restricted via a limit (setLimit()) or folder filters (setIncludeFolders() and - * setExcludeFolders()). - * - * Additionally setRequestProperties() allows to retrieve additional information - * about the results. - * - * Queries can be easily converted to SPARQL via the toSparqlQuery() method or to - * search URLs ready for KIO::DirLister using toSearchUrl(). - * - * The typical usage of a Query instance would be QueryServiceClient::query(). - * However one can also use toSparqlQuery() to convert it into a SPARQL query - * string and use that string in QueryServiceClient::sparqlQuery() or even - * directly in Soprano::Model::executeQuery() via \p ResourceManager::instance()->mainModel() - * or in a custom Model. - * - * \sa QueryParser, FileQuery - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT Query - { - public: - /** - * Create an empty invalid query object. - */ - Query(); - - /** - * Create a query with root term \a term. - */ - explicit Query( const Term& term ); - - /** - * Copy constructor. - */ - Query( const Query& ); - - /** - * Destructor - */ - ~Query(); - - /** - * Assignment operator - */ - Query& operator=( const Query& ); - - /** - * Assignment operator. Assigns \p term to - * this query without changing any other - * properties. - * - * \since 4.5 - */ - Query& operator=( const Term& term ); - - /** - * \return \p true if the query is valid, i.e. - * it has a valid term(). - */ - bool isValid() const; - - /** - * \return \p true if this is a file query that will - * only return files and folders. - * - * \sa FileQuery - * - * \since 4.5 - */ - bool isFileQuery() const; - - /** - * \return A copy of this query which is restricted to files. - * - * \since 4.6 - */ - FileQuery toFileQuery() const; - - /** - * The root term of the query. - * This can be any type of term. - * - * \sa setTerm() - */ - Term term() const; - - /** - * The maximum number of results that this query should yield. - * - * \sa setLimit() - */ - int limit() const; - - /** - * The first result that should be retrieved. - * - * \sa setOffset() - * - * \since 4.5 - */ - int offset() const; - - /** - * Set the root term of the query. - * - * \sa term - */ - void setTerm( const Term& ); - - /** - * Set the maximum number of results this query - * should yield. - * - * \sa limit - */ - void setLimit( int ); - - /** - * The first result that should be retrieved. This can be combined - * with setLimit() to do paged results. - * - * \since 4.5 - */ - void setOffset( int offset ); - - /** - * %Nepomuk supports scoring the results based on any full text matching - * used in the query (full text matching is done via ComparisonTerm with - * the ComparisonTerm::Contains comperator) and sorting the results based - * on that score. - * - * By default full text scoring is disabled since it can mean a serious - * impact on query performance. - * - * \sa setFullTextScoringSortOrder(), Result::score() - * - * \since 4.6 - */ - void setFullTextScoringEnabled( bool enabled ); - - /** - * Set the full text scoring sort order. Ignored if full text scoring is - * disabled. - * - * By default the sort order is Qt::DescendingOrder. - * - * \sa setFullTextScoringEnabled() - * - * \since 4.6 - */ - void setFullTextScoringSortOrder( Qt::SortOrder order ); - - /** - * \return \p true if full text scoring has been enabled. - * - * \sa setFullTextScoringEnabled() - * - * \since 4.6 - */ - bool fullTextScoringEnabled() const; - - /** - * \return The full text scoring sort order as set via setFullTextScoringSortOrder() - * - * \since 4.6 - */ - Qt::SortOrder fullTextScoringSortOrder() const; - - /** - * A set of flags that influence the result of the query. - * - * \sa setQueryFlags(), SparqlFlags - * - * \since 4.6 - */ - enum QueryFlag { - /** - * No flags set. This is the default. - */ - NoQueryFlags = 0x0, - - /** - * By default queries that will only return results which are intended for - * the user's eyes. In situations where an application needs to work on - * internal or statistical data this restriction is not desireable. - * This flag disables the restriction and returns the full set of results. - */ - NoResultRestrictions = 0x1, - - /** - * Disables the return of full text search excerpts for ComparisonTerm::Contains - * terms which are normally reported through Result::excerpt(). It might make sense - * to set this flag in case one has no need for excerpts and does not want to suffer - * the small performance penalty that comes from querying them - */ - WithoutFullTextExcerpt = 0x2 - }; - Q_DECLARE_FLAGS( QueryFlags, QueryFlag ) - - /** - * Set the query flags to configure this query. - * - * \sa queryFlags() - * - * \since 4.6 - */ - void setQueryFlags( QueryFlags flags ); - - /** - * Get the query flags to configure this query. - * - * \sa setQueryFlags() - * - * \since 4.6 - */ - QueryFlags queryFlags() const; - - /** - * \class RequestProperty query.h Nepomuk/Query/Query - * - * \brief A request property can be added to a Query to retrieve - * additional information about the results. - * - * Normally a query would simply yield a list of resources, - * ie. URIs. Using RequestProperty one can request additional - * fields such as the modification time or the label or whatever - * is of interest in the current context. - * - * \sa addRequestProperty, setRequestProperties - */ - class NEPOMUKQUERY_EXPORT RequestProperty { - public: - /** - * Create a new request property. - * \param property The requested %property. - * \param optional if \p true the requested property will - * be %optional, ie. marked as OPTIONAL in SPARQL queries. - */ - RequestProperty( const Nepomuk::Types::Property& property, - bool optional = true ); - - /** - * Copy constructor. - */ - RequestProperty( const RequestProperty& ); - - /** - * Destructor. - */ - ~RequestProperty(); - - /** - * Copy operator. - */ - RequestProperty& operator=( const RequestProperty& ); - - /** - * Comparison operator. Two RequestProperty instances - * are equal if their property() and value of optional() - * are equal. - */ - bool operator==( const RequestProperty& other ) const; - - /** - * \return The property set in the constructor. - */ - Nepomuk::Types::Property property() const; - - /** - * \return The optional value set in the constructor. - */ - bool optional() const; - - private: - class Private; - QSharedDataPointer d; - }; - - /** - * Add a property that should be reported with each search result. - * - * \param property The requested property. - * - * ComparisonTerm::setVariableName() provides a more flexible (but also - * slightly more complicated) way to select additional results. - * - * \sa setRequestProperties, requestProperties, ComparisonTerm::setVariableName() - */ - void addRequestProperty( const RequestProperty& property ); - - /** - * Set the properties that should be reported with each search result. - * - * \param properties The requested properties. - * - * ComparisonTerm::setVariableName() provides a more flexible (but also - * slightly more complicated) way to select additional results. - * - * \sa addRequestProperty, requestProperties, ComparisonTerm::setVariableName() - */ - void setRequestProperties( const QList& properties ); - - /** - * \return The list of RequestProperty instances set via addRequestProperty - * and setRequestProperties. - */ - QList requestProperties() const; - - /** - * \brief Aditional flags modifying the behaviour of toSparqlQuery() and toSearchUrl(). - */ - enum SparqlFlag { - /** - * No flags, i.e. create a default query. - */ - NoFlags = 0x0, - - /** - * Create a SPARQL count query which will return the number - * of results rather than the results themselves. The resuling query will have - * a single binding called \p 'cnt'. - */ - CreateCountQuery = 0x1, - - /** - * Automatically handle inverse properties, consider for example nie:isPartOf - * and nie:hasPart at the same time and even if only one of both is - * defined. - */ - HandleInverseProperties = 0x2, - - /** - * Create a SPARQL ask query which will simply check if a matching result exists. - * Use Soprano::QueryResultIterator::boolValue() to check the result. - * - * \since 4.6 - */ - CreateAskQuery = 0x4 - }; - Q_DECLARE_FLAGS( SparqlFlags, SparqlFlag ) - - /** - * Convert the query into a SPARQL query which can be used with the - * Nepomuk query service or directly in Soprano::Model::executeQuery. - * - * It is recommended to use QueryServiceClient instead of creating - * the SPARQL query this way. - * - * The resulting query will bind the results to variable \p 'r'. Request - * properties will be bound to variables \p 'reqProp1' through \p 'reqPropN' - * (the only exception is a count query created via the CreateCountQuery flag). - * - * If you are looking for a serialization of a Query which can be parsed again - * use toString() instead. - * - * \warning The SPARQL queries created by this method contain SPARQL extensions - * from Virtuoso and will not work with other RDF storage solutions! - * - * \param flags Optional flags to change the query. - * - * \return The SPARQL representation of this query or an empty string - * if the query could not be converted (invalid query.) - * - * \sa toString(), toSearchUrl(), SparqlFlag - */ - QString toSparqlQuery( SparqlFlags flags = NoFlags ) const; - - /** - * Convert the query into a URL which can be listed using KIO::DirLister. - * The URL will use the \p nepomuksearch:/ KIO protocol to handle the listing - * of search results. - * - * \param flags Optional flags to change the query. Query::CreateCountQuery is not - * supported and will silently be dropped from \p flags. - * - * \return A URL which will list a virtual folder containing all search results - * from this query or an invalid URL in case this query is invalid. - * - * \sa toSparqlQuery(), SparqlFlag - */ - KUrl toSearchUrl( SparqlFlags flags = NoFlags ) const; - - /** - * Convert the query into a URL which can be listed using KIO::DirLister. - * The URL will use the \p nepomuksearch:/ KIO protocol to handle the listing - * of search results. - * - * This is the perfect method for listing results in file managers or file - * dialogs. - * - * \param customTitle An optional custom title that will be used for the listing - * of the results. This is achieved by setting the KIO::UDSEntry::UDS_DISPLAY_NAME to - * the customTitle value. - * \param flags Optional flags to change the query. Query::CreateCountQuery is not - * supported and will silently be dropped from \p flags. - * - * \return A URL which will list a virtual folder containing all search results - * from this query or an invalid URL in case this query is invalid. - * - * \sa toSparqlQuery(), SparqlFlag - * - * \since 4.5 - */ - KUrl toSearchUrl( const QString& customTitle, SparqlFlags flags = NoFlags ) const; - - /** - * Build a request property map as used in QueryServiceClient::sparqlQuery() - * from the request properties set via addRequestProperty() and setRequestProperties(). - * - * Be aware that in most situations it is much simpler to use QueryServiceClient::query(). - */ - RequestPropertyMap requestPropertyMap() const; - - /** - * Comparison operator. - * - * \return \p true if this query is equal to \p query. - */ - bool operator==( const Query& query ) const; - - /** - * Comparison operator. - * - * \return \p true if this query differs from \p query. - * - * \since 4.6 - */ - bool operator!=( const Query& query ) const; - - /** - * Optimizes the query without chaning its meaning. This removes - * redundant terms such as NegationTerm and OptionalTerm nestings and flattens - * AndTerm and OrTerm hierarchies. - * - * \return An optimized version of this query. - * - * \since 4.6 - * - * \sa Term::optimized() - */ - Query optimized() const; - - /** - * Encode the Query in a string. Be aware that this does NOT create a SPARQL - * query. The returned string can be used to serialize queries that can later - * be read via fromString(). - * - * \sa fromString(), toSparqlQuery() - * - * \since 4.5 - */ - QString toString() const; - - /** - * Parse a Query that has been encoded as a string via toString(). - * - * \warning This method can NOT parse SPARQL syntax. - * - * \sa toString() - * - * \since 4.5 - */ - static Query fromString( const QString& queryString ); - - /** - * Extract a query from a nepomuksearch:/ query URL. - * - * \return The query that was encoded in \p url or an invalid query if - * either \p url is not a nepomuksearch:/ URL or if it contains a pure SPARQL - * query. In the latter case sparqlFromQueryUrl() can be used to extract that - * query. - * - * \sa sparqlFromQueryUrl() - * - * \since 4.5 - */ - static Query fromQueryUrl( const KUrl& url ); - - /** - * Extract the SPARQL query from a nepomuksearch:/ query URL. All kinds of - * nepomuksearch:/ URLs are supported. - * - * \return The SPARQL query string representing the query encoded - * in \p url. - * - * \sa fromQueryUrl() - * - * \since 4.5 - */ - static QString sparqlFromQueryUrl( const KUrl& url ); - - /** - * Extact the title from a nepomuksearch:/ query URL. The title - * is either a custom title which has been specified in - * toSearchUrl(const QString&, SparqlFlags) or the user query string - * in case of nepomuksearch:/myquery URLs. - * - * \return A title for the query \p url or an empty string - * in case \p url is not a nepomuksearch:/ URL or a useful title - * cannot be extracted. - * - * \since 4.5 - */ - static QString titleFromQueryUrl( const KUrl& url ); - - protected: - /** \cond protected_query_members */ - QSharedDataPointer d; - /** \endcond */ - }; - - /** - * Logical and operator which combines \p term into the term - * of \p query to match both. - * - * \sa AndTerm - * - * \since 4.6 - */ - NEPOMUKQUERY_EXPORT Query operator&&( const Query& query, const Term& term ); - - /** - * Logical or operator which combines \p term into the term - * of \p query to match either one. - * - * \sa OrTerm - * - * \since 4.6 - */ - NEPOMUKQUERY_EXPORT Query operator||( const Query& query, const Term& term ); - - /** - * Logical negation operator which negates the meaning of - * a query. - * - * \sa NegationTerm::negateTerm() - * - * \since 4.6 - */ - NEPOMUKQUERY_EXPORT Query operator!( const Query& query ); - - NEPOMUKQUERY_EXPORT uint qHash( const Nepomuk::Query::Query& ); - } -} - -Q_DECLARE_OPERATORS_FOR_FLAGS( Nepomuk::Query::Query::SparqlFlags ) -Q_DECLARE_OPERATORS_FOR_FLAGS( Nepomuk::Query::Query::QueryFlags ) - -NEPOMUKQUERY_EXPORT QDebug operator<<( QDebug, const Nepomuk::Query::Query& ); - -#endif diff --git a/nepomuk/query/query_p.h b/nepomuk/query/query_p.h deleted file mode 100644 index 03a287e5..00000000 --- a/nepomuk/query/query_p.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_SEARCH_QUERY_P_H_ -#define _NEPOMUK_SEARCH_QUERY_P_H_ - -#include -#include - -#include - -#include "term.h" -#include "query.h" -#include "filequery.h" - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - - class QueryBuilderData; - - class QueryPrivate : public QSharedData - { - public: - QueryPrivate() - : m_limit( 0 ), - m_offset( 0 ), - m_fullTextScoringEnabled( false ), - m_fullTextScoringSortOrder( Qt::DescendingOrder ), - m_isFileQuery( false ), - m_fileMode( FileQuery::QueryFilesAndFolders ) { - } - - Term createFolderFilter() const; - - /** - * Optimizations that cannot be done in Term::optimized() since they use internal - * features of some of the term types. - * We might expose some of them in the next major KDE release. - */ - Nepomuk::Query::Term optimizeEvenMore(const Nepomuk::Query::Term& term) const; - - QStringList buildRequestPropertyVariableList() const; - QString buildRequestPropertyPatterns() const; - - Term m_term; - int m_limit; - int m_offset; - - bool m_fullTextScoringEnabled; - Qt::SortOrder m_fullTextScoringSortOrder; - Query::QueryFlags m_flags; - - QList m_requestProperties; - - bool m_isFileQuery; - QHash m_includeFolders; - KUrl::List m_excludeFolders; - FileQuery::FileMode m_fileMode; - }; - } -} - -#endif diff --git a/nepomuk/query/querybuilderdata_p.h b/nepomuk/query/querybuilderdata_p.h deleted file mode 100644 index 3880e13e..00000000 --- a/nepomuk/query/querybuilderdata_p.h +++ /dev/null @@ -1,297 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_QUERY_BUILDER_DATA_H_ -#define _NEPOMUK_QUERY_QUERY_BUILDER_DATA_H_ - -#include -#include -#include -#include - -#include "literal.h" -#include "query.h" -#include "query_p.h" -#include "groupterm_p.h" - -namespace { -/// A hack to avoid passing extended chars to the bif:search_excerpts method which cannot handle -/// utf8 chars which use more than one char, ie. wide chars. -/// Thus, we simply truncate each term at the first wide char. -QStringList stripExtendedCharsHack(const QStringList& terms) { - QStringList newTerms; - foreach(const QString& term, terms) { - int i = 0; - while(i < term.length()) { - if(term[i].unicode() > 0x7f) { - break; - } - ++i; - } - if(i > 0) { - newTerms.append(term.left(i)); - } - } - return newTerms; -} -} - -namespace Nepomuk { - namespace Query { - class QueryBuilderData - { - private: - /// the query we are working for - const QueryPrivate* m_query; - - struct OrderVariable { - OrderVariable(int w, const QString& n, Qt::SortOrder o) - : weight(w), - name(n), - sortOrder(o) { - } - int weight; - QString name; - Qt::SortOrder sortOrder; - }; - - /// see uniqueVarName() - struct GroupTermPropertyCache { - const GroupTermPrivate* term; - QHash variableNameHash; - }; - - /// a running counter for unique variable names - int m_varNameCnt; - - /// copy of the flags as set in Query::toSparqlQuery - const Query::SparqlFlags m_flags; - - /// custom variables that have been added via ComparisonTerm::setVariableName - QSet m_customVariables; - - /// variables that are used for sorting set via ComparisonTerm::setSortWeight - QList m_orderVariables; - - /// all full-text matching scoring variables - QHash m_scoreVariables; - - /// The depth of a term in the query. This is only changed by ComparisonTerm - int m_depth; - - /// a stack of the group terms, the top item is the group the currently handled term is in - QStack m_groupTermStack; - - /// full text search terms with depth 0 for which bif:search_excerpt will be used - QHash m_fullTextSearchTerms; - - public: - inline QueryBuilderData( const QueryPrivate* query, Query::SparqlFlags flags ) - : m_query( query ), - m_varNameCnt( 0 ), - m_flags( flags ), - m_depth( 0 ) { - } - - inline const QueryPrivate* query() const { - return m_query; - } - - inline Query::SparqlFlags flags() const { - return m_flags; - } - - inline int depth() const { - return m_depth; - } - - inline void increaseDepth() { - ++m_depth; - } - - inline void decreaseDepth() { - --m_depth; - } - - /// used by ComparisonTerm to register var names set via ComparisonTerm::setVariableName - /// to allow them to be reused in the same way auto-generated variables are reused in - /// uniqueVarName() - inline void registerVarName( const Types::Property& property, const QString& varName ) { - if( property.isValid() && - property.maxCardinality() == 1 && - !m_groupTermStack.isEmpty() ) { - GroupTermPropertyCache& gpc = m_groupTermStack.top(); - gpc.variableNameHash[property] = varName; - } - } - - /// used by different implementations of TermPrivate::toSparqlGraphPattern and Query::toSparqlQuery - /// - /// we use a simple query optimization trick here that Virtuoso cannot pull itself since it does - /// not know about NRL cardinalities: - /// In one group term we can use the same variable name for comparisons on the same property with a - /// cardinality of 1. This reduces the number of match candidates for Virtuoso, thus, significantly - /// speeding up the query. - inline QString uniqueVarName( const Types::Property& property = Types::Property(), bool* firstUse = 0 ) { - if( property.isValid() && - property.maxCardinality() == 1 && - !m_groupTermStack.isEmpty() ) { - // use only one variable name for all occurrences of this property - GroupTermPropertyCache& gpc = m_groupTermStack.top(); - QHash::const_iterator it = gpc.variableNameHash.constFind( property ); - if( it == gpc.variableNameHash.constEnd() ) { - const QString v = QLatin1String( "?v" ) + QString::number( ++m_varNameCnt ); - gpc.variableNameHash.insert( property, v ); - if(firstUse) - *firstUse = true; - return v; - } - else { - if(firstUse) - *firstUse = false; - return *it; - } - } - else { - if(firstUse) - *firstUse = true; - return QLatin1String( "?v" ) + QString::number( ++m_varNameCnt ); - } - } - - /// used by ComparisonTerm to add variable names set via ComparisonTerm::setVariableName - inline void addCustomVariable( const QString& name ) { - m_customVariables << name; - } - - /// used by Query::toSparqlQuery - inline QStringList customVariables() const { - return m_customVariables.toList(); - } - - /// used by ComparisonTerm to add sorting variables (names include the '?') - inline void addOrderVariable( const QString& name, int weight, Qt::SortOrder order ) { - int i = 0; - while( i < m_orderVariables.count() && - m_orderVariables[i].weight > weight ) - ++i; - m_orderVariables.insert( i, OrderVariable( weight, name, order ) ); - } - - /// used by LiteralTerm and ComparisonTerm - /// states that "varName" is a value matching the given full text search terms - inline void addFullTextSearchTerms( const QString& varName, const QStringList& terms ) { - m_fullTextSearchTerms.insert( varName, terms ); - } - - /// used by AndTermPrivate and OrTermPrivate in toSparqlGraphPattern - inline void pushGroupTerm( const GroupTermPrivate* group ) { - GroupTermPropertyCache gpc; - gpc.term = group; - m_groupTermStack.push( gpc ); - } - - /// used by AndTermPrivate and OrTermPrivate in toSparqlGraphPattern - inline void popGroupTerm() { - m_groupTermStack.pop(); - } - - /// used by Query::toSparqlQuery - inline QString buildOrderString() const { - QList orderVars = m_orderVariables; - if( m_query->m_fullTextScoringEnabled && - !m_fullTextSearchTerms.isEmpty() ) { - orderVars.append( OrderVariable( 0, QLatin1String("?_n_f_t_m_s_"), m_query->m_fullTextScoringSortOrder ) ); - } - - if( !orderVars.isEmpty() ) { - QStringList s; - Q_FOREACH( const OrderVariable& orderVar, orderVars ) { - if( orderVar.sortOrder == Qt::DescendingOrder ) - s += QLatin1String("DESC "); - else - s += QLatin1String("ASC "); - s += QString::fromLatin1("( %1 )").arg(orderVar.name); - } - return QLatin1String(" ORDER BY ") + s.join( QLatin1String(" ") ); - } - else { - return QString(); - } - } - - /// create and remember a scoring variable for full text matching - inline QString createScoringVariable() { - QString v = uniqueVarName(); - m_scoreVariables.insert(v, m_depth); - return v; - } - - inline QString buildScoringExpression() const { - QStringList scores; - for( QHash::const_iterator it = m_scoreVariables.constBegin(); - it != m_scoreVariables.constEnd(); ++it ) { - const QString var = it.key(); - int depth = it.value(); - if( depth > 0 ) - scores += QString::fromLatin1("(%1/%2)").arg(var).arg(depth+1); - else - scores += var; - } - if( !scores.isEmpty() ) - return QLatin1String("max(") + scores.join(QLatin1String("+")) + QLatin1String(") as ?_n_f_t_m_s_"); - else - return QString(); - } - - inline QString buildSearchExcerptExpression() const { - if( !m_fullTextSearchTerms.isEmpty() ) { - QStringList excerptParts; - for( QHash::const_iterator it = m_fullTextSearchTerms.constBegin(); - it != m_fullTextSearchTerms.constEnd(); ++it ) { - const QString& varName = it.key(); - const QStringList terms = stripExtendedCharsHack(it.value()); - if(terms.count()) { - // bif:search_excerpt wants a vector of all search terms - excerptParts - << QString::fromLatin1("bif:search_excerpt(bif:vector('%1'), %2)") - .arg( terms.join(QLatin1String("','")), - varName ); - } - } - - if(excerptParts.count()) { - return QString::fromLatin1("(bif:concat(%1)) as ?_n_f_t_m_ex_") - .arg(excerptParts.join(QLatin1String(","))); - } - else { - return QString(); - } - } - else { - return QString(); - } - } - }; - } -} - -#endif diff --git a/nepomuk/query/queryparser.cpp b/nepomuk/query/queryparser.cpp deleted file mode 100644 index a343794e..00000000 --- a/nepomuk/query/queryparser.cpp +++ /dev/null @@ -1,815 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2007-2011 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#include "queryparser.h" -#include "query.h" -#include "query_p.h" -#include "literalterm.h" -#include "resourceterm.h" -#include "andterm.h" -#include "orterm.h" -#include "negationterm.h" -#include "comparisonterm.h" -#include "dateparser_p.h" -#include "nfo.h" - -#include -#include -#include -#include - -#include -#include - -#include "resourcemanager.h" -#include "property.h" -#include "literal.h" - -#include -#include -#include -#include -#include - - -using namespace Nepomuk::Query; - -namespace { - Nepomuk::Query::ComparisonTerm::Comparator fieldTypeRelationFromString( const QString& s ) { - if ( s == "=" ) { - return Nepomuk::Query::ComparisonTerm::Equal; - } - else if ( s == ":" ) { - return Nepomuk::Query::ComparisonTerm::Contains; - } - else if ( s == ">" ) { - return Nepomuk::Query::ComparisonTerm::Greater; - } - else if ( s == "<" ) { - return Nepomuk::Query::ComparisonTerm::Smaller; - } - else if ( s == ">=" ) { - return Nepomuk::Query::ComparisonTerm::GreaterOrEqual; - } - else if ( s == "<=" ) { - return Nepomuk::Query::ComparisonTerm::SmallerOrEqual; - } - else { - kDebug() << "FIXME: Unsupported relation:" << s; - return Nepomuk::Query::ComparisonTerm::Equal; - } - } - - QString stripQuotes( const QString& s, bool* hadQuotes = 0 ) { - if ( s[0] == '\'' || - s[0] == '\"' ) { - if( hadQuotes ) - *hadQuotes = true; - return s.mid( 1 ).left( s.length()-2 ); - } - else { - if( hadQuotes ) - *hadQuotes = false; - return s; - } - } - - QUrl tryToBeIntelligentAboutParsingUrl( const QString& s ) { - if ( s.contains( '%' ) && !s.contains( '/' ) ) { - return QUrl::fromEncoded( s.toLatin1() ); - } - else { - return QUrl( s ); - } - } - - Soprano::LiteralValue createLiteral( const QString& s, bool globbing ) { - // 1. check if it is a number - QString clearString(s); - clearString.remove(QLatin1Char('\'')); - clearString.remove(QLatin1Char('"')); - bool b = false; - int i = clearString.toInt( &b ); - if ( b ) - return Soprano::LiteralValue( i ); - double d = clearString.toDouble( &b ); - if ( b ) - return Soprano::LiteralValue( d ); - - // 2. no number - continue with the original string - - // no globbing if we have quotes or if there already is a wildcard - if ( s[0] == QLatin1Char('\'') || - s[0] == QLatin1Char('\"') ) { - return s; - } - - // - // we can only do query term globbing for strings longer than 3 chars - // - if( globbing && s.length() > 3 && !s.endsWith('*') && !s.endsWith('?') ) - return QString(s + '*'); - else - return s; - } - - bool positiveTerm( const QString& s_ ) { - const QString s = s_.toLower().simplified(); - if(s.isEmpty()) - return true; - else if(s == "+") - return true; - else if(s == "-") - return false; - else if(s == "!") - return false; - else if(s == "not") - return false; - else //unrecognized capture - return true; - } - - // A filename pattern needs to contain one dot and at least one '*' or '?': - // *.mp3 - // hello?.txt - // hello?.* - // test*.??? - bool isFilenamePattern( const QString& s ) - { - return( !s.contains(' ') && - s.count('.') == 1 && - s.count('*') + s.count('?') > 0 ); - } - - Nepomuk::Query::ComparisonTerm createFilenamePatternTerm( const QString& s ) - { - QString regex = QRegExp::escape(s); - regex.replace( "\\*", QLatin1String( ".*" ) ); - regex.replace( "\\?", QLatin1String( "." ) ); - regex.replace("\\", "\\\\"); - regex.prepend('^'); - regex.append('$'); - return Nepomuk::Query::ComparisonTerm( Nepomuk::Vocabulary::NFO::fileName(), - Nepomuk::Query::LiteralTerm( regex ), - Nepomuk::Query::ComparisonTerm::Regexp ); - } - - /** - * Merging literal terms is an optimization which is based on the assumption that most - * users want to search for the full text terms they enter in the value of the same - * property. - * Since merging two literals "foo" and "bar" into one term "foo AND bar" effectively - * changes the result set (the former allows that "foo" occurs in a property value - * different from "bar" while the latter forces them to occur in the same.) - * But the resulting query is much faster. - */ - Nepomuk::Query::Term mergeLiteralTerms( const Nepomuk::Query::Term& term ) - { - if( term.isAndTerm() ) { - AndTerm mergedTerm; - QStringList fullTextTerms; - Q_FOREACH( const Term& st, term.toAndTerm().subTerms() ) { - if( st.isLiteralTerm() ) { - fullTextTerms << st.toLiteralTerm().value().toString(); - } - else { - mergedTerm.addSubTerm( st ); - } - } - mergedTerm.addSubTerm( LiteralTerm( fullTextTerms.join( QString::fromLatin1(" AND ") ) ) ); - return mergedTerm.optimized(); - } - else { - return term; - } - } - - /** - * Tries to setup the sub-term of the given comparisonterm according to its property. - * This can fail if the sub-term cannot be converted to the property's range. - * - * This is used in QueryParser::Private::resolveFields - */ - bool setupComparisonTermSubTerm(Nepomuk::Query::ComparisonTerm& ct) - { - // property with resource range - if(ct.property().range().isValid()) { - if(ct.subTerm().isLiteralTerm()) { - // here we need a string. everything else does not work since we match labels - return ct.subTerm().toLiteralTerm().value().isString(); - } - else { - return true; - } - } - - // property with literal range - else if(ct.subTerm().isLiteralTerm()) { - // only strings can be matched via bif:contains - if(ct.comparator() == Nepomuk::Query::ComparisonTerm::Contains && - ct.property().literalRangeType().dataType() != QVariant::String) { - ct.setComparator(Nepomuk::Query::ComparisonTerm::Equal); - } - - // try to convert the value via QVariant - QVariant v = ct.subTerm().toLiteralTerm().value().variant(); - if(v.convert(ct.property().literalRangeType().dataType())) { - ct.setSubTerm(Nepomuk::Query::LiteralTerm(v)); - return true; - } - - // try some heuristics - else { - if(ct.property().literalRangeType().dataType() == QVariant::DateTime) { - // if it is an int with 4 digits it is very likely a year - if(ct.subTerm().toLiteralTerm().value().isInt() ) { - const int year = ct.subTerm().toLiteralTerm().value().toInt(); - if( year >= 1000 && year <= 9999) { - QDate date(year, 1, 1); - QTime time(0,0); - // greater than last day in same year - // greater or equal than the first day in same year - // smaller than first day in same year - // smaller or equal than last day in same year - if(ct.comparator() == ComparisonTerm::Greater || - ct.comparator() == ComparisonTerm::SmallerOrEqual) { - date.setYMD(date.year(), 12, 31); - time.setHMS(23,59,59,999); - } - ct.setSubTerm(Nepomuk::Query::LiteralTerm(QDateTime(date, time))); - return true; - } - } - } - } - } - - // fallback - return false; - } - -#ifndef Q_CC_MSVC -#warning Make the parser handle different data, time, and datetime encodings as well as suffixes like MB or GB -#endif -#if 0 - QDateTime parseDateTime( const Soprano::LiteralValue& literal ) - { - //TODO: change to DateTime parser once complete - Nepomuk::Search::DateParser date( literal.toString() ); - if( date.hasDate() ) { - return QDateTime( date.getDate() ); - } - else { - Nepomuk::Search::TimeParser time( literal.toString() ); - if(time.hasTime() ) - return QDateTime(QDate::currentDate(), time.next() ); - else - return QDateTime(); //return invalid datetime - } - } - - - Soprano::LiteralValue parseSizeType( const Soprano::LiteralValue& literal ) - { - const double KiB = 1024.0; - const double MiB = KiB * 1024.0; - const double GiB = MiB * 1024.0; - const double TiB = GiB * 1024.0; - - const double KB = 1000.0; - const double MB = KB * 1000.0; - const double GB = MB * 1000.0; - const double TB = GB * 1000.0; - - QHash sizes; - sizes.insert( "KiB", KiB ); - sizes.insert( "MiB", MiB ); - sizes.insert( "GiB", GiB ); - sizes.insert( "TiB", TiB ); - sizes.insert( "KB", KB ); - sizes.insert( "MB", MB ); - sizes.insert( "GB", GB ); - sizes.insert ("TB", TB ); - - for ( QHash::const_iterator i = sizes.constBegin(); - i != sizes.constEnd(); ++i ) { - QRegExp cur( QString("^([\\d]+.?[\\d]*)[\\s]*%1$").arg( i.key() ) ); - if( cur.indexIn( literal.toString() ) != -1 ) { - double value = cur.cap( 1 ).toDouble(); - double newValue = value * i.value(); - kDebug() << "Found value" << value << i.key() << "->" << newValue; - return Soprano::LiteralValue( newValue ); - } - } - return literal; - } - - - Nepomuk::Query::Term resolveLiteralValues( const Nepomuk::Query::Term& term ) - { - switch( term.type() ) { - case Nepomuk::Query::Term::Comparison: { - Nepomuk::Query::ComparisonTerm cterm = term.toComparisonTerm(); - Nepomuk::Types::Property p( cterm.property() ); - if ( p.literalRangeType().isValid() ) { - Q_ASSERT( cterm.subTerm().isLiteralTerm() ); - - Nepomuk::Query::ComparisonTerm newTerm; - newTerm.setComparator( cterm.comparator() ); - newTerm.setProperty( QUrl(cterm.property()) ); - - // now try to resolve the literal - const Nepomuk::Query::LiteralTerm subTerm = cterm.subTerm().toLiteralTerm(); - const Nepomuk::Types::Literal lt = p.literalRangeType(); - if ( lt.dataType() == QVariant::DateTime && - !subTerm.value().isDateTime() ) { - QDateTime dateTime = parseDateTime( subTerm.value() ); - if ( dateTime.isValid() ) { - newTerm.setSubTerm( Nepomuk::Query::LiteralTerm( dateTime ) ); - return newTerm; - } - } - else if ( lt.dataType() == QVariant::Int && - !subTerm.value().isInt() ) { - newTerm.setSubTerm( Nepomuk::Query::LiteralTerm( parseSizeType( subTerm.value() ) ) ); - return newTerm; - } - } - - return term; - } - - case Nepomuk::Query::Term::And: - case Nepomuk::Query::Term::Or: { - QList newSubTerms; - foreach( const Nepomuk::Query::Term& t, static_cast( term ).subTerms() ) { - newSubTerms << resolveLiteralValues(t); - } - if ( term.isAndTerm() ) - return Nepomuk::Query::AndTerm( newSubTerms ); - else - return Nepomuk::Query::OrTerm( newSubTerms ); - } - - default: - return term; - } - } -#endif - - // a field differs from a plain term in that it does never allow comparators - const char* s_fieldNamePattern = "([^\\s\"':=<>]+|(?:([\"'])[^\"':=<>]+\\%1))"; - const char* s_plainTermPattern = "([^-][^\\s\"':=<>]*|(?:([\"'])[^\"']+\\%1))"; - const char* s_inExclusionPattern = "((?:[\\+\\-\\!]\\s*|[nN][oO][tT]\\s+)?)"; - const char* s_uriPattern = "<([^<>]+)>"; - const char* s_comparatorPattern = "(:|\\<=|\\>=|=|\\<|\\>)"; - - /** - * Creating QRegExp is expensive, copying them is cheap. Thus, we keep static - * instances of the regexps around which we only have to create once. - */ - class QueryParserRegExpPool - { - public: - QueryParserRegExpPool() - : plainTermRx( QLatin1String(s_inExclusionPattern) - + QString::fromLatin1(s_plainTermPattern).arg( 3 ) ), - fieldRx( QLatin1String(s_inExclusionPattern) - + QString::fromLatin1(s_fieldNamePattern).arg( 3 ) - + QLatin1String(s_comparatorPattern) - + QString::fromLatin1(s_plainTermPattern).arg( 6 ) ), - propertyRx( QLatin1String(s_inExclusionPattern) - + QLatin1String(s_uriPattern) - + QLatin1String(s_comparatorPattern) - + QString::fromLatin1(s_plainTermPattern).arg( 5 ) ), - resourceRx( QLatin1String(s_inExclusionPattern) - + QLatin1String(s_uriPattern) - + QLatin1String("(?::|=)") - + QLatin1String(s_uriPattern) ), - fieldFieldRx( QLatin1String(s_inExclusionPattern) - + QString::fromLatin1(s_fieldNamePattern).arg( 3 ) - + QLatin1String(s_comparatorPattern) - + QLatin1String("\\(") - + QString::fromLatin1(s_fieldNamePattern).arg( 6 ) - + QLatin1String(s_comparatorPattern) - + QString::fromLatin1(s_plainTermPattern).arg( 9 ) - + QLatin1String("\\)") ) - { - } - - // match a simple search text - // captures: 1 - The optional + or - sign (may be empty) - // 2 - the search text (including optional paranthesis) - QRegExp plainTermRx; - - // match a field search term: fieldname + relation (:, =, etc) + search text with optional paranthesis - // captures: 1 - The optional + or - sign (may be empty) - // 2 - fieldname - // 3 - relation - // 4 - search text (including optional paranthesis) - QRegExp fieldRx; - - // match a property URI search term: property URI + relation (:, =, etc) + search text with optional paranthesis - // captures: 1 - The optional + or - sign (may be empty) - // 2 - property URI - // 3 - relation - // 4 - search text (including optional paranthesis) - QRegExp propertyRx; - - // match a property URI search term: property URI + relation (:, =, etc) + resource URI - // captures: 1 - The optional + or - sign (may be empty) - // 2 - property URI - // 3 - resource URI - QRegExp resourceRx; - - QRegExp fieldFieldRx; - }; - - // the one global instance used for the statis QueryParser methods - K_GLOBAL_STATIC( QueryParserRegExpPool, s_regExpPool ) -} - - -class Nepomuk::Query::QueryParser::Private -{ -public: - QueryParser* q; - - QSet andKeywords; - QSet orKeywords; - mutable QHash > fieldMatchCache; - QMutex fieldMatchCacheMutex; - - /// set by resolveFields if the query is in fact invalid - bool m_invalidQuery; - - /** - * Resolve the fields in all ComparisonTerms by looking up possible matching - * properties. - * This method will set m_invalidQuery in case there is one term for which - * no property can be matched. - */ - Nepomuk::Query::Term resolveFields( const Nepomuk::Query::Term& term ); -}; - - - -Term QueryParser::Private::resolveFields(const Term &term) -{ - switch( term.type() ) { - case Nepomuk::Query::Term::And: - case Nepomuk::Query::Term::Or: { - QList newSubTerms; - foreach( const Nepomuk::Query::Term& t, static_cast( term ).subTerms() ) { - Nepomuk::Query::Term resolvedTerm = resolveFields(t); - if ( resolvedTerm.isValid() ) - newSubTerms << resolvedTerm; - else - return Nepomuk::Query::Term(); - } - if ( term.isAndTerm() ) - return Nepomuk::Query::AndTerm( newSubTerms ); - else - return Nepomuk::Query::OrTerm( newSubTerms ); - } - - - case Nepomuk::Query::Term::Negation: { - return Nepomuk::Query::NegationTerm::negateTerm( resolveFields( term.toNegationTerm().subTerm() ) ); - } - - - case Nepomuk::Query::Term::Comparison: { - Nepomuk::Query::ComparisonTerm newTerm; - newTerm.setComparator( term.toComparisonTerm().comparator() ); - newTerm.setProperty( term.toComparisonTerm().property() ); - newTerm.setSubTerm( resolveFields( term.toComparisonTerm().subTerm() ) ); - - // A very dumb test to see if the property is set or not: does the URI have a scheme. - // With a proper parser and in-place property matching there will be no need for this anymore - if ( newTerm.property().uri().scheme().isEmpty() ) { - QList properties = q->matchProperty( term.toComparisonTerm().property().uri().toString() ); - // we only use a max of 4 properties, otherwise the queries get too big - // in addition we try to exclude properties which do not make sense: - // - numerical values can never match a resource - Nepomuk::Query::OrTerm orTerm; - for( int i = 0; i < properties.count() && orTerm.subTerms().count() < 4; ++i ) { - const Nepomuk::Types::Property& property = properties[i]; - Nepomuk::Query::ComparisonTerm t( newTerm ); - t.setProperty( property ); - if(setupComparisonTermSubTerm(t)) { - orTerm.addSubTerm( t ); - } - } - if(!orTerm.isValid()) { - m_invalidQuery = true; - return Nepomuk::Query::Term(); - } - return orTerm.optimized(); - } - } - - default: - return term; - } -} - - -Nepomuk::Query::QueryParser::QueryParser() - : d( new Private() ) -{ - d->q = this; - - QString andListStr = i18nc( "Boolean AND keyword in desktop search strings. " - "You can add several variants separated by spaces, " - "e.g. retain the English one alongside the translation; " - "keywords are not case sensitive. Make sure there is " - "no conflict with the OR keyword.", - "and" ); - foreach ( const QString &andKeyword, andListStr.split( ' ', QString::SkipEmptyParts ) ) { - d->andKeywords.insert( andKeyword.toLower() ); - } - QString orListStr = i18nc( "Boolean OR keyword in desktop search strings. " - "You can add several variants separated by spaces, " - "e.g. retain the English one alongside the translation; " - "keywords are not case sensitive. Make sure there is " - "no conflict with the AND keyword.", - "or" ); - foreach ( const QString &orKeyword, orListStr.split( ' ', QString::SkipEmptyParts ) ) { - d->orKeywords.insert( orKeyword.toLower() ); - } -} - - -Nepomuk::Query::QueryParser::~QueryParser() -{ - delete d; -} - - -QList Nepomuk::Query::QueryParser::matchProperty( const QString& fieldName ) const -{ - kDebug() << fieldName; - - QMutexLocker lock( &d->fieldMatchCacheMutex ); - - QHash >::ConstIterator it = d->fieldMatchCache.constFind( fieldName ); - if( it != d->fieldMatchCache.constEnd() ) { - return it.value(); - } - else { - lock.unlock(); - - QList results; - - // - // Due to the limited number of properties in the database a REGEX filter - // is actually faster than a fulltext query via bif:contains (this is what - // experiments showed). - // - QString query = QString( "select distinct ?p where { " - "graph ?g { " - "?p a %1 . " - "?p %2 ?l . " - "FILTER(REGEX(STR(?l),'%3*','i') || REGEX(STR(?p),'%3*','i')) . " - "} " - "}" ) - .arg( Soprano::Node::resourceToN3( Soprano::Vocabulary::RDF::Property() ) ) - .arg( Soprano::Node::resourceToN3( Soprano::Vocabulary::RDFS::label() ) ) - .arg( fieldName ); - kDebug() << "Match query:" << query; - - Soprano::QueryResultIterator labelHits - = Nepomuk::ResourceManager::instance()->mainModel()->executeQuery( query, Soprano::Query::QueryLanguageSparql ); - - while ( labelHits.next() ) { - QUrl property = labelHits.binding( "p" ).uri(); - results << property; - kDebug() << "Found property match" << property; - } - - lock.relock(); - d->fieldMatchCache.insert( fieldName, results ); - return results; - } -} - - -Nepomuk::Query::Query Nepomuk::Query::QueryParser::parse( const QString& query ) const -{ - return parse( query, NoParserFlags ); -} - - -Nepomuk::Query::Query Nepomuk::Query::QueryParser::parse( const QString& query, ParserFlags flags ) const -{ - // TODO: a "real" parser which can handle all of the Xesam user language - // This one for example does not handle nesting at all. - - Nepomuk::Query::Query final; - QList terms; - - bool inOrBlock = false; - bool inAndBlock = false; - - int pos = 0; - - // create local copies of the regexps for thread safety purposes - const QRegExp resourceRx = s_regExpPool->resourceRx; - const QRegExp propertyRx = s_regExpPool->propertyRx; - const QRegExp fieldFieldRx = s_regExpPool->fieldFieldRx; - const QRegExp fieldRx = s_regExpPool->fieldRx; - const QRegExp plainTermRx = s_regExpPool->plainTermRx; - - while ( pos < query.length() ) { - // skip whitespace - while ( pos < query.length() && query[pos].isSpace() ) { - kDebug() << "Skipping space at" << pos; - ++pos; - } - - Term term; - - if ( pos < query.length() ) { - if ( resourceRx.indexIn( query, pos ) == pos ) { - kDebug() << "matched resource term at" << pos << resourceRx.cap( 0 ); - term = ComparisonTerm( tryToBeIntelligentAboutParsingUrl( resourceRx.cap( 2 ) ), - ResourceTerm( tryToBeIntelligentAboutParsingUrl( resourceRx.cap( 3 ) ) ), - ComparisonTerm::Equal ); - if ( !positiveTerm( resourceRx.cap( 1 ) ) ) { - term = NegationTerm::negateTerm( term ); - } - pos += resourceRx.matchedLength(); - } - - else if ( propertyRx.indexIn( query, pos ) == pos ) { - kDebug() << "matched property term at" << pos << propertyRx.cap( 0 ); - ComparisonTerm ct; - ct.setProperty( tryToBeIntelligentAboutParsingUrl( propertyRx.cap( 2 ) ) ); - ct.setSubTerm( LiteralTerm( createLiteral( propertyRx.cap( 4 ), flags&QueryTermGlobbing ) ) ); - QString comparator = propertyRx.cap( 3 ); - ct.setComparator( fieldTypeRelationFromString( comparator ) ); - pos += propertyRx.matchedLength(); - - if ( !positiveTerm(propertyRx.cap( 1 ) ) ) { - term = NegationTerm::negateTerm( ct ); - } - else { - term = ct; - } - } - - else if ( fieldFieldRx.indexIn( query, pos ) == pos ) { - kDebug() << "matched field field term at" << pos - << fieldFieldRx.cap( 0 ) - << fieldFieldRx.cap( 2 ) - << fieldFieldRx.cap( 4 ) - << fieldFieldRx.cap( 5 ) - << fieldFieldRx.cap( 7 ) - << fieldFieldRx.cap( 8 ); - ComparisonTerm ct; - ct.setProperty( QUrl(stripQuotes( fieldFieldRx.cap( 2 ) )) ); - QString comparator = fieldFieldRx.cap( 4 ); - ct.setComparator( fieldTypeRelationFromString( comparator ) ); - ct.setSubTerm( ComparisonTerm( QUrl(stripQuotes( fieldFieldRx.cap( 5 ) )), - LiteralTerm( createLiteral( fieldFieldRx.cap( 8 ), flags&QueryTermGlobbing ) ), - fieldTypeRelationFromString( fieldFieldRx.cap( 7 ) ) ) ); - pos += fieldFieldRx.matchedLength(); - - if ( !positiveTerm( fieldFieldRx.cap( 1 ) ) ) { - term = NegationTerm::negateTerm( ct ); - } - else { - term = ct; - } - } - - else if ( fieldRx.indexIn( query, pos ) == pos ) { - kDebug() << "matched field term at" << pos << fieldRx.cap( 0 ) << fieldRx.cap( 2 ) << fieldRx.cap( 4 ) << fieldRx.cap( 5 ); - if( stripQuotes ( fieldRx.cap( 2 ) ).compare( QString( "inFolder" ), Qt::CaseInsensitive ) == 0 ) { - KUrl url( fieldRx.cap( 5 ) ); - kDebug() << "found include path" << url; - FileQuery fileQuery(final); - if ( positiveTerm( fieldRx.cap( 1 ) ) ) - fileQuery.addIncludeFolder(url); - else - fileQuery.addExcludeFolder(url); - final = fileQuery; - pos += fieldRx.matchedLength(); - } - else { - ComparisonTerm ct; - ct.setProperty( QUrl( stripQuotes( fieldRx.cap( 2 ) ) ) ); - ct.setSubTerm( LiteralTerm( createLiteral( fieldRx.cap( 5 ), flags&QueryTermGlobbing ) ) ); - QString comparator = fieldRx.cap( 4 ); - ct.setComparator( fieldTypeRelationFromString( comparator ) ); - pos += fieldRx.matchedLength(); - if ( !positiveTerm(fieldRx.cap( 1 ) ) ) { - NegationTerm nt; - nt.setSubTerm( ct ); - term = nt; - } - else { - term = ct; - } - } - } - - else if ( plainTermRx.indexIn( query, pos ) == pos ) { - QString value = plainTermRx.cap( 2 ); - if ( d->orKeywords.contains( value.toLower() ) ) { - inOrBlock = true; - } - else if ( d->andKeywords.contains( value.toLower() ) ) { - inAndBlock = true; - } - else { - kDebug() << "matched literal at" << pos << value; - if( flags&DetectFilenamePattern && isFilenamePattern(value) ) { - term = createFilenamePatternTerm( value ); - } - else { - term = LiteralTerm( createLiteral( value, flags&QueryTermGlobbing ) ); - } - if ( !positiveTerm(plainTermRx.cap( 1 ) ) ) { - term = NegationTerm::negateTerm( term ); - } - } - pos += plainTermRx.matchedLength(); - } - - else { - kDebug() << "Invalid query at" << pos << query; - return Query(); - } - - if ( term.isValid() ) { - if ( inOrBlock && !terms.isEmpty() ) { - OrTerm orTerm; - orTerm.addSubTerm( terms.takeLast() ); - orTerm.addSubTerm( term ); - terms.append( orTerm ); - } - else if ( inAndBlock && !terms.isEmpty() ) { - AndTerm andTerm; - andTerm.addSubTerm( terms.takeLast() ); - andTerm.addSubTerm( term ); - terms.append( andTerm ); - } - else { - terms.append( term ); - } - } - } - } - - if ( terms.count() == 1 ) { - final.setTerm( terms[0] ); - } - else if ( terms.count() > 0 ) { - AndTerm t; - t.setSubTerms( terms ); - final.setTerm( t ); - } - - d->m_invalidQuery = false; - final.setTerm( mergeLiteralTerms( d->resolveFields( final.term() ) ) ); - if(d->m_invalidQuery) { - return Query(); - } - else { - return final; - } -} - - -// static -Nepomuk::Query::Query Nepomuk::Query::QueryParser::parseQuery( const QString& query ) -{ - QueryParser parser; - return parser.parse( query ); -} - - -// static -Nepomuk::Query::Query Nepomuk::Query::QueryParser::parseQuery( const QString& query, ParserFlags flags ) -{ - QueryParser parser; - return parser.parse( query, flags ); -} diff --git a/nepomuk/query/queryparser.h b/nepomuk/query/queryparser.h deleted file mode 100644 index 02cbcaf1..00000000 --- a/nepomuk/query/queryparser.h +++ /dev/null @@ -1,205 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_SEARCH_QUERY_PARSER_H_ -#define _NEPOMUK_SEARCH_QUERY_PARSER_H_ - -#include "query.h" - -#include - -#include "nepomukquery_export.h" - - -namespace Nepomuk { - namespace Query { - /** - * \class QueryParser queryparser.h Nepomuk/Query/QueryParser - * - * \brief Parser for desktop user queries. - * - * \warning This is NOT a SPARQL parser. - * - * The QueryParser can be used to parse user queries, ie. queries that the user - * would enter in any search interface, and convert them into Query instances. - * - * The syntax is fairly simple: plain strings match to LiteralTerm terms, - * URIs need to be N3-encoded, when using white space parenthesis need to - * be put around properties and values, terms can be excluded via \p '-'. - * - * \section queryparser_examples Examples - * - * %Query everything that contains the term "nepomuk": - * \code - * nepomuk - * \endcode - * - * %Query everything that contains both the terms "Hello" and "World": - * \code - * Hello World - * \endcode - * - * %Query everything that contains the term "Hello World": - * \code - * "Hello World" - * \endcode - * - * %Query everything that has a tag whose label matches "nepomuk" (actually - * this is where Query::resolveProperties would match "hastag" to nao:hasTag): - * \code - * hastag:nepomuk - * \endcode - * - * %Query everything that has a tag labeled "nepomuk" or a tag labeled "scribo: - * \code - * hastag:nepomuk OR hastag:scribo - * \endcode - * - * %Query everything that has a tag labeled "nepomuk" but not a tag labeled "scribo": - * \code - * +hastag:nepomuk AND -hastag:scribo - * \endcode - * - * The parser can handle one special case of nesting (TODO: implement a "real" parser) - * which matches all resources that are related to a resource which in turn has a certain - * property: - * \code - * related:(hastag:nepomuk) - * \endcode - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT QueryParser - { - public: - /** - * Create a new query parser. - */ - QueryParser(); - - /** - * Destructor - */ - ~QueryParser(); - - /** - * Flags to change the behaviour of the parser. - * - * \since 4.5 - */ - enum ParserFlag { - /** - * No flags. Default for parse() - */ - NoParserFlags = 0x0, - - /** - * Make each full text term use a '*' wildcard - * to match longer strings ('foobar' is matched - * by 'foob*'). - * - * Be aware that the query engine needs at least - * 4 chars to do globbing though. - * - * This is disabled by default. - */ - QueryTermGlobbing = 0x1, - - /** - * Try to detect filename pattern like *.mp3 - * or hello*.txt and create appropriate ComparisonTerm - * instances using ComparisonTerm::Regexp instead of - * ComparisonTerm::Contains. - * - * \since 4.6 - */ - DetectFilenamePattern = 0x2 - }; - Q_DECLARE_FLAGS( ParserFlags, ParserFlag ) - - /** - * Parse a user query. - * - * \return The parsed query or an invalid Query object - * in case the parsing failed. - */ - Query parse( const QString& query ) const; - - /** - * Parse a user query. - * - * \param query The query string to parse - * \param flags a set of flags influencing the parsing process. - * - * \return The parsed query or an invalid Query object - * in case the parsing failed. - * - * \since 4.5 - */ - Query parse( const QString& query, ParserFlags flags ) const; - - /** - * Try to match a field name as used in a query string to actual - * properties. - * - * The matching is cached inside the Query instance for fast - * subsequent lookups. - * - * Example: - * \code - * hastag:nepomuk - * \endcode - * - * \return A list of properties that match \p fieldName or an empty - * list in case nothing was matched. - * - * This method is used by parse() to match properties used in user queries. - */ - QList matchProperty( const QString& fieldName ) const; - - /** - * Convenience method to quickly parse a query without creating an object. - * - * \return The parsed query or an invalid Query object - * in case the parsing failed. - */ - static Query parseQuery( const QString& query ); - - /** - * \overload - * - * \param query The query string to parse - * \param flags a set of flags influencing the parsing process. - * - * \since 4.6 - */ - static Query parseQuery( const QString& query, ParserFlags flags ); - - private: - class Private; - Private* const d; - }; - } -} - -Q_DECLARE_OPERATORS_FOR_FLAGS( Nepomuk::Query::QueryParser::ParserFlags ) - -#endif diff --git a/nepomuk/query/queryserializer.cpp b/nepomuk/query/queryserializer.cpp deleted file mode 100644 index 17fc97a1..00000000 --- a/nepomuk/query/queryserializer.cpp +++ /dev/null @@ -1,493 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#include "queryserializer.h" - -#include "filequery.h" -#include "term.h" -#include "literalterm.h" -#include "resourceterm.h" -#include "andterm.h" -#include "orterm.h" -#include "negationterm.h" -#include "comparisonterm.h" -#include "comparisonterm_p.h" -#include "resourcetypeterm.h" -#include "optionalterm.h" - -#include "property.h" -#include "class.h" - -#include - -#include -#include - -#include - - -using namespace Nepomuk::Query; - -namespace { - - QString aggregateToString( Nepomuk::Query::ComparisonTerm::AggregateFunction f ) - { - switch( f ) { - case Nepomuk::Query::ComparisonTerm::Count: - return QString::fromLatin1("count"); - case Nepomuk::Query::ComparisonTerm::DistinctCount: - return QString::fromLatin1("distinctcount"); - case Nepomuk::Query::ComparisonTerm::Max: - return QString::fromLatin1("max"); - case Nepomuk::Query::ComparisonTerm::Min: - return QString::fromLatin1("min"); - case Nepomuk::Query::ComparisonTerm::Sum: - return QString::fromLatin1("sum"); - case Nepomuk::Query::ComparisonTerm::DistinctSum: - return QString::fromLatin1("distinctsum"); - case Nepomuk::Query::ComparisonTerm::Average: - return QString::fromLatin1("avg"); - case Nepomuk::Query::ComparisonTerm::DistinctAverage: - return QString::fromLatin1("distinctavg"); - default: - return QString(); - } - } - - Nepomuk::Query::ComparisonTerm::AggregateFunction stringToAggregate( const QStringRef& f ) - { - if( f == QString::fromLatin1("count") ) - return Nepomuk::Query::ComparisonTerm::Count; - else if( f == QString::fromLatin1("distinctcount") ) - return Nepomuk::Query::ComparisonTerm::DistinctCount; - else if( f == QString::fromLatin1("max") ) - return Nepomuk::Query::ComparisonTerm::Max; - else if( f == QString::fromLatin1("min") ) - return Nepomuk::Query::ComparisonTerm::Min; - else if( f == QString::fromLatin1("sum") ) - return Nepomuk::Query::ComparisonTerm::Sum; - else if( f == QString::fromLatin1("distinctsum") ) - return Nepomuk::Query::ComparisonTerm::DistinctSum; - else if( f == QString::fromLatin1("avg") ) - return Nepomuk::Query::ComparisonTerm::Average; - else if( f == QString::fromLatin1("distinctavg") ) - return Nepomuk::Query::ComparisonTerm::DistinctAverage; - else - return Nepomuk::Query::ComparisonTerm::NoAggregateFunction; - } - - - bool doSerializeTerm( QXmlStreamWriter& xml, const Nepomuk::Query::Term& term ) - { - switch(term.type()) { - case Term::Literal: { - xml.writeStartElement( QLatin1String("literal") ); - const Soprano::LiteralValue value = term.toLiteralTerm().value(); - if( value.isPlain() ) - xml.writeAttribute( QLatin1String("lang"), value.language().toString() ); - else - xml.writeAttribute( QLatin1String("datatype"), KUrl(value.dataTypeUri()).url() ); - xml.writeCharacters( value.toString() ); - xml.writeEndElement(); - break; - } - - case Term::Resource: - xml.writeStartElement( QLatin1String("resource") ); - xml.writeAttribute( QLatin1String("uri"), KUrl( term.toResourceTerm().resource().resourceUri() ).url() ); - xml.writeEndElement(); - break; - - case Term::And: - xml.writeStartElement( QLatin1String("and") ); - Q_FOREACH( const Term& myterm, term.toAndTerm().subTerms() ) { - doSerializeTerm( xml, myterm ); - } - xml.writeEndElement(); - break; - - case Term::Or: - xml.writeStartElement( QLatin1String("or") ); - Q_FOREACH( const Term& myterm, term.toOrTerm().subTerms() ) { - doSerializeTerm( xml, myterm ); - } - xml.writeEndElement(); - break; - - case Term::Comparison: { - ComparisonTerm cTerm( term.toComparisonTerm() ); - - xml.writeStartElement( QLatin1String("comparison") ); - - if( cTerm.property().isValid() ) - xml.writeAttribute( QLatin1String("property"), KUrl(cTerm.property().uri()).url() ); - xml.writeAttribute( QLatin1String("comparator"), Nepomuk::Query::comparatorToString(cTerm.comparator()) ); - if( !cTerm.variableName().isEmpty() ) - xml.writeAttribute( QLatin1String("varname"), cTerm.variableName() ); - if( cTerm.aggregateFunction() != ComparisonTerm::NoAggregateFunction ) - xml.writeAttribute( QLatin1String("aggregate"), aggregateToString(cTerm.aggregateFunction()) ); - if( cTerm.sortWeight() != 0 ) { - xml.writeAttribute( QLatin1String("sortWeight"), QString::number(cTerm.sortWeight()) ); - xml.writeAttribute( QLatin1String("sortOrder"), cTerm.sortOrder() == Qt::AscendingOrder ? QLatin1String("asc") : QLatin1String("desc") ); - } - xml.writeAttribute( QLatin1String("inverted"), cTerm.isInverted() ? QLatin1String("true") : QLatin1String("false") ); - - doSerializeTerm( xml, cTerm.subTerm() ); - - xml.writeEndElement(); - break; - } - - case Term::ResourceType: - xml.writeStartElement( QLatin1String("type") ); - xml.writeAttribute( QLatin1String("uri"), KUrl( term.toResourceTypeTerm().type().uri() ).url() ); - xml.writeEndElement(); - break; - - case Term::Negation: - xml.writeStartElement( QLatin1String("not") ); - doSerializeTerm( xml, term.toNegationTerm().subTerm() ); - xml.writeEndElement(); - break; - - case Term::Optional: - xml.writeStartElement( QLatin1String("optional") ); - doSerializeTerm( xml, term.toOptionalTerm().subTerm() ); - xml.writeEndElement(); - break; - - default: - return false; - } - - return true; - } - - - Term doParseTerm( QXmlStreamReader& xml, bool* ok = 0 ) - { - Q_ASSERT( xml.isStartElement() ); - - if( xml.name() == QLatin1String("literal") ) { - if( ok ) - *ok = true; - QXmlStreamAttributes attr = xml.attributes(); - LiteralTerm term; - if( attr.hasAttribute( QLatin1String("datatype") ) ) - term = LiteralTerm( Soprano::LiteralValue::fromString( xml.readElementText(), KUrl(attr.value( QLatin1String("datatype") ).toString()) ) ); - else - term = LiteralTerm( Soprano::LiteralValue::createPlainLiteral( xml.readElementText(), attr.value( QLatin1String("lang") ).toString()) ); - // no need to skip to next element due to usage of readElementText? - return term; - } - - else if( xml.name() == QLatin1String("resource") ) { - if( ok ) - *ok = true; - ResourceTerm term( KUrl(xml.attributes().value( QLatin1String("uri") ).toString()) ); - xml.readNextStartElement(); // skip to next element - return term; - } - - else if( xml.name() == QLatin1String("and") ) { - AndTerm term; - while( xml.readNextStartElement() ) { - term.addSubTerm( doParseTerm( xml, ok ) ); - if( ok && !*ok ) - return Term(); - } - return term; - } - - else if( xml.name() == QLatin1String("or") ) { - OrTerm term; - while( xml.readNextStartElement() ) { - term.addSubTerm( doParseTerm( xml, ok ) ); - if( ok && !*ok ) - return Term(); - } - return term; - } - - else if( xml.name() == QLatin1String("not") ) { - if( xml.readNextStartElement() ) { - Term term = doParseTerm( xml, ok ); - if( ok && !*ok ) - return Term(); - xml.readNextStartElement(); // skip to next element - return NegationTerm::negateTerm(term); - } - else { - if( ok ) - *ok = false; - return Term(); - } - } - - else if( xml.name() == QLatin1String("optional") ) { - if( xml.readNextStartElement() ) { - Term term = doParseTerm( xml, ok ); - if( ok && !*ok ) - return Term(); - xml.readNextStartElement(); // skip to next element - return OptionalTerm::optionalizeTerm(term); - } - else { - if( ok ) - *ok = false; - return Term(); - } - } - - else if( xml.name() == QLatin1String("type") ) { - if( ok ) - *ok = true; - ResourceTypeTerm term( KUrl(xml.attributes().value( QLatin1String("uri") ).toString()) ); - xml.readNextStartElement(); // skip to next element - return term; - } - - else if( xml.name() == QLatin1String("comparison") ) { - ComparisonTerm cTerm; - - QXmlStreamAttributes attr = xml.attributes(); - - if( attr.hasAttribute( QLatin1String("property") ) ) - cTerm.setProperty( KUrl(attr.value( QLatin1String("property")).toString()) ); - - if( attr.hasAttribute( QLatin1String("comparator") ) ) - cTerm.setComparator( Nepomuk::Query::stringToComparator(attr.value( QLatin1String("comparator"))) ); - - if( attr.hasAttribute( QLatin1String("varname") ) ) - cTerm.setVariableName( attr.value( QLatin1String("varname")).toString() ); - - if( attr.hasAttribute( QLatin1String("aggregate") ) ) - cTerm.setAggregateFunction( stringToAggregate(attr.value( QLatin1String("aggregate"))) ); - - if( attr.hasAttribute( QLatin1String("sortWeight") ) ) - cTerm.setSortWeight( attr.value( QLatin1String("sortWeight")).toString().toInt(), - attr.value( QLatin1String("sortOrder")) == QLatin1String("desc") ? Qt::DescendingOrder : Qt::AscendingOrder ); - - if( attr.hasAttribute( QLatin1String("inverted") ) ) - cTerm.setInverted( attr.value( QLatin1String("inverted")) == QLatin1String("true") ); - - if( xml.readNextStartElement() ) { - Term term = doParseTerm( xml, ok ); - if( ok && !*ok ) - return Term(); - cTerm.setSubTerm(term); - xml.readNextStartElement(); // skip to next element - } - - if( ok ) - *ok = true; - return cTerm; - } - - else { - kDebug() << "Unknown term type" << xml.name(); - if( ok ) - *ok = false; - return Term(); - } - } - - - Query::QueryFlags parseFlags( const QString& s ) - { - Query::QueryFlags flags = Query::NoQueryFlags; - QStringList sl = s.split( QLatin1String("|"), QString::SkipEmptyParts ); - Q_FOREACH( const QString& sf, sl ) { - if( sf == QLatin1String("NoResultRestrictions") ) - flags |= Query::NoResultRestrictions; - else if( sf == QLatin1String("WithoutFullTextExcerpt") ) - flags |= Query::WithoutFullTextExcerpt; - else - kError() << "Unknown query flag:" << sf; - } - return flags; - } - - QString serializeFlags( Query::QueryFlags flags ) { - QStringList sl; - if( flags&Query::NoResultRestrictions ) - sl << QLatin1String("NoResultRestrictions"); - if( flags&Query::WithoutFullTextExcerpt ) - sl << QLatin1String("WithoutFullTextExcerpt"); - return sl.join( QLatin1String("|") ); - } - - void readQueryAttributes( const QXmlStreamAttributes& attributes, Query& query ) - { - if( attributes.hasAttribute( QLatin1String("limit") ) ) - query.setLimit( attributes.value( QLatin1String("limit") ).toString().toInt() ); - if( attributes.hasAttribute( QLatin1String("offset") ) ) - query.setOffset( attributes.value( QLatin1String("offset") ).toString().toInt() ); - if( attributes.hasAttribute( QLatin1String("fullTextScoring") ) ) - query.setFullTextScoringEnabled( attributes.value( QLatin1String("fullTextScoring") ) == QLatin1String("true") ); - if( attributes.hasAttribute( QLatin1String("fullTextScoringOrder") ) ) - query.setFullTextScoringSortOrder( attributes.value( QLatin1String("fullTextScoringOrder") ) == QLatin1String("desc") ? Qt::DescendingOrder : Qt::AscendingOrder ); - if( attributes.hasAttribute( QLatin1String("flags") ) ) - query.setQueryFlags( parseFlags(attributes.value( QLatin1String("flags") ).toString() ) ); - } -} - - -QString Nepomuk::Query::serializeQuery( const Query& query ) -{ - QString s; - QXmlStreamWriter xml( &s ); - - xml.writeStartDocument(); - - if( query.isFileQuery() ) { - FileQuery fq( query ); - xml.writeStartElement( QLatin1String("filequery") ); - xml.writeAttribute( QLatin1String("queryFiles"), fq.fileMode()&FileQuery::QueryFiles ? QLatin1String("true") : QLatin1String("false") ); - xml.writeAttribute( QLatin1String("queryFolders"), fq.fileMode()&FileQuery::QueryFolders ? QLatin1String("true") : QLatin1String("false") ); - } - else { - xml.writeStartElement( QLatin1String("query") ); - } - - xml.writeAttribute( QLatin1String("limit"), QString::number(query.limit()) ); - xml.writeAttribute( QLatin1String("offset"), QString::number(query.offset()) ); - xml.writeAttribute( QLatin1String("fullTextScoring"), query.fullTextScoringEnabled() ? QLatin1String("true") : QLatin1String("false") ); - xml.writeAttribute( QLatin1String("fullTextScoringOrder"), query.fullTextScoringSortOrder() == Qt::AscendingOrder ? QLatin1String("asc") : QLatin1String("desc") ); - xml.writeAttribute( QLatin1String("flags"), serializeFlags( query.queryFlags() ) ); - - Q_FOREACH( const Query::RequestProperty& rp, query.requestProperties() ) { - xml.writeStartElement( QLatin1String("requestProperty") ); - xml.writeAttribute( QLatin1String("uri"), KUrl(rp.property().uri()).url() ); - xml.writeAttribute( QLatin1String("optional"), rp.optional() ? QLatin1String("true") : QLatin1String("false") ); - xml.writeEndElement(); - } - - if( query.isFileQuery() ) { - FileQuery fq( query ); - const QHash includeFolders = fq.allIncludeFolders(); - for( QHash::ConstIterator it = includeFolders.constBegin(); - it != includeFolders.constEnd(); ++it ) { - xml.writeStartElement( QLatin1String("folder") ); - xml.writeAttribute( QLatin1String("url"), it.key().url() ); - xml.writeAttribute( QLatin1String("include"), QLatin1String("true") ); - xml.writeAttribute( QLatin1String("recursive"), it.value() ? QLatin1String("true") : QLatin1String("false") ); - xml.writeEndElement(); - } - Q_FOREACH( const KUrl& url, fq.excludeFolders() ) { - xml.writeStartElement( QLatin1String("folder") ); - xml.writeAttribute( QLatin1String("url"), url.url() ); - xml.writeAttribute( QLatin1String("include"), QLatin1String("false") ); - xml.writeEndElement(); - } - } - - doSerializeTerm( xml, query.term() ); - - // close query element - xml.writeEndElement(); - xml.writeEndDocument(); - - return s; -} - - -Query Nepomuk::Query::parseQuery( const QString& s ) -{ - QXmlStreamReader xml( s ); - - Query query; - - while( xml.readNextStartElement() ) { - if( xml.name() == QLatin1String("query") ) { - readQueryAttributes( xml.attributes(), query ); - } - else if( xml.name() == QLatin1String("filequery") ) { - readQueryAttributes( xml.attributes(), query ); - - FileQuery fileQuery(query); - FileQuery::FileMode mode; - if( xml.attributes().value(QLatin1String("queryFiles") ) == QLatin1String("true") ) - mode |= FileQuery::QueryFiles; - if( xml.attributes().value(QLatin1String("queryFolders") ) == QLatin1String("true") ) - mode |= FileQuery::QueryFolders; - fileQuery.setFileMode(mode); - - query = fileQuery; - } - else if( xml.name() == QLatin1String("requestProperty") ) { - query.addRequestProperty( Query::RequestProperty( KUrl(xml.attributes().value( QLatin1String("uri") ).toString()), - xml.attributes().value( QLatin1String("optional") ) == QLatin1String("true") ) ); - xml.readNextStartElement(); // skip to next element - } - else if( xml.name() == QLatin1String("folder") ) { - if( !query.isFileQuery() ) { - kDebug() << "Folder tokens are only allowed in filequerys"; - query = Query(); - break; - } - - FileQuery fileQuery(query); - if( xml.attributes().value( QLatin1String("include") ) == QLatin1String("true") ) { - // for the recursive flag we use double negation since the default is true (even if the flag is not specified) - fileQuery.addIncludeFolder( KUrl( xml.attributes().value( QLatin1String("url") ).toString() ), - xml.attributes().value( QLatin1String("recursive") ) != QLatin1String("false") ); - } - else { - fileQuery.addExcludeFolder( KUrl( xml.attributes().value( QLatin1String("url") ).toString() ) ); - } - query = fileQuery; - xml.readNextStartElement(); // skip to next element - } - else { - bool termOk = false; - query.setTerm( doParseTerm( xml, &termOk ) ); - if( !termOk ) { - break; - } - } - } - - return query; -} - - -QString Nepomuk::Query::serializeTerm( const Term& term ) -{ - QString s; - QXmlStreamWriter xml( &s ); - - // FIXME: should we really add the document details? - xml.writeStartDocument(); - doSerializeTerm( xml, term ); - xml.writeEndDocument(); - - return s; -} - - -Term Nepomuk::Query::parseTerm( const QString& s ) -{ - QXmlStreamReader xml( s ); - if( xml.readNextStartElement() ) - return doParseTerm( xml ); - else - return Term(); - -} diff --git a/nepomuk/query/queryserializer.h b/nepomuk/query/queryserializer.h deleted file mode 100644 index a3dcaf7f..00000000 --- a/nepomuk/query/queryserializer.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_QUERY_QUERY_SERIALIZER_H_ -#define _NEPOMUK_QUERY_QUERY_SERIALIZER_H_ - -class QString; - -namespace Nepomuk { - namespace Query { - class Query; - class Term; - - QString serializeQuery( const Query& query ); - Query parseQuery( const QString& s ); - - QString serializeTerm( const Term& term ); - Term parseTerm( const QString& s ); - } -} - -#endif - diff --git a/nepomuk/query/queryserviceclient.cpp b/nepomuk/query/queryserviceclient.cpp deleted file mode 100644 index 841308ff..00000000 --- a/nepomuk/query/queryserviceclient.cpp +++ /dev/null @@ -1,449 +0,0 @@ -/* - Copyright (c) 2008-2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "queryserviceclient.h" -#include "queryserviceclient_p.h" -#include "dbusoperators_p.h" -#include "result.h" -#include "query.h" -#include "queryserviceinterface.h" -#include "queryinterface.h" -#include - -#include -#include -#include -#include - -#include -#include - -#include -#include - - -namespace { - /// create a mapping from binding name to property - QHash encodeRequestProperties( const QList& rps ) - { - QHash encodedRps; - int i = 1; - foreach( const Nepomuk::Query::Query::RequestProperty& rp, rps ) { - encodedRps.insert( QString( "reqProp%1" ).arg( i++ ), KUrl( rp.property().uri() ).url() ); - } - return encodedRps; - } - - /// create a mapping from binding name to property - QHash encodeRequestProperties( const QHash& rps ) - { - QHash encodedRps; - for( QHash::const_iterator it = rps.constBegin(); - it != rps.constEnd(); ++it ) { - encodedRps.insert( it.key(), KUrl( it.value().uri() ).url() ); - } - return encodedRps; - } - - NepomukResultListEventLoop::NepomukResultListEventLoop(Nepomuk::Query::QueryServiceClient* parent) - : QEventLoop(parent) - { - connect(parent, SIGNAL(newEntries(QList)), - this, SLOT(addEntries(QList))); - } - - NepomukResultListEventLoop::~NepomukResultListEventLoop() - { - } - - void NepomukResultListEventLoop::addEntries(const QList< Nepomuk::Query::Result >& entries) - { - m_result << entries; - } - - QList< Nepomuk::Query::Result > NepomukResultListEventLoop::result() const - { - return m_result; - } - -} - - -class Nepomuk::Query::QueryServiceClient::Private -{ -public: - Private() - : queryServiceInterface( 0 ), - queryInterface( 0 ), - dbusConnection( DBusConnectionPool::threadConnection() ), - m_queryActive( false ), - loop( 0 ) { - } - - void _k_entriesRemoved( const QStringList& ); - void _k_finishedListing(); - void _k_handleQueryReply(QDBusPendingCallWatcher*); - void _k_serviceRegistered( const QString& ); - void _k_serviceUnregistered( const QString& ); - - org::kde::nepomuk::QueryService* queryServiceInterface; - org::kde::nepomuk::Query* queryInterface; - QDBusServiceWatcher *queryServiceWatcher; - - QueryServiceClient* q; - - QPointer m_pendingCallWatcher; - - QDBusConnection dbusConnection; - - bool m_queryActive; - QEventLoop* loop; - QString m_errorMessage; -}; - - -void Nepomuk::Query::QueryServiceClient::Private::_k_entriesRemoved( const QStringList& uris ) -{ - QList ul; - foreach( const QString& s, uris ) { - ul.append( QUrl( s ) ); - } - emit q->entriesRemoved( ul ); -} - - -void Nepomuk::Query::QueryServiceClient::Private::_k_finishedListing() -{ - m_queryActive = false; - emit q->finishedListing(); - if( loop ) { - q->close(); - } -} - - -void Nepomuk::Query::QueryServiceClient::Private::_k_handleQueryReply(QDBusPendingCallWatcher* watcher) -{ - QDBusPendingReply reply = *watcher; - if(reply.isError()) { - kDebug() << reply.error(); - m_errorMessage = reply.error().message(); - m_queryActive = false; - emit q->error(m_errorMessage); - if( loop ) { - loop->exit(); - } - } - else { - queryInterface = new org::kde::nepomuk::Query( queryServiceInterface->service(), - reply.value().path(), - dbusConnection ); - connect( queryInterface, SIGNAL(newEntries(QList)), - q, SIGNAL(newEntries(QList)) ); - connect( queryInterface, SIGNAL(resultCount(int)), - q, SIGNAL(resultCount(int)) ); - connect( queryInterface, SIGNAL(entriesRemoved(QStringList)), - q, SLOT(_k_entriesRemoved(QStringList)) ); - connect( queryInterface, SIGNAL(finishedListing()), - q, SLOT(_k_finishedListing()) ); - // run the listing async in case the event loop below is the only one we have - // and we need it to handle the signals and list returns results immediately - QTimer::singleShot( 0, queryInterface, SLOT(list()) ); - } - - delete watcher; -} - - -void Nepomuk::Query::QueryServiceClient::Private::_k_serviceRegistered(const QString &service) -{ - if (service == "org.kde.nepomuk.services.nepomukqueryservice") { - delete queryServiceInterface; - queryServiceInterface = new org::kde::nepomuk::QueryService( "org.kde.nepomuk.services.nepomukqueryservice", - "/nepomukqueryservice", - dbusConnection ); - emit q->serviceAvailabilityChanged(true); - } -} - - -void Nepomuk::Query::QueryServiceClient::Private::_k_serviceUnregistered(const QString &service) -{ - if (service == "org.kde.nepomuk.services.nepomukqueryservice") { - emit q->serviceAvailabilityChanged(false); - } -} - - - - -Nepomuk::Query::QueryServiceClient::QueryServiceClient( QObject* parent ) - : QObject( parent ), - d( new Private() ) -{ - d->q = this; - - Nepomuk::Query::registerDBusTypes(); - - // we use our own connection to be thread-safe - d->queryServiceInterface = new org::kde::nepomuk::QueryService( "org.kde.nepomuk.services.nepomukqueryservice", - "/nepomukqueryservice", - d->dbusConnection ); - d->queryServiceWatcher = new QDBusServiceWatcher(QLatin1String("org.kde.nepomuk.services.nepomukqueryservice"), - QDBusConnection::sessionBus(), - QDBusServiceWatcher::WatchForOwnerChange, - this); - connect(d->queryServiceWatcher, SIGNAL(serviceRegistered(QString)), this, SLOT(_k_serviceRegistered(QString))); - connect(d->queryServiceWatcher, SIGNAL(serviceUnregistered(QString)), this, SLOT(_k_serviceUnregistered(QString))); -} - - -Nepomuk::Query::QueryServiceClient::~QueryServiceClient() -{ - close(); - delete d->queryServiceInterface; - delete d; -} - - -bool Nepomuk::Query::QueryServiceClient::query( const Query& query ) -{ - close(); - - if ( d->queryServiceInterface->isValid() ) { - d->m_queryActive = true; - d->m_pendingCallWatcher = new QDBusPendingCallWatcher(d->queryServiceInterface->asyncCall(QLatin1String("query"), - query.toString()), - this); - connect(d->m_pendingCallWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - this, SLOT(_k_handleQueryReply(QDBusPendingCallWatcher*))); - return true; - } - else { - kDebug() << "Could not contact nepomuk query service."; - return false; - } -} - - -bool Nepomuk::Query::QueryServiceClient::sparqlQuery( const QString& query, const QHash& requestPropertyMap ) -{ - close(); - - if ( d->queryServiceInterface->isValid() ) { - d->m_queryActive = true; - d->m_pendingCallWatcher = new QDBusPendingCallWatcher(d->queryServiceInterface->asyncCall(QLatin1String("sparqlQuery"), - query, - QVariant::fromValue(encodeRequestProperties( requestPropertyMap ))), - this); - connect(d->m_pendingCallWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - this, SLOT(_k_handleQueryReply(QDBusPendingCallWatcher*))); - return true; - } - else { - kDebug() << "Could not contact nepomuk query service."; - return false; - } -} - - -bool Nepomuk::Query::QueryServiceClient::desktopQuery( const QString& query ) -{ - close(); - - if ( d->queryServiceInterface->isValid() ) { - d->m_queryActive = true; - d->m_pendingCallWatcher = new QDBusPendingCallWatcher(d->queryServiceInterface->asyncCall(QLatin1String("desktopQuery"), - query), - this); - connect(d->m_pendingCallWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), - this, SLOT(_k_handleQueryReply(QDBusPendingCallWatcher*))); - return true; - } - else { - kDebug() << "Could not contact nepomuk query service."; - return false; - } -} - - -bool Nepomuk::Query::QueryServiceClient::blockingQuery( const Query& q ) -{ - if( query( q ) ) { - QEventLoop loop; - d->loop = &loop; - loop.exec(); - d->loop = 0; - close(); - return true; - } - else { - return false; - } -} - - -QList< Nepomuk::Query::Result > Nepomuk::Query::QueryServiceClient::syncQuery(const Query& q, bool* ok) -{ - QueryServiceClient qsc; - if( qsc.query( q ) ) { - NepomukResultListEventLoop loop(&qsc); - qsc.d->loop = &loop; - loop.exec(); - qsc.d->loop = 0; - if (ok) { - *ok = !qsc.errorMessage().isEmpty(); - } - return loop.result(); - } - else { - if (ok) { - *ok = false; - } - return QList< Nepomuk::Query::Result >(); - } -} - - -bool Nepomuk::Query::QueryServiceClient::blockingSparqlQuery( const QString& q, const QHash& requestPropertyMap ) -{ - if( sparqlQuery( q, requestPropertyMap ) ) { - QEventLoop loop; - d->loop = &loop; - loop.exec(); - d->loop = 0; - close(); - return true; - } - else { - return false; - } -} - - -QList< Nepomuk::Query::Result > Nepomuk::Query::QueryServiceClient::syncSparqlQuery(const QString& q, - const QHash& requestPropertyMap, - bool *ok) -{ - QueryServiceClient qsc; - if( qsc.sparqlQuery( q, requestPropertyMap ) ) { - NepomukResultListEventLoop loop(&qsc); - qsc.d->loop = &loop; - loop.exec(); - qsc.d->loop = 0; - if (ok) { - *ok = !qsc.errorMessage().isEmpty(); - } - return loop.result(); - } - else { - if (ok) { - *ok = false; - } - return QList< Nepomuk::Query::Result >(); - } -} - - -bool Nepomuk::Query::QueryServiceClient::blockingDesktopQuery( const QString& q ) -{ - if( desktopQuery( q ) ) { - QEventLoop loop; - d->loop = &loop; - loop.exec(); - d->loop = 0; - close(); - return true; - } - else { - return false; - } -} - - -QList< Nepomuk::Query::Result > Nepomuk::Query::QueryServiceClient::syncDesktopQuery(const QString& q, bool* ok) -{ - QueryServiceClient qsc; - if( qsc.desktopQuery( q ) ) { - NepomukResultListEventLoop loop(&qsc); - qsc.d->loop = &loop; - loop.exec(); - qsc.d->loop = 0; - if (ok) { - *ok = !qsc.errorMessage().isEmpty(); - } - return loop.result(); - } - else { - if (ok) { - *ok = false; - } - return QList< Nepomuk::Query::Result >(); - } -} - - -void Nepomuk::Query::QueryServiceClient::close() -{ - // drop pending query calls - - // in case we fired a query but it did not return yet, cancel it - if (d->m_pendingCallWatcher && !d->queryInterface) { - QDBusPendingReply reply = *(d->m_pendingCallWatcher); - OrgKdeNepomukQueryInterface interface( d->queryServiceInterface->service(), - reply.value().path(), - d->dbusConnection ); - interface.close(); - } - delete d->m_pendingCallWatcher; - - d->m_errorMessage.truncate(0); - - if ( d->queryInterface ) { - kDebug(); - d->queryInterface->close(); - delete d->queryInterface; - d->queryInterface = 0; - d->m_queryActive = false; - if( d->loop ) - d->loop->exit(); - } -} - - -bool Nepomuk::Query::QueryServiceClient::isListingFinished() const -{ - return !d->m_queryActive; -} - - -bool Nepomuk::Query::QueryServiceClient::serviceAvailable() -{ - return QDBusConnection::sessionBus().interface()->isServiceRegistered( "org.kde.nepomuk.services.nepomukqueryservice" ); -} - - -QString Nepomuk::Query::QueryServiceClient::errorMessage() const -{ - return d->m_errorMessage; -} - -#include "queryserviceclient.moc" -#include "queryserviceclient_p.moc" diff --git a/nepomuk/query/queryserviceclient.h b/nepomuk/query/queryserviceclient.h deleted file mode 100644 index d41bfc09..00000000 --- a/nepomuk/query/queryserviceclient.h +++ /dev/null @@ -1,343 +0,0 @@ -/* - Copyright (c) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_SERVICE_CLIENT_H_ -#define _NEPOMUK_QUERY_SERVICE_CLIENT_H_ - -#include - -#include "property.h" -#include "query.h" - -#include "nepomukquery_export.h" - -class QUrl; - -namespace Nepomuk { - namespace Query { - - class Result; - - /** - * \class QueryServiceClient queryserviceclient.h Nepomuk/Query/QueryServiceClient - * - * \brief Convenience frontend to the %Nepomuk Query DBus Service - * - * The QueryServiceClient provides an easy way to access the %Nepomuk Query Service - * without having to deal with any communication details. By default it monitors - * queries for changes. - * - * Usage is simple: Create an instance of the client for each search you want to - * track. One instance may also be reused for subsequent queries if further updates - * of the persistent query are not necessary. - * - * For quick queries which do not require any updates one of the static query methods - * can be used: syncQuery(), syncSparqlQuery(), or syncDesktopQuery(). - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT QueryServiceClient : public QObject - { - Q_OBJECT - - public: - /** - * Create a new QueryServiceClient instance. - */ - QueryServiceClient( QObject* parent = 0 ); - - /** - * Desctructor. Closes the query. - */ - ~QueryServiceClient(); - - /** - * \brief Check if the Nepomuk query service is running. - * \return \p true if the Nepomuk query service is running and could - * be contacted via DBus, \p false otherwise - */ - static bool serviceAvailable(); - - /** - * Start a query using the Nepomuk query service. - * - * A local event loop will be started to block the method - * call until all results have been listed, and results will be - * returned. You can check if the query was successful through - * the \p ok pointer. - * - * If updates to the query results are required an instance of QueryServiceClient - * should be created and one of the non-static query methods be used. - * - * \param query the query to perform. - * \param ok a valid boolean pointer, which will be set to \p true - * if the query service was found and the query was started, \p false otherwise. - * If you don't want to track errors, you can pass a null pointer instead. - * - * \return a list of \p Result for the given query. - * - * \sa query(const Query&) - * - * \since 4.5 - */ - static QList syncQuery( const Query& query, bool *ok = 0 ); - - /** - * \overload - * - * \param query a SPARQL query which binds results to variable \p 'r'. - * \param ok a valid boolean pointer, which will be set to \p true - * if the query service was found and the query was started, \p false otherwise. - * If you don't want to track errors, you can pass a null pointer instead. - * \param requestPropertyMap An optional mapping of variable binding names in \p query - * to their corresponding properties. For details see sparqlQuery. - * - * \sa sparqlQuery(const Query&) - * - * \since 4.5 - */ - static QList syncSparqlQuery( const QString& query, - const Nepomuk::Query::RequestPropertyMap& requestPropertyMap = Nepomuk::Query::RequestPropertyMap(), - bool *ok = 0 ); - - /** - * \overload - * - * \param query a desktop query string which can be parsed by QueryParser. - * \param ok a valid boolean pointer, which will be set to \p true - * if the query service was found and the query was started, \p false otherwise. - * If you don't want to track errors, you can pass a null pointer instead. - * - * \sa desktopQuery(const QString&) - * - * \since 4.5 - */ - static QList syncDesktopQuery( const QString& query, bool *ok = 0 ); - - public Q_SLOTS: - /** - * Start a query using the Nepomuk query service. - * - * Results will be reported via newEntries. All results - * have been reported once finishedListing has been emitted. - * - * \param query the query to perform. - * - * \return \p true if the query service was found and the query - * was started. \p false otherwise. - */ - bool query( const Query& query ); - - /** - * \overload - * - * \param query a SPARQL query which binds results to variable \p 'r'. - * \param requestPropertyMap An optional mapping of variable binding names in \p query - * to their corresponding properties. These bindings will then be reported via - * Result::requestProperties(). This map will be constructed automatically when using - * query(const Query&). - * - * \section sparql_query_examples Examples: - * - * Select a simple request property as can also be done via Query::Query: - * - * \code - * QString query = "select ?r ?mtime where { " - * "?r a nfo:FileDataObject . " - * "?r nie:lastModified ?mtime . " - * "}"; - * - * QueryServiceClient::RequestPropertyMap requestPropertyMap; - * requestPropertyMap.insert( "mtime", Vocabulary::NIE::lastModified() ); - * - * sparqlQuery( query, requestPropertyMap ); - * \endcode - * - * This will report the resources themselves and their modification time in the result's request - * properties: - * - * \code - * void handleResult( const Query::Result& results ) { - * QDateTime lastModified = result.requestProperty( Vocabulary::NIE::lastModified() ).toDateTime(); - * [...] - * \endcode - * - * While using Query::Query restricts to request properties to diret properties of the - * results using a custom SPARQL query allows to use any binding as request property. - * The used property URI in the mapping does not even need to match anything in the query: - * - * \code - * QString query = "select ?r ?phone where { " - * "?r a nco:PersonContact . " - * "?r nco:hasPhoneNumber ?n . " - * "?n nco:phoneNumber ?phone . " - * "}"; - * - * QueryServiceClient::RequestPropertyMap requestPropertyMap; - * requestPropertyMap.insert( "phone", Vocabulary::NCO::hasPhoneNumber() ); - * \endcode - * - * \sa Query::requestPropertyMap() - */ - bool sparqlQuery( const QString& query, const Nepomuk::Query::RequestPropertyMap& requestPropertyMap = Nepomuk::Query::RequestPropertyMap() ); - - /** - * \overload - * - * \param query a desktop query string which can be parsed by QueryParser. - */ - bool desktopQuery( const QString& query ); - - /** - * Start a query using the Nepomuk query service. - * - * Results will be reported as with query(const QString&) - * but a local event loop will be started to block the method - * call until all results have been listed. - * - * The client will be closed after the initial listing. Thus, - * changes to results will not be reported as it is the case - * with the non-blocking methods. - * - * \param query the query to perform. - * - * \return \p true if the query service was found and the query - * was started. \p false otherwise. - * - * \sa query(const Query&), close() - */ - bool blockingQuery( const Query& query ); - - /** - * \overload - * - * \param query a SPARQL query which binds results to variable \p 'r'. - * \param requestPropertyMap An optional mapping of variable binding names in \p query - * to their corresponding properties. For details see sparqlQuery. - * - * \sa sparqlQuery(const Query&) - */ - bool blockingSparqlQuery( const QString& query, const Nepomuk::Query::RequestPropertyMap& requestPropertyMap = Nepomuk::Query::RequestPropertyMap() ); - - /** - * \overload - * - * \param query a desktop query string which can be parsed by QueryParser. - * - * \sa desktopQuery(const QString&), close() - */ - bool blockingDesktopQuery( const QString& query ); - - /** - * Close the client, thus stop to monitor the query - * for changes. Without closing the client it will continue - * signalling changes to the results. - * - * This will also make any blockingQuery return immediately. - */ - void close(); - - /** - * \return \p true if all results have been listed (ie. finishedListing() has - * been emitted), close() has been called, or no query was started. - * - * \since 4.6 - */ - bool isListingFinished() const; - - /** - * The last error message which has been emitted via error() or an - * empty string if there was no error. - * - * \since 4.6 - */ - QString errorMessage() const; - - Q_SIGNALS: - /** - * Emitted for new search results. This signal is emitted both - * for the initial listing and for changes to the search. - */ - void newEntries( const QList& entries ); - - /** - * Emitted if the search results changed when monitoring a query. - * \param entries A list of resource URIs identifying the resources - * that dropped out of the query results. - */ - void entriesRemoved( const QList& entries ); - - /** - * The number of results that are reported via newEntries() before the - * finishedListing() signal. - * - * Emitted once the count of the results is available. This might - * happen before the first result is emitted, in between the results, or - * in rare cases it could even happen after all results have been reported. - * - * Also be aware that no count will be provided when using sparqlQuery() - * - * \since 4.6 - */ - void resultCount( int count ); - - /** - * Emitted when the initial listing has been finished, ie. if all - * results have been reported via newEntries. If no further updates - * are necessary the client should be closed now. - * - * In case of an error this signal is not emitted. - * - * \sa error() - */ - void finishedListing(); - - /** - * Emitted when an error occurs. This typically happens in case the query - * service is not running or does not respond. No further signals will be - * emitted after this one. - * - * \since 4.6 - */ - void error( const QString& errorMessage ); - - /** - * Emitted when the availability of the query service changes - * - * \since 4.8 - */ - void serviceAvailabilityChanged( bool running ); - - private: - class Private; - Private* const d; - - Q_PRIVATE_SLOT( d, void _k_entriesRemoved( const QStringList& ) ) - Q_PRIVATE_SLOT( d, void _k_finishedListing() ) - Q_PRIVATE_SLOT( d, void _k_handleQueryReply(QDBusPendingCallWatcher*) ) - Q_PRIVATE_SLOT( d, void _k_serviceRegistered( const QString& ) ) - Q_PRIVATE_SLOT( d, void _k_serviceUnregistered( const QString& ) ) - }; - } -} - -#endif diff --git a/nepomuk/query/queryserviceclient_p.h b/nepomuk/query/queryserviceclient_p.h deleted file mode 100644 index d8db98fc..00000000 --- a/nepomuk/query/queryserviceclient_p.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - Copyright (c) 2010 Dario Freddi - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_SERVICE_CLIENT_P_H_ -#define _NEPOMUK_QUERY_SERVICE_CLIENT_P_H_ - -#include "result.h" - -#include -#include - -namespace { - - class NepomukResultListEventLoop : public QEventLoop - { - Q_OBJECT - public: - NepomukResultListEventLoop(Nepomuk::Query::QueryServiceClient *parent); - virtual ~NepomukResultListEventLoop(); - - QList result() const; - - public Q_SLOTS: - void addEntries(const QList &entries); - - private: - QList m_result; - }; - -} - -#endif diff --git a/nepomuk/query/resourceterm.cpp b/nepomuk/query/resourceterm.cpp deleted file mode 100644 index 2a6485bb..00000000 --- a/nepomuk/query/resourceterm.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "resourceterm.h" -#include "resourceterm_p.h" -#include "querybuilderdata_p.h" -#include "andterm_p.h" - -#include - - -bool Nepomuk::Query::ResourceTermPrivate::equals( const TermPrivate* other ) const -{ - if ( other->m_type == m_type ) { - const ResourceTermPrivate* rtp = static_cast( other ); - return rtp->m_resource == m_resource; - } - else { - return false; - } -} - - -QString Nepomuk::Query::ResourceTermPrivate::toSparqlGraphPattern( const QString& varName, const TermPrivate* parentTerm, const QString& additionalFilters, QueryBuilderData* qbd ) const -{ - // - // A negation is expressed via a filter. Since filters can only work on a "real" graph pattern - // we need to make sure that such a pattern exists. This can be done by searching one in a - // surrounding AndTerm. - // - // Why is that enough? - // Nested AndTerms are flattened before the SPARQL query is constructed in Query. Thus, an AndTerm can - // only be embedded in an OrTerm or as a child term to either a ComparisonTerm or an OptionalTerm. - // In both cases we need a real pattern inside the AndTerm. - // - // We use a type pattern for performance reasons. Thus, we assume that each resource has a type. This - // is not perfect but much faster than using a wildcard for the property. And in the end all Nepomuk - // resources should have a properly defined type. - // - bool haveRealTerm = false; - if( parentTerm && parentTerm->m_type == Term::And ) { - haveRealTerm = static_cast(parentTerm)->hasRealPattern(); - } - - QString term; - if( !haveRealTerm ) { - term += QString::fromLatin1("%1 a %2 . ") - .arg( varName, qbd->uniqueVarName() ); - } - - term += QString::fromLatin1("FILTER(%1=%2) . ") - .arg( varName, - Soprano::Node::resourceToN3( m_resource.resourceUri() ) ); - - term += additionalFilters; - - return term; -} - - -Nepomuk::Query::ResourceTerm::ResourceTerm( const ResourceTerm& term ) - : Term( term ) -{ -} - - -Nepomuk::Query::ResourceTerm::ResourceTerm( const Nepomuk::Resource& resource ) - : Term( new ResourceTermPrivate() ) -{ - setResource( resource ); -} - - -Nepomuk::Query::ResourceTerm::~ResourceTerm() -{ -} - - -Nepomuk::Query::ResourceTerm& Nepomuk::Query::ResourceTerm::operator=( const ResourceTerm& term ) -{ - d_ptr = term.d_ptr; - return *this; -} - - -Nepomuk::Resource Nepomuk::Query::ResourceTerm::resource() const -{ - N_D_CONST( ResourceTerm ); - return d->m_resource; -} - - -void Nepomuk::Query::ResourceTerm::setResource( const Nepomuk::Resource& resource ) -{ - N_D( ResourceTerm ); - d->m_resource = resource; -} diff --git a/nepomuk/query/resourceterm.h b/nepomuk/query/resourceterm.h deleted file mode 100644 index 7dc2d5c6..00000000 --- a/nepomuk/query/resourceterm.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_RESOURCE_TERM_H_ -#define _NEPOMUK_QUERY_RESOURCE_TERM_H_ - -#include "term.h" -#include "resource.h" - -#include - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class ResourceTerm resourceterm.h Nepomuk/Query/ResourceTerm - * - * \brief Matches exactly one resource. - * - * The ResourceTerm does only make sense as a sub term to ComparisonTerm - * to match to a known resource. The typical example would be matching - * against a known tag: - * - * \code - * Tag myTag = fancyGetTag(); - * ComparisonTerm term( Vocabulary::NAO::hasTag(), ResourceTerm(myTag) ); - * \endcode - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT ResourceTerm : public Term - { - public: - /** - * Copy constructor. - */ - ResourceTerm( const ResourceTerm& term ); - - /** - * Default constructor - * - * \param resource The resource this term should match against. - */ - ResourceTerm( const Nepomuk::Resource& resource = Nepomuk::Resource() ); - - /** - * Desctructor. - */ - ~ResourceTerm(); - - /** - * Assignment operator. - */ - ResourceTerm& operator=( const ResourceTerm& term ); - - /** - * The resource this term should match against. - * - * \sa setResource() - */ - Nepomuk::Resource resource() const; - - /** - * Set the resource this term should match against. - * - * \sa resource() - */ - void setResource( const Nepomuk::Resource& resource ); - }; - } -} - -#endif diff --git a/nepomuk/query/resourceterm_p.h b/nepomuk/query/resourceterm_p.h deleted file mode 100644 index df92b056..00000000 --- a/nepomuk/query/resourceterm_p.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_RESOURCE_TERM_P_H_ -#define _NEPOMUK_QUERY_RESOURCE_TERM_P_H_ - -#include "term_p.h" -#include "resource.h" - -#include - -namespace Nepomuk { - namespace Query { - class ResourceTermPrivate : public TermPrivate - { - public: - ResourceTermPrivate() { - m_type = Term::Resource; - } - - TermPrivate* clone() const { return new ResourceTermPrivate( *this ); } - - bool equals( const TermPrivate* other ) const; - bool isValid() const { return m_resource.isValid(); } - QString toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString& additionalFilters, QueryBuilderData* qbd ) const; - - Resource m_resource; - }; - } -} - -#endif diff --git a/nepomuk/query/resourcetypeterm.cpp b/nepomuk/query/resourcetypeterm.cpp deleted file mode 100644 index 1f8a287a..00000000 --- a/nepomuk/query/resourcetypeterm.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "resourcetypeterm.h" -#include "resourcetypeterm_p.h" -#include "querybuilderdata_p.h" - -#include -#include - - -bool Nepomuk::Query::ResourceTypeTermPrivate::equals( const TermPrivate* other ) const -{ - if ( other->m_type == m_type ) { - const ResourceTypeTermPrivate* rtp = static_cast( other ); - return rtp->m_types == m_types; - } - else { - return false; - } -} - - -QString Nepomuk::Query::ResourceTypeTermPrivate::toSparqlGraphPattern( const QString& resName, const TermPrivate* parentTerm, const QString &additionalFilters, QueryBuilderData *qbd ) const -{ - Q_UNUSED(parentTerm); - - // we are using the crappy inferencing provided by the nepomuk ontology service where - // each class is also a subclass of itself. - if(m_types.count() == 1) { - return QString::fromLatin1("%1 a %2 . %3") - .arg( resName, - Soprano::Node::resourceToN3( m_types.begin()->uri() ), - additionalFilters ); - } - else { - QStringList typeN3s; - foreach(const Types::Class& type, m_types) { - typeN3s.append(Soprano::Node::resourceToN3(type.uri())); - } - - return QString::fromLatin1("%1 a %2 . FILTER(%2 in (%3)) . %4") - .arg( resName, - qbd->uniqueVarName(), - typeN3s.join(QLatin1String(",")), - additionalFilters); - } -} - - -Nepomuk::Query::ResourceTypeTerm::ResourceTypeTerm( const ResourceTypeTerm& term ) - : Term( term ) -{ -} - - -Nepomuk::Query::ResourceTypeTerm::ResourceTypeTerm( const Nepomuk::Types::Class& type ) - : Term( new ResourceTypeTermPrivate() ) -{ - setType( type ); -} - - -Nepomuk::Query::ResourceTypeTerm::~ResourceTypeTerm() -{ -} - - -Nepomuk::Query::ResourceTypeTerm& Nepomuk::Query::ResourceTypeTerm::operator=( const ResourceTypeTerm& term ) -{ - d_ptr = term.d_ptr; - return *this; -} - - -Nepomuk::Types::Class Nepomuk::Query::ResourceTypeTerm::type() const -{ - N_D_CONST( ResourceTypeTerm ); - if(!d->m_types.isEmpty()) - return *d->m_types.begin(); - else - return Types::Class(); -} - - -void Nepomuk::Query::ResourceTypeTerm::setType( const Nepomuk::Types::Class& type ) -{ - N_D( ResourceTypeTerm ); - d->m_types.clear(); - if(type.isValid()) - d->m_types.insert(type); -} diff --git a/nepomuk/query/resourcetypeterm.h b/nepomuk/query/resourcetypeterm.h deleted file mode 100644 index 6b2e37ce..00000000 --- a/nepomuk/query/resourcetypeterm.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_RESOURCE_TYPE_TERM_H_ -#define _NEPOMUK_QUERY_RESOURCE_TYPE_TERM_H_ - -#include "term.h" -#include "class.h" - -#include - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class ResourceTypeTerm resourcetypeterm.h Nepomuk/Query/ResourceTypeTerm - * - * \brief Matching resources by type. - * - * The %ResourceTypeTerm matches all resources of a specific type. The only - * difference to using a ComparisonTerm with property \p rdf:type and a ResourceTerm - * subterm is that %ResourceTypeTerm also matches resources which have a type - * derived from the requested one. - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT ResourceTypeTerm : public Term - { - public: - /** - * Copy constructor. - */ - ResourceTypeTerm( const ResourceTypeTerm& term ); - - /** - * Default constructor. - * - * \param type The type to match. - */ - ResourceTypeTerm( const Nepomuk::Types::Class& type = Nepomuk::Types::Class() ); - - /** - * Destructor. - */ - ~ResourceTypeTerm(); - - /** - * Assignment operator. - */ - ResourceTypeTerm& operator=( const ResourceTypeTerm& term ); - - /** - * The type to match. - * - * \sa setType() - */ - Nepomuk::Types::Class type() const; - - /** - * Set the type to match. - * - * \sa type() - */ - void setType( const Nepomuk::Types::Class& type ); - }; - } -} - -#endif diff --git a/nepomuk/query/resourcetypeterm_p.h b/nepomuk/query/resourcetypeterm_p.h deleted file mode 100644 index 9155d6c5..00000000 --- a/nepomuk/query/resourcetypeterm_p.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2012 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_RESOURCE_TYPE_TERM_P_H_ -#define _NEPOMUK_QUERY_RESOURCE_TYPE_TERM_P_H_ - -#include "term_p.h" -#include "class.h" - -#include -#include - -namespace Nepomuk { - namespace Query { - class ResourceTypeTermPrivate : public TermPrivate - { - public: - ResourceTypeTermPrivate() { - m_type = Term::ResourceType; - } - - TermPrivate* clone() const { return new ResourceTypeTermPrivate( *this ); } - - bool equals( const TermPrivate* other ) const; - bool isValid() const { return !m_types.isEmpty(); } - QString toSparqlGraphPattern( const QString& resourceVarName, const TermPrivate* parentTerm, const QString& additionalFilters, QueryBuilderData* qbd ) const; - - QSet m_types; - }; - } -} - -#endif diff --git a/nepomuk/query/result.cpp b/nepomuk/query/result.cpp deleted file mode 100644 index 12e4e88c..00000000 --- a/nepomuk/query/result.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#include "result.h" -#include "variant.h" - -#include - -#include "resource.h" -#include "property.h" - -#include // for qHash( QUrl() ) -#include - - -class Nepomuk::Query::Result::Private : public QSharedData -{ -public: - Resource resource; - double score; - QHash requestProperties; - Soprano::BindingSet additionalBindings; - QString excerpt; -}; - - -Nepomuk::Query::Result::Result() - : d( new Private() ) -{ -} - - -Nepomuk::Query::Result::Result( const Resource& res, double score ) - : d( new Private() ) -{ - d->resource = res; - d->score = score; -} - - -Nepomuk::Query::Result::Result( const Result& other ) -{ - d = other.d; -} - - -Nepomuk::Query::Result::~Result() -{ -} - - -Nepomuk::Query::Result& Nepomuk::Query::Result::operator=( const Result& other ) -{ - d = other.d; - return *this; -} - - -double Nepomuk::Query::Result::score() const -{ - return d->score; -} - - -Nepomuk::Resource Nepomuk::Query::Result::resource() const -{ - return d->resource; -} - - -void Nepomuk::Query::Result::setScore( double score ) -{ - d->score = score; -} - - -void Nepomuk::Query::Result::addRequestProperty( const Nepomuk::Types::Property& property, const Soprano::Node& value ) -{ - d->requestProperties[property] = value; -} - - -Soprano::Node Nepomuk::Query::Result::operator[]( const Nepomuk::Types::Property& property ) const -{ - return requestProperty( property ); -} - - -Soprano::Node Nepomuk::Query::Result::requestProperty( const Nepomuk::Types::Property& property ) const -{ - QHash::const_iterator it = d->requestProperties.find( property ); - if ( it != d->requestProperties.end() ) { - return *it; - } - else { - return Soprano::Node(); - } -} - - -QHash Nepomuk::Query::Result::requestProperties() const -{ - return d->requestProperties; -} - - -void Nepomuk::Query::Result::setAdditionalBindings( const Soprano::BindingSet& bindings ) -{ - d->additionalBindings = bindings; -} - - -Soprano::BindingSet Nepomuk::Query::Result::additionalBindings() const -{ - return d->additionalBindings; -} - - -Nepomuk::Variant Nepomuk::Query::Result::additionalBinding( const QString& name ) const -{ - return Variant::fromNode( d->additionalBindings.value(name) ); -} - - -void Nepomuk::Query::Result::setExcerpt( const QString& text ) -{ - d->excerpt = text; -} - - -QString Nepomuk::Query::Result::excerpt() const -{ - return d->excerpt; -} - - -bool Nepomuk::Query::Result::operator==( const Result& other ) const -{ - if ( d->resource != other.d->resource || - d->score != other.d->score ) { - return false; - } - for ( QHash::const_iterator it = d->requestProperties.constBegin(); - it != d->requestProperties.constEnd(); ++it ) { - QHash::const_iterator it2 = other.d->requestProperties.constFind( it.key() ); - if ( it2 == other.d->requestProperties.constEnd() || - it2.value() != it.value() ) { - return false; - } - } - for ( QHash::const_iterator it = other.d->requestProperties.constBegin(); - it != other.d->requestProperties.constEnd(); ++it ) { - QHash::const_iterator it2 = d->requestProperties.constFind( it.key() ); - if ( it2 == d->requestProperties.constEnd() || - it2.value() != it.value() ) { - return false; - } - } - return d->additionalBindings == other.d->additionalBindings; -} diff --git a/nepomuk/query/result.h b/nepomuk/query/result.h deleted file mode 100644 index 618cb265..00000000 --- a/nepomuk/query/result.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_QUERY_RESULT_H_ -#define _NEPOMUK_QUERY_RESULT_H_ - -#include -#include -#include -#include - -#include -#include - -#include "nepomukquery_export.h" - -namespace Nepomuk { - - class Resource; - class Variant; - namespace Types { - class Property; - } - - namespace Query { - /** - * \class Result result.h Nepomuk/Query/Result - * - * \brief A single search result. - * - * A search via QueryServiceClient returns a set of Result object. A result consists - * of a Nepomuk::Resource and an optional score. - * - * Additional bindings (variable values) as requested via ComparisonTerm::setVariableName() - * can be retrieved using additionalBinding(). - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT Result - { - public: - /** - * Create an empty result. - */ - Result(); - - /** - * Create a new result. - * - * \param resource The result resource. - * \param score The optional result score. - */ - Result( const Nepomuk::Resource& resource, double score = 0.0 ); - - /** - * Copy constructor. - */ - Result( const Result& ); - - /** - * Destructor - */ - ~Result(); - - /** - * Assignment operator - */ - Result& operator=( const Result& ); - - /** - * The score of the result. By default the value is 0.0 - * which means no score. - * - * Be aware that scoring needs to be enabled via Query::setFullTextScoringEnabled() - * in order for this value to be filled. - * - * \sa setScore - */ - double score() const; - - /** - * The result resource. - */ - Resource resource() const; - - /** - * Set the score of the result. - * - * Normally there is no need to call this method as the query service - * does set the bindings. - * - * \sa score - */ - void setScore( double score ); - - /** - * Add the value of a request property. - * - * \sa Query::RequestProperty - */ - void addRequestProperty( const Types::Property& property, const Soprano::Node& value ); - - /** - * Retrieve the values of the request properties. - * - * \sa Query::RequestProperty - */ - QHash requestProperties() const; - - /** - * Retrieve value of request property \p property. - * - * \sa requestProperties, addRequestProperty - */ - Soprano::Node operator[]( const Types::Property& property ) const; - - /** - * Retrieve value of request property \p property. - * - * \sa additionalBinding, requestProperties, addRequestProperty - */ - Soprano::Node requestProperty( const Types::Property& property ) const; - - /** - * Set the additional bindings a query returned besides the result - * itself and the request properties. - * - * Normally there is no need to call this method as the query service - * does set the bindings. - * - * \since 4.5 - */ - void setAdditionalBindings( const Soprano::BindingSet& bindings ); - - /** - * Retrieve the set of additional bindings as set via setAdditionalBindings(). - * Normally one would use additionalBinding() instead. - * - * \since 4.5 - */ - Soprano::BindingSet additionalBindings() const; - - /** - * Retrieve an additional binding as returned by the query. Typically - * these bindings are created via ComparisonTerm::setVariableName(). - * But they could also stem from custom SPARQL queries. A simple - * example would be: - * - * \code - * select ?r ?rating where { ?r nao:numericRating ?rating . } - * \endcode - * - * Here \p ?r would be used as the result's resource while - * \p ?rating could be accessed via - * - * \code - * additionalBinding( QLatin1String("rating") ); - * \endcode - * - * If for some reason one needs the plain binding values one - * could use additionalBinding(). - * - * \since 4.5 - */ - Variant additionalBinding( const QString& name ) const; - - /** - * Set the excerpt from the query. - * - * Normally there is no need to call this method as the query service - * does set the excerpt. - * - * \since 4.6 - */ - void setExcerpt( const QString& text ); - - /** - * An excerpt of the matched text with highlighted search words - * in case the query contained a full text matching. - * - * \return A rich-text snippet highlighting the search words or - * and empty string if the query did not contain any full text - * search terms. - * - * \sa LiteralTerm - * - * \since 4.6 - */ - QString excerpt() const; - - /** - * Comparison operator - */ - bool operator==( const Result& ) const; - - private: - class Private; - QSharedDataPointer d; - }; - } -} - -#endif diff --git a/nepomuk/query/simpleterm.cpp b/nepomuk/query/simpleterm.cpp deleted file mode 100644 index 600db933..00000000 --- a/nepomuk/query/simpleterm.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "simpleterm.h" -#include "simpleterm_p.h" - -bool Nepomuk::Query::SimpleTermPrivate::equals( const TermPrivate* other ) const -{ - if ( other->m_type == m_type ) { - return( m_subTerm == static_cast( other )->m_subTerm ); - } - else { - return false; - } -} - - -Nepomuk::Query::SimpleTerm::SimpleTerm( const Term& term ) - : Term( term ) -{ -} - - -Nepomuk::Query::SimpleTerm::SimpleTerm( TermPrivate* d ) - : Term( d ) -{ -} - - -Nepomuk::Query::SimpleTerm::~SimpleTerm() -{ -} - -Nepomuk::Query::Term Nepomuk::Query::SimpleTerm::subTerm() const -{ - N_D_CONST( SimpleTerm ); - return d->m_subTerm; -} - - -void Nepomuk::Query::SimpleTerm::setSubTerm( const Term& term ) -{ - N_D( SimpleTerm ); - d->m_subTerm = term; -} diff --git a/nepomuk/query/simpleterm.h b/nepomuk/query/simpleterm.h deleted file mode 100644 index bf7b6da8..00000000 --- a/nepomuk/query/simpleterm.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_SIMPLE_TERM_H_ -#define _NEPOMUK_QUERY_SIMPLE_TERM_H_ - -#include "term.h" - -#include "nepomukquery_export.h" - -namespace Nepomuk { - namespace Query { - /** - * \class SimpleTerm simpleterm.h Nepomuk/Query/SimpleTerm - * - * \brief Abstract base class for NegationTerm and ComparisonTerm - * which maintains one sub-term. - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT SimpleTerm : public Term - { - public: - /** - * Destructor. - */ - ~SimpleTerm(); - - /** - * The sub term to match against. - * - * \sa setSubTerm() - */ - Term subTerm() const; - - /** - * Set the sub term to match against. - * - * \sa subTerm() - */ - void setSubTerm( const Term& term ); - - /** \cond protected_error_members */ - protected: - SimpleTerm( const Term& term ); - SimpleTerm( TermPrivate* ); - /** \endcond */ - }; - } -} - -#endif diff --git a/nepomuk/query/simpleterm_p.h b/nepomuk/query/simpleterm_p.h deleted file mode 100644 index acbc3ea3..00000000 --- a/nepomuk/query/simpleterm_p.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_SIMPLE_TERM_P_H_ -#define _NEPOMUK_QUERY_SIMPLE_TERM_P_H_ - -#include "term_p.h" - -namespace Nepomuk { - namespace Query { - class SimpleTermPrivate : public TermPrivate - { - public: - bool isValid() const { return m_subTerm.isValid(); } - - bool equals( const TermPrivate* other ) const; - - Term m_subTerm; - }; - } -} - -#endif diff --git a/nepomuk/query/standardqueries.cpp b/nepomuk/query/standardqueries.cpp deleted file mode 100644 index 0afb7383..00000000 --- a/nepomuk/query/standardqueries.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . - */ - -#include "standardqueries.h" -#include "filequery.h" -#include "comparisonterm.h" -#include "literalterm.h" -#include "andterm.h" -#include "orterm.h" -#include "negationterm.h" - -#include "nie.h" -#include "nfo.h" -#include "nie.h" -#include "nuao.h" - -#include - -#include - - -Nepomuk::Query::Query Nepomuk::Query::standardQuery( StandardQuery query, const Term& /*subterm*/ ) -{ - switch( query ) { - case LastModifiedFilesQuery: { - ComparisonTerm lastModifiedTerm( Nepomuk::Vocabulary::NIE::lastModified(), Term() ); - lastModifiedTerm.setSortWeight( 1, Qt::DescendingOrder ); - FileQuery lastModifiedQuery( lastModifiedTerm ); - return lastModifiedQuery; - } - - case MostImportantResourcesQuery: { - ComparisonTerm fancyTerm( Soprano::Vocabulary::NAO::score(), Term() ); - fancyTerm.setSortWeight( 1, Qt::DescendingOrder ); - Query fancyQuery( fancyTerm ); - return fancyQuery; - } - - case NeverOpenedFilesQuery: { - // there are two ways a usage count of 0 can be expressed: - // 1. property with value 0 - // 2. no property at all - OrTerm usageCntTerm( - ComparisonTerm( - Nepomuk::Vocabulary::NUAO::usageCount(), - LiteralTerm( 0 ), - ComparisonTerm::Equal ), - NegationTerm::negateTerm( - ComparisonTerm( - Nepomuk::Vocabulary::NUAO::usageCount(), - Term() ) ) ); - - // Before we had the data management service there was no usage count - // tracking. Thus, in order not to return all files we should filter - // out all files that were created before we started tracking usage. - // However, by default we only show the top 10 results. Thus, in the - // worst case this query will return the same as lastModifiedFilesQuery(). - ComparisonTerm modDateTerm( - Nepomuk::Vocabulary::NIE::lastModified(), - Term() ); - modDateTerm.setSortWeight( 1, Qt::DescendingOrder ); - - FileQuery query( usageCntTerm && modDateTerm ); - return query; - } - - case ResourcesForActivityQuery: { - // FIXME - // get all resources that have some prop defined in a graph which was created in the requested activity? - // select distinct ?r where { graph ?g { ?r ?p ?o . } . ?g . } - // it would be something like: MetaDataTerm( , ) - } - } - - return Query(); -} - - -Nepomuk::Query::Query Nepomuk::Query::dateRangeQuery( const QDate& start, const QDate& end, DateRangeFlags dateFlags ) -{ - // create our range - const LiteralTerm dateFrom( QDateTime( start, QTime( 0,0,0 ) ) ); - const LiteralTerm dateTo( QDateTime( end, QTime( 23, 59, 59, 999 ) ) ); - - // slight optimization: no need for an end filter if the end is in the future - const bool needStartFilter = start.isValid(); - const bool needEndFilter = end.isValid() && end < QDate::currentDate(); - - Query query; - - if( dateFlags & ModificationDate ) { - // include files modified in our date range - ComparisonTerm lastModifiedStart = Nepomuk::Vocabulary::NIE::lastModified() > dateFrom; - ComparisonTerm lastModifiedEnd = Nepomuk::Vocabulary::NIE::lastModified() < dateTo; - if( needStartFilter && needEndFilter ) - query = query || ( lastModifiedStart && lastModifiedEnd ); - else if( needStartFilter ) - query = query || lastModifiedStart; - else if( needEndFilter ) - query = query || lastModifiedEnd; - } - - if( dateFlags & ContentDate ) { - // include files created (as in photos taken) in our data range - ComparisonTerm contentCreatedStart = Nepomuk::Vocabulary::NIE::contentCreated() > dateFrom; - ComparisonTerm contentCreatedEnd = Nepomuk::Vocabulary::NIE::contentCreated() < dateTo; - if( needStartFilter && needEndFilter ) - query = query || ( contentCreatedStart && contentCreatedEnd ); - else if( needStartFilter ) - query = query || contentCreatedStart; - else if( needEndFilter ) - query = query || contentCreatedEnd; - } - - if( dateFlags & UsageDate ) { - // include files opened (and optionally modified) in our date range - // TODO: also take the end of the event into account - ComparisonTerm accessEventStart = Nepomuk::Vocabulary::NUAO::start() > dateFrom; - ComparisonTerm accessEventEnd = Nepomuk::Vocabulary::NUAO::start() < dateTo; - ComparisonTerm accessEventCondition( Nepomuk::Vocabulary::NUAO::involves(), Term() ); - if( needStartFilter && needEndFilter ) - accessEventCondition.setSubTerm( accessEventStart && accessEventEnd ); - else if( needStartFilter ) - accessEventCondition.setSubTerm( accessEventStart ); - else if( needEndFilter ) - accessEventCondition.setSubTerm( accessEventEnd ); - if( accessEventCondition.subTerm().isValid() ) - query = query || accessEventCondition.inverted(); - } - - return query; -} diff --git a/nepomuk/query/standardqueries.h b/nepomuk/query/standardqueries.h deleted file mode 100644 index 79282657..00000000 --- a/nepomuk/query/standardqueries.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . - */ - -#ifndef _NEPOMUK_STANDARD_QUERIES_H_ -#define _NEPOMUK_STANDARD_QUERIES_H_ - -#include "nepomukquery_export.h" -#include "term.h" - -class QDate; - -namespace Nepomuk { - namespace Query { - class Query; - - /** - * A set of predefined queries that can be created via standardQuery(). - * - * \since 4.6 - */ - enum StandardQuery { - /** - * Creates a query that returns all files sorted by descending modification date. - * - * The subterm parameter can be used to specify an application restricting the results - * to files created/opened with that application. - */ - LastModifiedFilesQuery, - - /** - * Creates a query that returns all resources sorted by descending score (as calculated - * by the DataMaintenanceService) - * - * The subterm parameter can be used to specify an application restricting the results - * to files created/opened with that application. - */ - MostImportantResourcesQuery, - - /** - * Creates a query that returns all files with a usage count of 0 - * sorted by descending modification date. - */ - NeverOpenedFilesQuery, - - /** - * Get the resources related to a specific activity. Use a ResourceTerm referring to - * the activity as parameter in standardQuery. - */ - ResourcesForActivityQuery - }; - - - /** - * Modificators to influence the behaviour of dateRangeQuery(). - * - * \since 4.6 - */ - enum DateRangeFlag { - /** - * Query for the modification date (nie:lastModified) - */ - ModificationDate = 0x1, - - /** - * Query for the content creation date (nie:contentCreated) - */ - ContentDate = 0x2, - - /** - * Query for usage events referring to the resource. - */ - UsageDate = 0x4, - - /** - * Query for all possible dates. - */ - AllDates = ModificationDate|ContentDate|UsageDate - }; - Q_DECLARE_FLAGS( DateRangeFlags, DateRangeFlag ) - - /** - * Create a standard query as defined by \p query. - * - * \param query The query to be generated. See StandardQuery. - * \param subterm An optional subterm used for specific types of standard queries that need - * a parameter like ResourcesForActivityQuery. - * - * To get a query that only returns files (this is already true for some of the predefined queries) - * use something like the following: - * - * \code - * Query::FileQuery query = Query::standardQuery( Query::LastModifiedFilesQuery ); - * \endcode - * - * Be aware that queries can be combined. One can for example get the most important files related - * to an activity as follows: - * - * \code - * Query query = Query::standardQuery( Query::ResourcesForActivityQuery, myActivity ) - * && Query::standardQuery( Query::MostImportantResourcesQuery ); - * \endcode - * - * \since 4.6 - */ - NEPOMUKQUERY_EXPORT Query standardQuery( StandardQuery query, const Term& subterm = Term() ); - - /** - * Create a query that returns resources/files that have been modified/accessed in the range - * from \p start to \p end (including both full days). The flags specified in \p dateFlags can be used to influence the - * type of dates that are queried. - * - * \param start The start date of the range, if invalid no start is used, i.e. everything before \p end matches. - * \param end The end date of the range, if invalid no end is used, i.e. everything after \p start matches. - * \param dateFlags Optional flags to influence the final query. - * - * \since 4.6 - */ - NEPOMUKQUERY_EXPORT Query dateRangeQuery( const QDate& start, const QDate& end, DateRangeFlags dateFlags = AllDates ); - } -} - -Q_DECLARE_OPERATORS_FOR_FLAGS( Nepomuk::Query::DateRangeFlags ) - -#endif diff --git a/nepomuk/query/term.cpp b/nepomuk/query/term.cpp deleted file mode 100644 index b9b96a41..00000000 --- a/nepomuk/query/term.cpp +++ /dev/null @@ -1,527 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#include "term.h" -#include "term_p.h" -#include "literalterm.h" -#include "resourceterm.h" -#include "andterm.h" -#include "orterm.h" -#include "negationterm.h" -#include "optionalterm.h" -#include "comparisonterm.h" -#include "resourcetypeterm.h" -#include "literalterm_p.h" -#include "resourceterm_p.h" -#include "andterm_p.h" -#include "orterm_p.h" -#include "negationterm_p.h" -#include "optionalterm_p.h" -#include "comparisonterm_p.h" -#include "resourcetypeterm_p.h" -#include "queryserializer.h" - -#include -#include -#include - -#include "property.h" -#include "variant.h" - - -Nepomuk::Query::Term::Term() - : d_ptr( new TermPrivate() ) -{ -} - - -Nepomuk::Query::Term::Term( const Term& other ) - : d_ptr( other.d_ptr ) -{ -} - - -Nepomuk::Query::Term::Term( TermPrivate* d ) - : d_ptr( d ) -{ -} - - -Nepomuk::Query::Term::~Term() -{ -} - - -Nepomuk::Query::Term& Nepomuk::Query::Term::operator=( const Term& other ) -{ - d_ptr = other.d_ptr; - return *this; -} - - -bool Nepomuk::Query::Term::isValid() const -{ - return d_ptr->isValid(); -} - - -Nepomuk::Query::Term::Type Nepomuk::Query::Term::type() const -{ - return d_ptr->m_type; -} - - -Nepomuk::Query::Term Nepomuk::Query::Term::optimized() const -{ - switch( type() ) { - case Nepomuk::Query::Term::And: - case Nepomuk::Query::Term::Or: { - QList subTerms = static_cast( *this ).subTerms(); - QList newSubTerms; - QList::const_iterator end( subTerms.constEnd() ); - for ( QList::const_iterator it = subTerms.constBegin(); - it != end; ++it ) { - const Nepomuk::Query::Term& t = *it; - Nepomuk::Query::Term ot = t.optimized(); - QList terms; - if ( ot.type() == type() ) { - terms = static_cast( ot ).subTerms(); - } - else if( ot.isValid() ) { - terms += ot; - } - Q_FOREACH( const Nepomuk::Query::Term& t, terms ) { - if( !newSubTerms.contains( t ) ) - newSubTerms += t; - } - } - if ( newSubTerms.count() == 0 ) - return Nepomuk::Query::Term(); - else if ( newSubTerms.count() == 1 ) - return *newSubTerms.begin(); - else if ( isAndTerm() ) - return Nepomuk::Query::AndTerm( newSubTerms ); - else - return Nepomuk::Query::OrTerm( newSubTerms ); - } - - case Nepomuk::Query::Term::Negation: { - Nepomuk::Query::NegationTerm nt = toNegationTerm(); - // a negation in a negation - if( nt.subTerm().isNegationTerm() ) - return nt.subTerm().toNegationTerm().subTerm().optimized(); - else - return Nepomuk::Query::NegationTerm::negateTerm( nt.subTerm().optimized() ); - } - - case Nepomuk::Query::Term::Optional: { - Nepomuk::Query::OptionalTerm ot = toOptionalTerm(); - // remove duplicate optional terms - if( ot.subTerm().isOptionalTerm() ) - return ot.subTerm().optimized(); - else - return Nepomuk::Query::OptionalTerm::optionalizeTerm( ot.subTerm().optimized() ); - } - - case Nepomuk::Query::Term::Comparison: { - Nepomuk::Query::ComparisonTerm ct( toComparisonTerm() ); - ct.setSubTerm( ct.subTerm().optimized() ); - return ct; - } - - default: - return *this; - } -} - - -bool Nepomuk::Query::Term::isLiteralTerm() const -{ - return type() == Literal; -} - - -bool Nepomuk::Query::Term::isResourceTerm() const -{ - return type() == Resource; -} - - -bool Nepomuk::Query::Term::isNegationTerm() const -{ - return type() == Negation; -} - - -bool Nepomuk::Query::Term::isOptionalTerm() const -{ - return type() == Optional; -} - - -bool Nepomuk::Query::Term::isAndTerm() const -{ - return type() == And; -} - - -bool Nepomuk::Query::Term::isOrTerm() const -{ - return type() == Or; -} - - -bool Nepomuk::Query::Term::isComparisonTerm() const -{ - return type() == Comparison; -} - - -bool Nepomuk::Query::Term::isResourceTypeTerm() const -{ - return type() == ResourceType; -} - - -Nepomuk::Query::LiteralTerm Nepomuk::Query::Term::toLiteralTerm() const -{ - if ( isLiteralTerm() ) { - return *static_cast( this ); - } - else - return LiteralTerm(); -} - - -Nepomuk::Query::ResourceTerm Nepomuk::Query::Term::toResourceTerm() const -{ - if ( isResourceTerm() ) - return *static_cast( this ); - else - return ResourceTerm(); -} - - -Nepomuk::Query::NegationTerm Nepomuk::Query::Term::toNegationTerm() const -{ - if ( isNegationTerm() ) - return *static_cast( this ); - else - return NegationTerm(); -} - - -Nepomuk::Query::OptionalTerm Nepomuk::Query::Term::toOptionalTerm() const -{ - if ( isOptionalTerm() ) - return *static_cast( this ); - else - return OptionalTerm(); -} - - -Nepomuk::Query::AndTerm Nepomuk::Query::Term::toAndTerm() const -{ - if ( isAndTerm() ) - return *static_cast( this ); - else - return AndTerm(); -} - - -Nepomuk::Query::OrTerm Nepomuk::Query::Term::toOrTerm() const -{ - if ( isOrTerm() ) - return *static_cast( this ); - else - return OrTerm(); -} - - -Nepomuk::Query::ComparisonTerm Nepomuk::Query::Term::toComparisonTerm() const -{ - if ( isComparisonTerm() ) - return *static_cast( this ); - else - return ComparisonTerm(); -} - - -Nepomuk::Query::ResourceTypeTerm Nepomuk::Query::Term::toResourceTypeTerm() const -{ - if ( isResourceTypeTerm() ) - return *static_cast( this ); - else - return ResourceTypeTerm(); -} - - -#define CONVERT_AND_RETURN( Class ) \ - if ( !is##Class() ) \ - d_ptr = new Class##Private(); \ - return *static_cast( this ) - -Nepomuk::Query::LiteralTerm& Nepomuk::Query::Term::toLiteralTerm() -{ - CONVERT_AND_RETURN( LiteralTerm ); -} - - -Nepomuk::Query::ResourceTerm& Nepomuk::Query::Term::toResourceTerm() -{ - CONVERT_AND_RETURN( ResourceTerm ); -} - - -Nepomuk::Query::NegationTerm& Nepomuk::Query::Term::toNegationTerm() -{ - CONVERT_AND_RETURN( NegationTerm ); -} - - -Nepomuk::Query::OptionalTerm& Nepomuk::Query::Term::toOptionalTerm() -{ - CONVERT_AND_RETURN( OptionalTerm ); -} - - -Nepomuk::Query::AndTerm& Nepomuk::Query::Term::toAndTerm() -{ - CONVERT_AND_RETURN( AndTerm ); -} - - -Nepomuk::Query::OrTerm& Nepomuk::Query::Term::toOrTerm() -{ - CONVERT_AND_RETURN( OrTerm ); -} - - -Nepomuk::Query::ComparisonTerm& Nepomuk::Query::Term::toComparisonTerm() -{ - CONVERT_AND_RETURN( ComparisonTerm ); -} - - -Nepomuk::Query::ResourceTypeTerm& Nepomuk::Query::Term::toResourceTypeTerm() -{ - CONVERT_AND_RETURN( ResourceTypeTerm ); -} - - -QString Nepomuk::Query::Term::toString() const -{ - return Nepomuk::Query::serializeTerm( *this ); -} - - -// static -Nepomuk::Query::Term Nepomuk::Query::Term::fromString( const QString& s ) -{ - return Nepomuk::Query::parseTerm( s ); -} - - -// static -Nepomuk::Query::Term Nepomuk::Query::Term::fromVariant( const Variant& variant ) -{ - if( variant.isResource() ) { - return ResourceTerm( variant.toResource() ); - } - else if( !variant.isList() ) { - Soprano::LiteralValue v( variant.variant() ); - if( v.isValid() ) { - return LiteralTerm( v ); - } - } - - // fallback: invalid term - return Term(); -} - - -// static -Nepomuk::Query::Term Nepomuk::Query::Term::fromProperty( const Nepomuk::Types::Property& property, const Nepomuk::Variant& variant ) -{ - if( variant.isList() ) { - AndTerm andTerm; - Q_FOREACH( const Variant& v, variant.toVariantList() ) { - andTerm.addSubTerm( fromProperty(property, v) ); - } - return andTerm; - } - else { - return ComparisonTerm( property, Term::fromVariant(variant), ComparisonTerm::Equal ); - } -} - - -bool Nepomuk::Query::Term::operator==( const Term& other ) const -{ - return d_ptr->equals( other.d_ptr ); -} - - -bool Nepomuk::Query::Term::operator!=( const Term& other ) const -{ - return !d_ptr->equals( other.d_ptr ); -} - - -QDebug operator<<( QDebug dbg, const Nepomuk::Query::Term& term ) -{ - return term.operator<<( dbg ); -} - - -Nepomuk::Query::Term Nepomuk::Query::operator&&( const Term& term1, const Term& term2 ) -{ - QList terms; - if( term1.isAndTerm() ) - terms << term1.toAndTerm().subTerms(); - else if( term1.isValid() ) - terms << term1; - if( term2.isAndTerm() ) - terms << term2.toAndTerm().subTerms(); - else if( term2.isValid() ) - terms << term2; - - if( terms.count() == 1 ) - return terms.first(); - else if( terms.count() > 1 ) - return AndTerm( terms ); - else - return Term(); -} - - -Nepomuk::Query::Term Nepomuk::Query::operator||( const Term& term1, const Term& term2 ) -{ - QList terms; - if( term1.isOrTerm() ) - terms << term1.toOrTerm().subTerms(); - else if( term1.isValid() ) - terms << term1; - if( term2.isOrTerm() ) - terms << term2.toOrTerm().subTerms(); - else if( term2.isValid() ) - terms << term2; - - if( terms.count() == 1 ) - return terms.first(); - else if( terms.count() > 1 ) - return OrTerm( terms ); - else - return Term(); -} - - -Nepomuk::Query::Term Nepomuk::Query::operator!( const Nepomuk::Query::Term& term ) -{ - return NegationTerm::negateTerm( term ); -} - - -Nepomuk::Query::ComparisonTerm Nepomuk::Query::operator<( const Nepomuk::Types::Property& property, const Nepomuk::Query::Term& term ) -{ - return ComparisonTerm( property, term, ComparisonTerm::Smaller ); -} - - -Nepomuk::Query::ComparisonTerm Nepomuk::Query::operator>( const Nepomuk::Types::Property& property, const Nepomuk::Query::Term& term ) -{ - return ComparisonTerm( property, term, ComparisonTerm::Greater ); -} - - -Nepomuk::Query::ComparisonTerm Nepomuk::Query::operator<=( const Nepomuk::Types::Property& property, const Nepomuk::Query::Term& term ) -{ - return ComparisonTerm( property, term, ComparisonTerm::SmallerOrEqual ); -} - - -Nepomuk::Query::ComparisonTerm Nepomuk::Query::operator>=( const Nepomuk::Types::Property& property, const Nepomuk::Query::Term& term ) -{ - return ComparisonTerm( property, term, ComparisonTerm::GreaterOrEqual ); -} - - -Nepomuk::Query::ComparisonTerm Nepomuk::Query::operator==( const Nepomuk::Types::Property& property, const Nepomuk::Query::Term& term ) -{ - return ComparisonTerm( property, term, ComparisonTerm::Equal ); -} - - -Nepomuk::Query::Term Nepomuk::Query::operator!=( const Nepomuk::Types::Property& property, const Nepomuk::Query::Term& term ) -{ - return !( property == term ); -} - - -uint Nepomuk::Query::qHash( const Nepomuk::Query::Term& term ) -{ - switch( term.type() ) { - case Nepomuk::Query::Term::Literal: - return( qHash( term.toLiteralTerm().value().toString() ) ); - - case Nepomuk::Query::Term::Comparison: - return( qHash( term.toComparisonTerm().property().uri().toString() )<<24 | - qHash( term.toComparisonTerm().subTerm() )<<16 | - ( uint )term.toComparisonTerm().comparator()<<8 ); - - case Nepomuk::Query::Term::Negation: - return qHash(term.toNegationTerm().subTerm()); - - case Nepomuk::Query::Term::Optional: - return qHash(term.toOptionalTerm().subTerm()); - - case Nepomuk::Query::Term::Resource: - return qHash( term.toResourceTerm().resource().resourceUri() ); - - case Nepomuk::Query::Term::ResourceType: - return qHash( term.toResourceTypeTerm().type().uri() ); - - case Nepomuk::Query::Term::And: - case Nepomuk::Query::Term::Or: { - uint h = ( uint )term.type(); - QList subTerms = static_cast( term ).subTerms(); - for ( int i = 0; i < subTerms.count(); ++i ) { - h |= ( qHash( subTerms[i] )< Nepomuk::Query::TermPrivate* QSharedDataPointer::clone() -{ - return d->clone(); -} - - -QDebug Nepomuk::Query::Term::operator<<( QDebug dbg ) const -{ - return dbg << toString(); -} diff --git a/nepomuk/query/term.h b/nepomuk/query/term.h deleted file mode 100644 index f641e358..00000000 --- a/nepomuk/query/term.h +++ /dev/null @@ -1,593 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_SEARCH_TERM_H_ -#define _NEPOMUK_SEARCH_TERM_H_ - -#include -#include -#include - -#include - -#include "nepomukquery_export.h" - -namespace Nepomuk { - - class Variant; - - namespace Types { - class Property; - } - - namespace Query { - - class LiteralTerm; - class ResourceTerm; - class NegationTerm; - class AndTerm; - class OrTerm; - class ComparisonTerm; - class ResourceTypeTerm; - class OptionalTerm; - - class TermPrivate; - - /** - * \class Term term.h Nepomuk/Query/Term - * - * \brief The base class for all term types. - * - * Queries are build from Term instances. A Term can have one of multiple - * types and subterms. See Term::Type for details on the different Term types. - * - * \author Sebastian Trueg - * - * \since 4.4 - */ - class NEPOMUKQUERY_EXPORT Term - { - public: - /** - * The type of a term identifying its meaning. - * - * \sa type() - */ - enum Type { - /** - * An invalid term matching nothing - */ - Invalid, - - /** - * A literal term is the simplest form of %Term. It simply contains a literal - * value. - * - * \sa LiteralTerm - */ - Literal, - - /** - * A resource term matches one resource by URI. - * - * \sa ResourceTerm - */ - Resource, - - /** - * Match all resources that match all sub terms. - * - * \sa AndTerm - */ - And, - - /** - * Match all resources that match one of the sub terms. - * - * \sa OrTerm - */ - Or, - - /** - * A comparison. The comparison operator needs to be specified in addition. - * A single subterm specifies the resource or value to match. - * - * \sa ComparisonTerm - */ - Comparison, - - /** - * Matches all resources of a specific type. - * - * \sa ResourceTypeTerm - */ - ResourceType, - - /** - * A negation term inverts the meaning of its sub term. - * - * \sa NegationTerm - */ - Negation, - - /** - * An optional term which marks its sub term as optional. - * - * \sa OptionalTerm - * - * \since 4.5 - */ - Optional - }; - - /** - * Constructs an invalid term. - */ - Term(); - - /** - * Copy constructor. - */ - Term( const Term& other ); - - /** - * Destructor - */ - ~Term(); - - /** - * Copy operator. - */ - Term& operator=( const Term& other ); - - /** - * \return \p true if the term is valid. A valid - * term can be used to construct a Query. - */ - bool isValid() const; - - /** - * \return the Term type. - */ - Type type() const; - - /** - * Optimizes the term without changing its meaning. This removes - * redundant terms such as NegationTerm and OptionalTerm nestings and flattens - * AndTerm and OrTerm hierarchies. - * - * \return An optimized version of this term. - * - * \since 4.6 - * - * \sa Query::optimized() - */ - Term optimized() const; - - /** - * \return \p true if this term is a LiteralTerm. - */ - bool isLiteralTerm() const; - - /** - * \return \p true if this term is a ResourceTerm. - */ - bool isResourceTerm() const; - - /** - * \return \p true if this term is a NegationTerm. - */ - bool isNegationTerm() const; - - /** - * \return \p true if this term is a OptionalTerm. - * - * \since 4.5 - */ - bool isOptionalTerm() const; - - /** - * \return \p true if this term is an AndTerm. - */ - bool isAndTerm() const; - - /** - * \return \p true if this term is an OrTerm. - */ - bool isOrTerm() const; - - /** - * \return \p true if this term is a ComparisonTerm. - */ - bool isComparisonTerm() const; - - /** - * \return \p true if this term is a ResourceTypeTerm. - */ - bool isResourceTypeTerm() const; - - /** - * Interpret this term as a LiteralTerm. - * - * \return A copy of this term if its type - * is Literal, a new LiteralTerm otherwise. - */ - LiteralTerm toLiteralTerm() const; - - /** - * Interpret this term as a ResourceTerm. - * - * \return A copy of this term if its type - * is Resource, a new ResourceTerm otherwise. - */ - ResourceTerm toResourceTerm() const; - - /** - * Interpret this term as a NegationTerm. - * - * \return A copy of this term if its type - * is Negation, a new NegationTerm otherwise. - */ - NegationTerm toNegationTerm() const; - - /** - * Interpret this term as a OptionalTerm. - * - * \return A copy of this term if its type - * is Optional, a new OptionalTerm otherwise. - * - * \since 4.5 - */ - OptionalTerm toOptionalTerm() const; - - /** - * Interpret this term as a AndTerm. - * - * \return A copy of this term if its type - * is And, a new AndTerm otherwise. - */ - AndTerm toAndTerm() const; - - /** - * Interpret this term as a OrTerm. - * - * \return A copy of this term if its type - * is Or, a new OrTerm otherwise. - */ - OrTerm toOrTerm() const; - - /** - * Interpret this term as a ComparisonTerm. - * - * \return A copy of this term if its type - * is Comparison, a new ComparisonTerm otherwise. - */ - ComparisonTerm toComparisonTerm() const; - - /** - * Interpret this term as a ResourceTypeTerm. - * - * \return A copy of this term if its type - * is ClassType, a new ResourceTypeTerm otherwise. - */ - ResourceTypeTerm toResourceTypeTerm() const; - - /** - * Convert this term into a LiteralTerm. - * If type is not Literal it will be changed - * and the result is a new LiteralTerm. - * - * \return A reference to this term as a LiteralTerm. - */ - LiteralTerm& toLiteralTerm(); - - /** - * Convert this term into a ResourceTerm. - * If type is not Resource it will be changed - * and the result is a new ResourceTerm. - * - * \return A reference to this term as a ResourceTerm. - */ - ResourceTerm& toResourceTerm(); - - /** - * Convert this term into a NegationTerm. - * If type is not Negation it will be changed - * and the result is a new NegationTerm. - * - * \return A reference to this term as a NegationTerm. - */ - NegationTerm& toNegationTerm(); - - /** - * Convert this term into a OptionalTerm. - * If type is not Optional it will be changed - * and the result is a new OptionalTerm. - * - * \return A reference to this term as a OptionalTerm. - * - * \since 4.5 - */ - OptionalTerm& toOptionalTerm(); - - /** - * Convert this term into a AndTerm. - * If type is not And it will be changed - * and the result is a new AndTerm. - * - * \return A reference to this term as a AndTerm. - */ - AndTerm& toAndTerm(); - - /** - * Convert this term into a OrTerm. - * If type is not Or it will be changed - * and the result is a new OrTerm. - * - * \return A reference to this term as a OrTerm. - */ - OrTerm& toOrTerm(); - - /** - * Convert this term into a ComparisonTerm. - * If type is not Comparison it will be changed - * and the result is a new ComparisonTerm. - * - * \return A reference to this term as a ComparisonTerm. - */ - ComparisonTerm& toComparisonTerm(); - - /** - * Convert this term into a ResourceTypeTerm. - * If type is not ClassType it will be changed - * and the result is a new ResourceTypeTerm. - * - * \return A reference to this term as a ResourceTypeTerm. - */ - ResourceTypeTerm& toResourceTypeTerm(); - - /** - * Encode the Term in a string. Be aware that this does NOT create a SPARQL - * query. The returned string can be used to serialize terms that can later - * be read via fromString(). - * - * \sa fromString() - * - * \since 4.5 - */ - QString toString() const; - - /** - * Parse a Term that has been encoded as a string via toString(). - * - * \warning This method can NOT parse SPARQL syntax. - * - * \sa toString() - * - * \since 4.5 - */ - static Term fromString( const QString& s ); - - /** - * Construct a Term from a Variant value. This is a convenience method - * that simplifies handling Nepomuk values. However, list variants are - * not supported and will result in an invalid Term. - * - * \return A ResourceTerm in case \p variant is a resource, a LiteralTerm - * if \p variant is a supported literal value, or an invalid Term if \p - * variant is invalid or a list. - * - * \since 4.6 - */ - static Term fromVariant( const Variant& variant ); - - /** - * Create a term using a Types::Property and a Variant. Sadly this cannot be modelled - * as an operator since it would clash with Entity::operator==(). - * - * \param property The property to be used in the ComparisonTerm. - * \param variant The value to be compared to. Either ResourceTerm or LiteralTerm is used. List - * variants (Variant::isList()) are handled via an AndTerm meaning all values need to match. - * - * \since 4.6 - * - * \relates ComparisonTerm - */ - static Term fromProperty( const Types::Property& property, const Variant& variant ); - - /** - * Comparison operator. - * - * \return \p true if this term is equal to \p term. - */ - bool operator==( const Term& term ) const; - - /** - * Comparison operator. - * - * \return \p true if this term differs from \p term. - * - * \since 4.6 - */ - bool operator!=( const Term& term ) const; - - // FIXME: the compiler does not find this operator! - QDebug operator<<( QDebug ) const; - - /** \cond protected_term_members */ - protected: - Term( TermPrivate* ); - - QSharedDataPointer d_ptr; - - friend class TermPrivate; - friend class GroupTermPrivate; - friend class AndTermPrivate; - friend class OrTermPrivate; - friend class ComparisonTermPrivate; - friend class NegationTermPrivate; - friend class OptionalTermPrivate; - friend class Query; - friend class QueryPrivate; - /** \endcond */ - }; - - /** - * Logical and operator which combines two terms into - * one term matching both \p term1 and \p term2. - * - * \relates AndTerm - * - * \since 4.6 - */ - NEPOMUKQUERY_EXPORT Term operator&&( const Term& term1, const Term& term2 ); - - /** - * Logical or operator which combines two terms into - * one term matching either \p term1 or \p term2. - * - * \relates OrTerm - * - * \since 4.6 - */ - NEPOMUKQUERY_EXPORT Term operator||( const Term& term1, const Term& term2 ); - - /** - * Logical negation operator which negates the meaning of - * one term. - * - * \sa NegationTerm::negateTerm() - * \relates NegationTerm - * - * \since 4.6 - */ - NEPOMUKQUERY_EXPORT Term operator!( const Term& term ); - - /** - * Comparision operator for simple creation of ComparisonTerm objects using the - * ComparisonTerm::Smaller comparator. - * - * \return A ComparisonTerm equvalent to: - * - * \code - * ComparisonTerm( property, term, ComparisonTerm::Smaller ); - * \endcode - * - * \since 4.6 - * - * \relates ComparisonTerm - */ - NEPOMUKQUERY_EXPORT ComparisonTerm operator<( const Types::Property& property, const Term& term ); - - /** - * Comparision operator for simple creation of ComparisonTerm objects using the - * ComparisonTerm::Greater comparator. - * - * \return A ComparisonTerm equvalent to: - * - * \code - * ComparisonTerm( property, term, ComparisonTerm::Greater ); - * \endcode - * - * \since 4.6 - * - * \relates ComparisonTerm - */ - NEPOMUKQUERY_EXPORT ComparisonTerm operator>( const Types::Property& property, const Term& term ); - - /** - * Comparision operator for simple creation of ComparisonTerm objects using the - * ComparisonTerm::SmallerOrEqual comparator. - * - * \return A ComparisonTerm equvalent to: - * - * \code - * ComparisonTerm( property, term, ComparisonTerm::SmallerOrEqual ); - * \endcode - * - * \since 4.6 - * - * \relates ComparisonTerm - */ - NEPOMUKQUERY_EXPORT ComparisonTerm operator<=( const Types::Property& property, const Term& term ); - - /** - * Comparision operator for simple creation of ComparisonTerm objects using the - * ComparisonTerm::GreaterOrEqual comparator. - * - * \return A ComparisonTerm equvalent to: - * - * \code - * ComparisonTerm( property, term, ComparisonTerm::GreaterOrEqual ); - * \endcode - * - * \since 4.6 - * - * \relates ComparisonTerm - */ - NEPOMUKQUERY_EXPORT ComparisonTerm operator>=( const Types::Property& property, const Term& term ); - - /** - * Comparision operator for simple creation of ComparisonTerm objects using the - * ComparisonTerm::Equal comparator. - * - * \return A ComparisonTerm equvalent to: - * - * \code - * ComparisonTerm( property, term, ComparisonTerm::Equal ); - * \endcode - * - * \since 4.6 - * - * \relates ComparisonTerm - */ - NEPOMUKQUERY_EXPORT ComparisonTerm operator==( const Types::Property& property, const Term& term ); - - /** - * Comparision operator for simple creation of negated ComparisionTerm objects using the - * ComparisonTerm::Equal comparator. - * - * \since 4.6 - * - * \return A Term equvalent to: - * - * \code - * NegationTerm::negateTerm( ComparisonTerm( property, term, ComparisonTerm::Equal ) ); - * \endcode - * - * \relates ComparisonTerm - * - * \sa NegationTerm - */ - NEPOMUKQUERY_EXPORT Term operator!=( const Types::Property& property, const Term& term ); - - NEPOMUKQUERY_EXPORT uint qHash( const Nepomuk::Query::Term& ); - } - -} - -/** \cond hide_nepomuk_term_clone_from_doxygen */ -// there is a hand written instantiation of clone() -template<> Nepomuk::Query::TermPrivate* QSharedDataPointer::clone(); -/** \endcond */ - -// FIXME: the compiler does not find the operator in the class -NEPOMUKQUERY_EXPORT QDebug operator<<( QDebug, const Nepomuk::Query::Term& ); - -#endif diff --git a/nepomuk/query/term_p.h b/nepomuk/query/term_p.h deleted file mode 100644 index 32bc6701..00000000 --- a/nepomuk/query/term_p.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_SEARCH_TERM_P_H_ -#define _NEPOMUK_SEARCH_TERM_P_H_ - -#include - -#include "term.h" - -namespace Nepomuk { - namespace Query { - - class QueryBuilderData; - - class TermPrivate : public QSharedData - { - public: - TermPrivate( Term::Type t = Term::Invalid ) - : m_type( t ) { - } - virtual ~TermPrivate() { - } - - virtual TermPrivate* clone() const { return new TermPrivate( *this ); } - - virtual bool isValid() const { return false; } - virtual QString toSparqlGraphPattern( const QString&, const TermPrivate*, const QString&, QueryBuilderData* ) const { return QString(); } - virtual bool equals( const TermPrivate* other ) const { - return m_type == other->m_type; - } - - Term::Type m_type; - }; - } -} - -#define N_D(Class) Class##Private* d = static_cast( d_ptr.data() ) -#define N_D_CONST(Class) const Class##Private* d = static_cast( d_ptr.constData() ) - -#endif diff --git a/nepomuk/query/util.h b/nepomuk/query/util.h deleted file mode 100644 index 90028130..00000000 --- a/nepomuk/query/util.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License version 2 as published by the Free Software Foundation. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_QUERY_UTILS_H_ -#define _NEPOMUK_QUERY_UTILS_H_ - -#include -#include - -template -bool compareQList( const QList& rp1, const QList& rp2 ) { - if( rp1.count() != rp2.count() ) - return false; - foreach( const T& rp, rp1 ) { - if ( !rp2.contains( rp ) ) { - return false; - } - } - return true; -} - -template -bool compareHash( const QHash& h1, const QHash& h2 ) { - if( h1.count() != h2.count() ) - return false; - for( typename QHash::ConstIterator it1 = h1.constBegin(); - it1 != h1.constEnd(); ++it1 ) { - typename QHash::ConstIterator it2 = h2.find( it1.key() ); - if( it2 == h2.constEnd() || - *it1 != *it2 ) - return false; - } - return true; -} - -#endif diff --git a/nepomuk/rcgen/CMakeLists.txt b/nepomuk/rcgen/CMakeLists.txt deleted file mode 100644 index 11be8024..00000000 --- a/nepomuk/rcgen/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -project(nepomuk_rcgen) - -include_directories( - ${nepomuk_rcgen_SOURCE_DIR} - ${KDE4_KDEUI_INCLUDES} - ${QT_INCLUDES} - ${SOPRANO_INCLUDE_DIR} ) - -set(nepomuk_rcgen_SRCS - codegenerator.cpp - fastcode.cpp - property.cpp - rcgen.cpp - resourceclass.cpp - safecode.cpp - ontologyparser.cpp) - -qt4_add_resources(nepomuk_rcgen_SRCS templates.qrc) -kde4_add_executable(nepomuk-rcgen NOGUI ${nepomuk_rcgen_SRCS}) -target_link_libraries(nepomuk-rcgen - ${QT_QTCORE_LIBRARY} - ${QT_QTDBUS_LIBRARY} - ${SOPRANO_LIBRARIES} - kdecore - kdeui -) - -install(TARGETS nepomuk-rcgen ${INSTALL_TARGETS_DEFAULT_ARGS} ) diff --git a/nepomuk/rcgen/abstractcode.h b/nepomuk/rcgen/abstractcode.h deleted file mode 100644 index 04c2d8b6..00000000 --- a/nepomuk/rcgen/abstractcode.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#ifndef _NEPOMUK_ABSTRACTCODE_H_ -#define _NEPOMUK_ABSTRACTCODE_H_ - -#include - -class Property; -class ResourceClass; - -/** - * @short A class that encapsulates the definition generation methods. - * - * This class encapsulates the code generation for the definitions of - * the resource and property getter and setter methods. - */ -class AbstractCode -{ - public: - virtual ~AbstractCode() {} - - /** - * Returns the declaration of the property setter method. - * - * @param property The property to work on. - * @param resourceClass The resource the property belongs to. - * @param withNamespace Whether the namespace shall be included or not. - */ - virtual QString propertySetterDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const = 0; - - /** - * Returns the declaration of the property getter method. - * - * @param property The property to work on. - * @param resourceClass The resource the property belongs to. - * @param withNamespace Whether the namespace shall be included or not. - */ - virtual QString propertyGetterDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const = 0; - - /** - * Returns the declaration of the property adder method. - * - * @param property The property to work on. - * @param resourceClass The resource the property belongs to. - * @param withNamespace Whether the namespace shall be included or not. - */ - virtual QString propertyAdderDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const = 0; - - /** - * Returns the declaration of the property for the reverse property getter method. - * - * @param property The property to work on. - * @param resourceClass The resource the property belongs to. - * @param withNamespace Whether the namespace shall be included or not. - */ - virtual QString propertyReversePropertyGetterDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const = 0; - - /** - * Returns the declaration of the resource method that returns all resources. - * - * @param resourceClass The resource to work on. - * @param withNamespace Whether the namespace shall be included or not. - */ - virtual QString resourceAllResourcesDeclaration( const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const = 0; - - /** - * Returns the declaration of the resource method that provides pseudo inheritance. - * - * @param resourceBaseClass The resource to work on. - * @param resourceClass The resource to cast to. - * @param withNamespace Whether the namespace shall be included or not. - */ - virtual QString resourcePseudoInheritanceDeclaration( const ResourceClass* resourceBaseClass, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const = 0; - - /** - * Returns the definition of the property setter method. - * - * @param property The property to work on. - * @param resourceClass The resource the property belongs to. - */ - virtual QString propertySetterDefinition( const Property *property, - const ResourceClass* resourceClass ) const = 0; - - /** - * Returns the definition of the property getter method. - * - * @param property The property to work on. - * @param resourceClass The resource the property belongs to. - */ - virtual QString propertyGetterDefinition( const Property *property, - const ResourceClass* resourceClass ) const = 0; - - /** - * Returns the definition of the property adder method. - * - * @param property The property to work on. - * @param resourceClass The resource the property belongs to. - */ - virtual QString propertyAdderDefinition( const Property *property, - const ResourceClass* resourceClass ) const = 0; - - /** - * Returns the definition of the property for the reverse property getter method. - * - * @param property The property to work on. - * @param resourceClass The resource the property belongs to. - */ - virtual QString propertyReversePropertyGetterDefinition( const Property *property, - const ResourceClass* resourceClass ) const = 0; - - /** - * Returns the definition of the resource method that returns all resources. - * - * @param resourceClass The resource to work on. - */ - virtual QString resourceAllResourcesDefinition( const ResourceClass* resourceClass ) const = 0; - - /** - * Returns the definition of the resource method that provides pseudo inheritance. - * - * @param resourceBaseClass The resource to work on. - * @param resourceClass The resource to cast to. - */ - virtual QString resourcePseudoInheritanceDefinition( const ResourceClass* resourceBaseClass, - const ResourceClass* resourceClass ) const = 0; -}; - -#endif diff --git a/nepomuk/rcgen/codegenerator.cpp b/nepomuk/rcgen/codegenerator.cpp deleted file mode 100644 index 1bb2736e..00000000 --- a/nepomuk/rcgen/codegenerator.cpp +++ /dev/null @@ -1,510 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2009 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#include "codegenerator.h" - -#include "abstractcode.h" -#include "fastcode.h" -#include "property.h" -#include "resourceclass.h" -#include "safecode.h" - -#include -#include -#include -#include -#include -#include -#include - - -extern bool quiet; - -static QString headerTemplate( CodeGenerator::Mode mode ) -{ - QFile gplFile( ":gpl.tpl" ); - gplFile.open( QIODevice::ReadOnly ); - - QFile headerFile( QString::fromLatin1( ":header_%1.tpl" ) - .arg( mode == CodeGenerator::SafeMode ? QLatin1String( "safe" ) : QLatin1String( "fast" ) ) ); - headerFile.open( QIODevice::ReadOnly ); - - QString result = QString::fromLatin1( gplFile.readAll() ); - result += QString::fromLatin1( headerFile.readAll() ); - - return result; -} - -static QString sourceTemplate( CodeGenerator::Mode mode ) -{ - QFile gplFile( ":gpl.tpl" ); - gplFile.open( QIODevice::ReadOnly ); - - QFile sourceFile( QString::fromLatin1( ":source_%1.tpl" ) - .arg( mode == CodeGenerator::SafeMode ? QLatin1String( "safe" ) : QLatin1String( "fast" ) ) ); - sourceFile.open( QIODevice::ReadOnly ); - - QString result = QString::fromLatin1( gplFile.readAll() ); - result += QString::fromLatin1( sourceFile.readAll() ); - - return result; -} - -static QString writeComment( const QString& comment, int indent ) -{ - static const int maxLine = 50; - - QString s; - - if( !comment.isEmpty() ) { - s += QString().fill( ' ', indent ); - s += "/**\n" - + QString().fill( ' ', indent+1 ) - + "* "; - - QStringList words = comment.split( QRegExp("\\s"), QString::SkipEmptyParts ); - int cnt = 0; - for( int i = 0; i < words.count(); ++i ) { - if( cnt >= maxLine ) { - s += '\n' - + QString().fill( ' ', indent+1 ) - + "* "; - cnt = 0; - } - - s += words[i] + ' '; - cnt += words[i].length(); - } - - if( cnt > 0 ) - s += '\n'; - s += QString().fill( ' ', indent+1 ) - + "*/"; - } - - return s; -} - -CodeGenerator::CodeGenerator( Mode mode, const QList& classes ) - : m_mode( mode ), - m_classes( classes ) -{ - if ( m_mode == SafeMode ) { - m_code = new SafeCode; - m_nameSpace = QLatin1String("Nepomuk"); - } else { - m_code = new FastCode; - m_nameSpace = QLatin1String("NepomukFast"); - } -} - -CodeGenerator::~CodeGenerator() -{ - delete m_code; -} - -bool CodeGenerator::write( const ResourceClass* resourceClass, const QString& folder ) const -{ - QFile f( folder + resourceClass->headerName() ); - if( !f.open( QIODevice::WriteOnly ) ) - return false; - - QTextStream s( &f ); - if( !writeHeader( resourceClass, s ) ) - return false; - - f.close(); - - f.setFileName( folder + resourceClass->sourceName() ); - if( !f.open( QIODevice::WriteOnly ) ) - return false; - - if( !writeSource( resourceClass, s ) ) - return false; - - return true; -} - -bool CodeGenerator::writeDummyClasses( const QString &folder ) const -{ - if ( m_mode == FastMode ) { - QFile headerOutput( folder + "resource.h" ); - if ( !headerOutput.open( QIODevice::WriteOnly ) ) - return false; - - QFile sourceOutput( folder + "resource.cpp" ); - if ( !sourceOutput.open( QIODevice::WriteOnly ) ) - return false; - - QFile headerInput( ":dummyresource_header_fast.tpl" ); - headerInput.open( QIODevice::ReadOnly ); - - QFile sourceInput( ":dummyresource_source_fast.tpl" ); - sourceInput.open( QIODevice::ReadOnly ); - - headerOutput.write( headerInput.readAll() ); - sourceOutput.write( sourceInput.readAll() ); - } - - return true; -} - -bool CodeGenerator::writeHeader( const ResourceClass *resourceClass, QTextStream& stream ) const -{ - QString s = headerTemplate( m_mode ); - ResourceClass* parent = resourceClass->parentClass( true ); - s.replace( "NEPOMUK_VISIBILITY_HEADER_INCLUDE", visibilityHeader() ); - s.replace( "NEPOMUK_VISIBILITY", visibilityExportMacro() ); - s.replace( "NEPOMUK_RESOURCECOMMENT", writeComment( resourceClass->comment(), 4 ) ); - s.replace( "NEPOMUK_RESOURCENAMEUPPER", resourceClass->name().toUpper() ); - s.replace( "NEPOMUK_RESOURCENAME", resourceClass->name() ); - if ( m_mode == FastMode && parent->name() == "Resource" ) - s.replace( "NEPOMUK_PARENTRESOURCE", "NepomukFast::Resource" ); - else - s.replace( "NEPOMUK_PARENTRESOURCE", parent->name() ); - - // A resource that is not part of the currently generated stuff is supposed - // to be installed in include/nepomuk - if ( parent->generateClass() ) { - s.replace( "NEPOMUK_PARENT_INCLUDE", QString("\"%1.h\"").arg( parent->name().toLower() ) ); - } - else { - if ( m_mode == SafeMode ) - s.replace( "NEPOMUK_PARENT_INCLUDE", QString("").arg( parent->name().toLower() ) ); - else - s.replace( "NEPOMUK_PARENT_INCLUDE", QString("\"resource.h\"") ); - } - - QString methods; - QTextStream ms( &methods ); - QSet includes; - - QListIterator it( resourceClass->allProperties() ); - while( it.hasNext() ) { - const Property* p = it.next(); - - if( p->maxCardinality() == 1 || p->cardinality() == 1 ) { - Property * prop = const_cast(p); - bool isList = prop->isList(); - - prop->setIsList( true ); - if( !writePropertyHeader( prop, resourceClass, ms ) ) - continue; - - prop->setIsList( false ); - if( !writePropertyHeader( prop, resourceClass, ms ) ) - continue; - - writePropertyUriHeader( prop, ms ); - - prop->setIsList( isList ); - } - else { - if( !writePropertyHeader( p, resourceClass, ms ) ) - continue; - writePropertyUriHeader( p, ms ); - } - - if( !p->hasSimpleType() ) - includes.insert( p->typeString( true ) ); - } - - - it = resourceClass->allReverseProperties(); - while( it.hasNext() ) { - const Property* p = it.next(); - - if( p->literalRange().isEmpty() && - !p->range() ) { - if ( !quiet ) - qDebug() << "(CodeGenerator::writeSource) type not defined for property: " << p->name() << endl; - continue; - } - - if ( p->inverseProperty() ) { - // we already define a reverse property. So leave the generated one out - continue; - } - - if ( m_mode == SafeMode ) { - ms << writeComment( QString("Get all resources that have this resource set as property '%1'. ") - .arg(p->name()) + p->comment() + QString(" \\sa ResourceManager::allResourcesWithProperty"), 2*4 ) << endl; - ms << " " << m_code->propertyReversePropertyGetterDeclaration( p, resourceClass ) << ";" << endl; - ms << endl; - } - - if( !p->hasSimpleType() ) - includes.insert( p->domain(true)->name() ); - } - - - // - // Nepomuk does not support multiple inheritance - // So we have to use a workaround instead (we even include the one class used as "proper" superclass - // since the order of the super classes is not deterministic and may change with a different serialization) - // - if( resourceClass->allParentResources().count() > 1 ) { - foreach( ResourceClass* rc, resourceClass->allParentResources() ) { - // ignore the one we derived from - if( rc->generateClass() ) { - const QString decl = m_code->resourcePseudoInheritanceDeclaration( resourceClass, rc ); - if ( decl.isEmpty() ) - continue; - ms << writeComment( QString("Nepomuk does not support multiple inheritance. Thus, to access " - "properties from all parent classes helper methods like this are " - "introduced. The object returned represents the exact same resource."), 2*4 ) << endl - << " " << decl << ";" << endl << endl; - - includes.insert( rc->name() ); - } - } - } - - if ( m_mode == SafeMode ) { - ms << writeComment( QString("Retrieve a list of all available %1 resources. " - "This list consists of all resource of type %1 that are stored " - "in the local Nepomuk meta data storage and any changes made locally. " - "Be aware that in some cases this list can get very big. Then it might " - "be better to use libKNep directly.").arg( resourceClass->name() ), 2*4 ) << endl; - ms << " static " << m_code->resourceAllResourcesDeclaration( resourceClass ) << ";" << endl; - } - - QString includeString; - QSetIterator includeIt( includes ); - while( includeIt.hasNext() ) { - includeString += " class " + includeIt.next() + ";\n"; - } - - s.replace( "NEPOMUK_OTHERCLASSES", includeString ); - s.replace( "NEPOMUK_METHODS", methods ); - - stream << s; - - return true; -} - -bool CodeGenerator::writePropertyHeader(const Property* p, const ResourceClass* resourceClass, QTextStream& ms) const -{ - if( p->literalRange().isEmpty() && - !p->range() ) { - if ( !quiet ) - qDebug() << "(CodeGenerator::writeSource) type not defined for property: " << p->name() << endl; - return false; - } - - if ( m_mode == SafeMode ) { - ms << writeComment( QString("Get property '%1'. ").arg(p->name()) + p->comment(), 2*4 ) << endl; - ms << " " << m_code->propertyGetterDeclaration( p, resourceClass ) << ";" << endl; - ms << endl; - } - - ms << writeComment( QString("Set property '%1'. ").arg(p->name()) + p->comment(), 2*4 ) << endl; - ms << " " << m_code->propertySetterDeclaration( p, resourceClass ) << ";" << endl; - ms << endl; - - if( p->isList() ) { - ms << writeComment( QString("Add a value to property '%1'. ").arg(p->name()) + p->comment(), 2*4 ) << endl; - ms << " " << m_code->propertyAdderDeclaration( p, resourceClass ) << ";" << endl; - ms << endl; - } - - return true; -} - -void CodeGenerator::writePropertyUriHeader(const Property* p, QTextStream& ts) const -{ - ts << writeComment( QString( "\\return The URI of the property '%1'." ).arg( p->name() ), 2*4 ) << endl; - ts << " " << "static QUrl " << p->name()[0].toLower() << p->name().mid(1) << "Uri();" << endl; - ts << endl; -} - - -bool CodeGenerator::writeSource( const ResourceClass* resourceClass, QTextStream& stream ) const -{ - QString s = sourceTemplate( m_mode ); - s.replace( "NEPOMUK_RESOURCENAMELOWER", resourceClass->name().toLower() ); - s.replace( "NEPOMUK_RESOURCENAME", resourceClass->name() ); - s.replace( "NEPOMUK_RESOURCETYPEURI", resourceClass->uri().toString() ); - if ( m_mode == FastMode && resourceClass->parentClass()->name() == "Resource" ) - s.replace( "NEPOMUK_PARENTRESOURCE", "NepomukFast::Resource" ); - else - s.replace( "NEPOMUK_PARENTRESOURCE", resourceClass->parentClass()->name() ); - - QString methods; - QStringList includes; - QTextStream ms( &methods ); - - QListIterator it( resourceClass->allProperties() ); - while( it.hasNext() ) { - const Property* p = it.next(); - - if( p->maxCardinality() == 1 || p->cardinality() == 1 ) { - Property * prop = const_cast(p); - bool isList = prop->isList(); - - prop->setIsList( true ); - if( !writePropertySource( prop, resourceClass, ms ) ) - continue; - - prop->setIsList( false ); - if( !writePropertySource( prop, resourceClass, ms ) ) - continue; - - writePropertyUriSource( prop, resourceClass, ms ); - - prop->setIsList( isList ); - } - else { - if( !writePropertySource( p, resourceClass, ms ) ) - continue; - writePropertyUriSource( p, resourceClass, ms ); - } - - if ( !p->hasSimpleType() ) { - includes.append( QString( "#include \"%1.h\"" ).arg( p->typeString( true ).toLower() ) ); - } - } - - it = resourceClass->allReverseProperties(); - while( it.hasNext() ) { - const Property* p = it.next(); - - if( p->literalRange().isEmpty() && - !p->range() ) { - if ( !quiet ) - qDebug() << "(CodeGenerator::writeSource) type not defined for property: " << p->name() << endl; - continue; - } - - if ( p->inverseProperty() ) { - // we already define a reverse property. So leave the generated one out - continue; - } - - if ( m_mode == SafeMode ) - ms << m_code->propertyReversePropertyGetterDefinition( p, resourceClass ) << endl; - - includes.append( QString( "#include \"%1\"" ).arg( p->domain(true)->headerName() ) ); - } - - // - // Nepomuk does not support multiple inheritance - // So we have to use a workaround instead (we even include the one class used as "proper" superclass - // since the order of the super classes is not deterministic and may change with a different serialization) - // - if( resourceClass->allParentResources().count() > 1 ) { - foreach( ResourceClass* rc, resourceClass->allParentResources() ) { - // ignore the one we derived from - if( rc->generateClass() ) { - ms << m_code->resourcePseudoInheritanceDefinition( resourceClass, rc ) << endl; - includes.append( QString("#include \"%1.h\"").arg( rc->name().toLower() ) ); - } - } - } - - if ( m_mode == SafeMode ) - ms << m_code->resourceAllResourcesDefinition( resourceClass ) << endl; - - // HACK: remove duplicates and resource include - includes = includes.toSet().toList(); - includes.removeAll( "#include \"resource.h\"" ); - - s.replace( "NEPOMUK_METHODS", methods ); - s.replace( "NEPOMUK_INCLUDES", includes.join( "\n" ) ); - - stream << s; - - return true; -} - -bool CodeGenerator::writePropertySource(const Property* p, const ResourceClass* resourceClass, QTextStream& ms) const -{ - if( p->literalRange().isEmpty() && !p->range() ) { - if ( !quiet ) - qDebug() << "(CodeGenerator::writeSource) type not defined for property: " << p->name() << endl; - return false; - } - - if ( m_mode == SafeMode ) - ms << m_code->propertyGetterDefinition( p, resourceClass ) << endl; - - ms << m_code->propertySetterDefinition( p, resourceClass ) << endl; - if( p->isList() ) - ms << m_code->propertyAdderDefinition( p, resourceClass ) << endl; - - return true; -} - -void CodeGenerator::writePropertyUriSource(const Property* p, const ResourceClass* resourceClass, QTextStream& ts) const -{ - // write the static method that returns the property's Uri - ts << "QUrl " << resourceClass->name( m_nameSpace ) << "::" << p->name()[0].toLower() << p->name().mid(1) << "Uri()" << endl - << "{" << endl - << " return QUrl::fromEncoded(\"" << p->uri().toString() << "\");" << endl - << "}" << endl << endl; -} - -bool CodeGenerator::writeSources( const QString& dir ) -{ - bool success = true; - - foreach( ResourceClass* rc, classes() ) { - if( rc->generateClass() ) - success &= write( rc, dir + QDir::separator() ); - } - - writeDummyClasses( dir + QDir::separator() ); - - return success; -} - - -QStringList CodeGenerator::listHeader() -{ - QStringList l; - foreach( ResourceClass* rc, classes() ) { - if( rc->generateClass() ) - l.append( rc->headerName() ); - } - return l; -} - - -QStringList CodeGenerator::listSources() -{ - QStringList l; - foreach( ResourceClass* rc, classes() ) { - if( rc->generateClass() ) - l.append( rc->sourceName() ); - } - return l; -} - - -QString CodeGenerator::visibilityHeader() const -{ - if( m_visibility.isEmpty() ) - return QString(); - else - return "#include \"" + m_visibility.toLower() + "_export.h\""; -} - - -QString CodeGenerator::visibilityExportMacro() const -{ - if( m_visibility.isEmpty() ) - return QString(); - else - return m_visibility.toUpper() + "_EXPORT"; -} diff --git a/nepomuk/rcgen/codegenerator.h b/nepomuk/rcgen/codegenerator.h deleted file mode 100644 index f26a8753..00000000 --- a/nepomuk/rcgen/codegenerator.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#ifndef _NEPOMUK_CODE_GENERATOR_H_ -#define _NEPOMUK_CODE_GENERATOR_H_ - -#include -#include - -class AbstractCode; -class ResourceClass; -class QString; -class QTextStream; -class Property; - -class CodeGenerator -{ -public: - enum Mode { - SafeMode, - FastMode - }; - - CodeGenerator( Mode mode, const QList& classes ); - ~CodeGenerator(); - - void setVisibility( const QString& v ) { m_visibility = v; } - - QList classes() const { return m_classes; } - - QStringList listHeader(); - QStringList listSources(); - bool writeSources( const QString& dir ); - -private: - bool write( const ResourceClass* resourceClass, const QString& folder ) const; - bool writeHeader( const ResourceClass* resourceClass, QTextStream& ) const; - bool writeSource( const ResourceClass* resourceClass, QTextStream& ) const; - bool writeDummyClasses( const QString &folder ) const; - - bool writePropertyHeader( const Property* p, const ResourceClass* resourceClass, QTextStream& ms ) const; - bool writePropertySource( const Property* p, const ResourceClass* resourceClass, QTextStream& ms ) const; - - void writePropertyUriHeader( const Property* p, QTextStream& ts ) const; - void writePropertyUriSource( const Property* p, const ResourceClass* resourceClass, QTextStream& ts ) const; - - QString visibilityHeader() const; - QString visibilityExportMacro() const; - - ResourceClass* findParentClass( ResourceClass* resourceClass ) const; - - const Mode m_mode; - const AbstractCode* m_code; - QString m_nameSpace; - - QList m_classes; - QString m_visibility; -}; - -#endif diff --git a/nepomuk/rcgen/fastcode.cpp b/nepomuk/rcgen/fastcode.cpp deleted file mode 100644 index b5ec943d..00000000 --- a/nepomuk/rcgen/fastcode.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#include "fastcode.h" - -#include "property.h" -#include "resourceclass.h" - -QString FastCode::propertySetterDeclaration( const Property* property, const ResourceClass* rc, const QString &nameSpace ) const -{ - return QString( "void %1set%2%3%4( const %5& value )" ) - .arg( !nameSpace.isEmpty() ? QString("%1::%2::").arg(nameSpace).arg(rc->name()) : QString() ) - .arg( property->name()[0].toUpper() ) - .arg( property->name().mid(1) ) - .arg( property->isList() ? (property->name().endsWith('s') ? QLatin1String("es") : QLatin1String("s") ) : QString() ) - .arg( property->typeString( false, nameSpace ) ); -} - -QString FastCode::propertyGetterDeclaration( const Property* property, const ResourceClass* rc, const QString &nameSpace ) const -{ - Q_UNUSED( property ); - Q_UNUSED( rc ); - Q_UNUSED( nameSpace ); - return QString(); -} - -QString FastCode::propertyAdderDeclaration( const Property* property, const ResourceClass* rc, const QString &nameSpace ) const -{ - return QString( "void %1add%2%3( const %4& value )" ) - .arg( !nameSpace.isEmpty() ? QString("%1::%2::").arg(nameSpace).arg(rc->name()) : QString() ) - .arg( property->name()[0].toUpper() ) - .arg( property->name().mid(1) ) - .arg( property->typeString( true, nameSpace ) ); -} - -QString FastCode::propertyReversePropertyGetterDeclaration( const Property* property, const ResourceClass* rc, const QString &nameSpace ) const -{ - Q_UNUSED( property ); - Q_UNUSED( rc ); - Q_UNUSED( nameSpace ); - return QString(); -} - -QString FastCode::resourceAllResourcesDeclaration( const ResourceClass* rc, const QString &nameSpace ) const -{ - Q_UNUSED( rc ); - Q_UNUSED( nameSpace ); - return QString(); -} - -QString FastCode::resourcePseudoInheritanceDeclaration( const ResourceClass* baseRc, const ResourceClass* rc, const QString &nameSpace ) const -{ - return QString( "%1 %2to%3() const" ) - .arg( rc->name( nameSpace ) ) - .arg( !nameSpace.isEmpty() ? baseRc->name( "NepomukFast" ) + "::" : QString() ) - .arg( rc->name() ); -} - -QString FastCode::propertySetterDefinition( const Property* property, const ResourceClass* rc ) const -{ - QString s = propertySetterDeclaration( property, rc, "NepomukFast" ) + '\n'; - - s += QLatin1String("{\n"); - if ( !property->isList() ) { - if ( property->hasSimpleType() ) { - s += QString::fromLatin1(" addProperty( QUrl::fromEncoded(\"%1\"), Soprano::LiteralValue( value ) );\n").arg( property->uri().toString() ); - } else { - s += QString::fromLatin1(" addProperty( QUrl::fromEncoded(\"%1\"), value.uri() );\n").arg( property->uri().toString() ); - } - } else { - if ( property->hasSimpleType() ) { - s += QString::fromLatin1(" for( %1::const_iterator it = value.constBegin();\n" - " it != value.constEnd(); ++it ) {\n" - " addProperty( QUrl::fromEncoded(\"%2\"), Soprano::LiteralValue( *it ) );\n" - " }\n").arg( property->typeString() ).arg( property->uri().toString() ); - } else { - s += QString::fromLatin1(" for( %1::const_iterator it = value.constBegin();\n" - " it != value.constEnd(); ++it ) {\n" - " addProperty( QUrl::fromEncoded(\"%2\"), (*it).uri() );\n" - " }\n").arg( property->typeString() ).arg( property->uri().toString() ); - } - } - s += QLatin1String("}\n"); - - return s; -} - -QString FastCode::propertyGetterDefinition( const Property* property, const ResourceClass* rc ) const -{ - Q_UNUSED( property ); - Q_UNUSED( rc ); - return QString(); -} - -QString FastCode::propertyAdderDefinition( const Property* property, const ResourceClass* rc ) const -{ - QString s = propertyAdderDeclaration( property, rc, "NepomukFast" ) + '\n'; - - s += QLatin1String("{\n"); - if ( property->hasSimpleType() ) { - s += QString::fromLatin1(" addProperty( QUrl::fromEncoded(\"%1\"), Soprano::LiteralValue( value ) );\n").arg( property->uri().toString() ); - } else { - s += QString::fromLatin1(" addProperty( QUrl::fromEncoded(\"%1\"), value.uri() );\n").arg( property->uri().toString() ); - } - s += QLatin1String("}\n"); - - return s; -} - -QString FastCode::propertyReversePropertyGetterDefinition( const Property* property, const ResourceClass* rc ) const -{ - Q_UNUSED( property ); - Q_UNUSED( rc ); - return QString(); -} - -QString FastCode::resourceAllResourcesDefinition( const ResourceClass* rc ) const -{ - Q_UNUSED( rc ); - return QString(); -} - -QString FastCode::resourcePseudoInheritanceDefinition( const ResourceClass* baseRc, const ResourceClass* rc ) const -{ - return QString( "%1\n" - "{\n" - " return %2( uri(), graphUri() );\n" - "}\n" ) - .arg( resourcePseudoInheritanceDeclaration( baseRc, rc, "NepomukFast" ) ) - .arg( rc->name( "NepomukFast" ) ); -} diff --git a/nepomuk/rcgen/fastcode.h b/nepomuk/rcgen/fastcode.h deleted file mode 100644 index f3f94a6d..00000000 --- a/nepomuk/rcgen/fastcode.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#ifndef _NEPOMUK_FASTCODE_H_ -#define _NEPOMUK_FASTCODE_H_ - -#include "abstractcode.h" - -/** - * @short Specific code implementation that is faster. - * - * This implementation of the AbstractCode interface returns generated - * code that uses Soprano directly without Nepomuk to be faster. - */ -class FastCode : public AbstractCode -{ - public: - QString propertySetterDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString propertyGetterDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString propertyAdderDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString propertyReversePropertyGetterDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString resourceAllResourcesDeclaration( const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString resourcePseudoInheritanceDeclaration( const ResourceClass* resourceBaseClass, - const ResourceClass* resourceClass, - const QString &nameSpace ) const; - - QString propertySetterDefinition( const Property *property, const ResourceClass* resourceClass ) const; - QString propertyGetterDefinition( const Property *property, const ResourceClass* resourceClass ) const; - QString propertyAdderDefinition( const Property *property, const ResourceClass* resourceClass ) const; - QString propertyReversePropertyGetterDefinition( const Property *property, - const ResourceClass* resourceClass ) const; - - QString resourceAllResourcesDefinition( const ResourceClass* resourceClass ) const; - QString resourcePseudoInheritanceDefinition( const ResourceClass* resourceBaseClass, - const ResourceClass* resourceClass ) const; -}; - -#endif diff --git a/nepomuk/rcgen/ontologyparser.cpp b/nepomuk/rcgen/ontologyparser.cpp deleted file mode 100644 index f9f8673b..00000000 --- a/nepomuk/rcgen/ontologyparser.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#include "ontologyparser.h" - -#include "property.h" -#include "resourceclass.h" - -#include - -#include -#include -#include -#include -#include -#include - - -extern bool quiet; - - -class OntologyParser::Private -{ -public: - Private() { - // default parent class - resources.insert( Soprano::Vocabulary::RDFS::Resource(), - ResourceClass( Soprano::Vocabulary::RDFS::Resource() ) ); - - // build xsd -> Qt type map - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::integer(), "qint64" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::negativeInteger(), "qint64" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::nonNegativeInteger(), "quint64" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::xsdLong(), "qint64" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::unsignedLong(), "quint64" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::xsdInt(), "qint32" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::unsignedInt(), "quint32" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::xsdShort(), "qint16" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::unsignedShort(), "quint16" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::xsdFloat(), "double" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::xsdDouble(), "double" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::boolean(), "bool" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::date(), "QDate" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::time(), "QTime" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::dateTime(), "QDateTime" ); - xmlSchemaTypes.insert( Soprano::Vocabulary::XMLSchema::string(), "QString" ); - } - - // the classes to be generated as set on the command line - // if empty, all classes are generated - QStringList classesToGenerate; - - // the optional visibility string. If not-empty generated classes will be exported via - // _EXPORT by including the header _export.h. - QString visibility; - - QMap resources; - QMap properties; - QMap comments; - const Soprano::Parser* rdfParser; - - QHash xmlSchemaTypes; - - ResourceClass* getClass( const QUrl& uri ) { - ResourceClass& r = resources[uri]; - r.setUri( uri ); - if ( !r.parentClass(false) ) { - r.setParentResource( &resources[Soprano::Vocabulary::RDFS::Resource()] ); - } - return &r; - } - - Property* getProperty( const QUrl& uri ) { - Property& p = properties[uri]; - p.setUri( uri ); - return &p; - } -}; - - -OntologyParser::OntologyParser() -{ - d = new Private; - d->rdfParser = 0; -} - - -OntologyParser::~OntologyParser() -{ - delete d; -} - - -bool OntologyParser::parse( const QString& filename, const QString& serializationMimeType ) -{ - Soprano::RdfSerialization serialization = Soprano::SerializationUnknown; - if( !serializationMimeType.isEmpty() ) { - serialization = Soprano::mimeTypeToSerialization( serializationMimeType ); - } - else if ( filename.endsWith( "trig" ) ) { - serialization = Soprano::SerializationTrig; - } - else { - serialization = Soprano::SerializationRdfXml; - } - - if ( !( d->rdfParser = Soprano::PluginManager::instance()->discoverParserForSerialization( serialization, serializationMimeType ) ) ) { - return false; - } - - if ( !quiet ) - qDebug() << "(OntologyParser) Parsing " << filename << endl; - - Soprano::StatementIterator it = d->rdfParser->parseFile( filename, - QUrl("http://org.kde.nepomuk/dummybaseuri"), - serialization, - serializationMimeType ); - bool success = true; - - while( it.next() ) { - const Soprano::Statement& s = *it; - - if( s.predicate().uri() == Soprano::Vocabulary::RDFS::subClassOf() ) { - ResourceClass* rc = d->getClass( s.subject().uri().toString() ); - rc->setParentResource( d->getClass( s.object().uri().toString() ) ); - rc->addParentResource( d->getClass( s.object().uri().toString() ) ); - rc->setGenerateClass( true ); - } - else if( s.predicate().uri() == Soprano::Vocabulary::RDF::type() ) { - if( s.object().uri().toString().endsWith( "#Class" ) ) - d->getClass( s.subject().uri().toString() )->setGenerateClass( true ); - } - else if( s.predicate().uri() == Soprano::Vocabulary::RDFS::domain() ) { - ResourceClass* rc = d->getClass( s.object().uri().toString() ); - Property* p = d->getProperty( s.subject().uri().toString() ); - p->setDomain( rc ); - if ( !rc->allProperties().contains( p ) ) - rc->addProperty( p ); - rc->setGenerateClass( true ); - } - else if( s.predicate().uri() == Soprano::Vocabulary::RDFS::range() ) { - Property* prop = d->getProperty(s.subject().uri().toString()); - QUrl type = s.object().uri(); - if( type.toString().contains( "XMLSchema" ) ) { - prop->setLiteralRange( d->xmlSchemaTypes[type] ); - } - else if( type == Soprano::Vocabulary::RDFS::Literal() ) { - prop->setLiteralRange( "QString" ); - } - else { - prop->setRange( d->getClass(s.object().uri()) ); - } - } - else if( s.predicate().uri() == Soprano::Vocabulary::NRL::maxCardinality() || - s.predicate().uri() == Soprano::Vocabulary::NRL::cardinality() ) { - Property * p = d->getProperty(s.subject().uri()); - int cValue = s.object().literal().toInt(); - - p->setIsList( cValue > 1 ); - if( s.predicate().uri() == Soprano::Vocabulary::NRL::maxCardinality() ) - p->setMaxCardinality( cValue ); - else - p->setCardinality( cValue ); - } - else if( s.predicate().uri() == Soprano::Vocabulary::RDFS::comment() ) { - d->comments[s.subject().uri()] = s.object().literal().toString(); - } - else if ( s.predicate().uri() == Soprano::Vocabulary::NRL::inverseProperty() ) { - d->getProperty(s.subject().uri())->setInverseProperty( d->getProperty(s.object().uri()) ); - d->getProperty(s.object().uri())->setInverseProperty( d->getProperty(s.subject().uri()) ); - } - } - - // determine the reverse properties - for( QMap::iterator propIt = d->properties.begin(); - propIt != d->properties.end(); ++propIt ) { - Property& p = propIt.value(); - if( p.range() ) { - if ( !quiet ) - qDebug() << "Setting reverse property " << p.uri() << " on type " << p.range()->uri() << endl; - if ( !p.range()->allReverseProperties().contains( &p ) ) - p.range()->addReverseProperty( &p ); - } - if ( !p.domain() ) { - p.setDomain( d->getClass(Soprano::Vocabulary::RDFS::Resource()) ); - } - - Q_ASSERT( d->properties.count( propIt.key() ) == 1 ); - } - - // now assign the comments to resources and properties - QMapIterator commentsIt( d->comments ); - while( commentsIt.hasNext() ) { - commentsIt.next(); - if( d->resources.contains( commentsIt.key() ) ) - d->resources[commentsIt.key()].setComment( commentsIt.value() ); - else if( d->properties.contains( commentsIt.key() ) ) - d->properties[commentsIt.key()].setComment( commentsIt.value() ); - } - - // testing stuff - for( QMap::iterator it = d->resources.begin(); - it != d->resources.end(); ++it ) { - if( !it->parentClass(false) ) { - it->setParentResource( d->getClass(Soprano::Vocabulary::RDFS::Resource()) ); - } - if ( !quiet ) - qDebug() << "Resource: " << (*it).name() - << "[" << (*it).uri() << "]" - << " (->" << (*it).parentClass(false)->name() << ")" - << ( (*it).generateClass() ? " (will be generated)" : " (will not be generated)" ) - << endl; - - Q_ASSERT( d->resources.count( it.key() ) == 1 ); - - QListIterator propIt( (*it).allProperties() ); - while( propIt.hasNext() ) { - const Property* p = propIt.next(); - if ( !quiet ) - qDebug() << " " << p->uri() << " (->" << p->typeString() << ")" << ( p->isList() ? QString("+") : QString("1") ) << endl; - } - } - - return success; -} - - -QList OntologyParser::parsedClasses() const -{ - QList rl; - for( QMap::iterator it = d->resources.begin(); - it != d->resources.end(); ++it ) - rl << &(*it); - return rl; -} diff --git a/nepomuk/rcgen/ontologyparser.h b/nepomuk/rcgen/ontologyparser.h deleted file mode 100644 index 135b9f72..00000000 --- a/nepomuk/rcgen/ontologyparser.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#ifndef _ONTOLOGY_PARSER_H_ -#define _ONTOLOGY_PARSER_H_ - -#include -#include - -class ResourceClass; - -class OntologyParser -{ - public: - OntologyParser(); - ~OntologyParser(); - - bool parse( const QString& filename, const QString& serialization = QString() ); - QList parsedClasses() const; - - private: - class Private; - Private* d; -}; - -#endif diff --git a/nepomuk/rcgen/property.cpp b/nepomuk/rcgen/property.cpp deleted file mode 100644 index 51d9c077..00000000 --- a/nepomuk/rcgen/property.cpp +++ /dev/null @@ -1,229 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#include "property.h" -#include "resourceclass.h" - -#include -#include -#include - -#include - -extern bool quiet; - -Property::Property() - : m_range( 0 ), - m_isList( true ), - m_domain( 0 ), - m_inverseProperty( 0 ), - m_maxCardinality( -1 ), - m_cardinality( -1 ) -{ -} - -// Property::Property( const QUrl& uri, const QString& type ) -// : m_uri( uri ), -// m_type( type ), -// m_isList( true ), -// m_domain( 0 ), -// m_inverseProperty( 0 ) -// { -// } - -void Property::setUri( const QUrl &uri ) -{ - m_uri = uri; -} - -QUrl Property::uri() const -{ - return m_uri; -} - -void Property::setRange( ResourceClass* type ) -{ - m_range = type; -} - -void Property::setLiteralRange( const QString& range ) -{ - m_literalRange = range; -} - -ResourceClass* Property::range() const -{ - return m_range; -} - -QString Property::literalRange() const -{ - return m_literalRange; -} - -void Property::setComment( const QString &comment ) -{ - m_comment = comment; -} - -QString Property::comment() const -{ - return m_comment; -} - -void Property::setIsList( bool isList ) -{ - m_isList = isList; -} - -bool Property::isList() const -{ - return m_isList; -} - -void Property::setDomain( ResourceClass *domain ) -{ - m_domain = domain; -} - -ResourceClass* Property::domain( bool onlyReturnGeneratedClass ) const -{ - ResourceClass* domain = m_domain; - if(onlyReturnGeneratedClass) { - while( !domain->generateClass() && - domain->uri() != Soprano::Vocabulary::RDFS::Resource() ) - domain = domain->parentClass(); - } - return domain; -} - -void Property::setInverseProperty( Property *property ) -{ - m_inverseProperty = property; -} - -Property* Property::inverseProperty() const -{ - return m_inverseProperty; -} - -QString Property::name() const -{ - // - // many predicates are named "hasSomething" - // we remove the "has" becasue setHasSomething sounds weird - // - const QString name = m_uri.toString().section( QRegExp( "[#/:]" ), -1 ); - if( name.toLower().startsWith( "has" ) ) - return name.mid( 3 ); - else - return name; -} - -QString Property::typeString( bool simple, const QString &nameSpace ) const -{ - QString t; - if( !m_literalRange.isEmpty() ) { - t = m_literalRange; - } - else { - if( m_range->generateClass() ) - t = m_range->name(); - else - t = m_range->parentClass( true )->name(); - if ( !nameSpace.isEmpty() ) - t.prepend( nameSpace + QLatin1String( "::" ) ); - } - - Q_ASSERT( !t.isEmpty() ); - - if( !simple && m_isList ) { - if( t == "QString" ) - return "QStringList"; - else - return "QList<" + t + '>'; - } - - return t; -} - -bool Property::hasSimpleType() const -{ - return ( m_range == 0 ); -} - -QString Property::literalTypeConversionMethod() const -{ - // for properties with cardinality == 1 we use a little hack since there will always be duplication of - // data. - if ( typeString(false) == "QStringList" ) { - return QLatin1String("toStringList())"); - } - else if ( typeString(true) == "QString" ) { - return QLatin1String("toStringList() << QString() ).first()"); - } - else if ( typeString(true) == "qint32" ) { - return m_isList ? QLatin1String("toIntList())") : QLatin1String("toIntList() << 0 ).first()"); - } - else if ( typeString(true) == "quint32" ) { - return m_isList ? QLatin1String("toUnsignedIntList())") : QLatin1String("toUnsignedIntList() << 0 ).first()"); - } - else if ( typeString(true) == "qint64" ) { - return m_isList ? QLatin1String("toInt64List())") : QLatin1String("toInt64List() << 0 ).first()"); - } - else if ( typeString(true) == "quint64" ) { - return m_isList ? QLatin1String("toUnsignedInt64List())") : QLatin1String("toUnsignedInt64List() << 0 ).first()"); - } - else if ( typeString(true) == "bool" ) { - return m_isList ? QLatin1String("toBoolList())") : QLatin1String("toBoolList() << false ).first()"); - } - else if ( typeString(true) == "double" ) { - return m_isList ? QLatin1String("toDoubleList())") : QLatin1String("toDoubleList() << 0.0 ).first()"); - } - else if ( typeString(true) == "QDateTime" ) { - return m_isList ? QLatin1String("toDateTimeList())") : QLatin1String("toDateTimeList() << QDateTime() ).first()"); - } - else if ( typeString(true) == "QDate" ) { - return m_isList ? QLatin1String("toDateList())") : QLatin1String("toDateList() << QDate() ).first()"); - } - else if ( typeString(true) == "QTime" ) { - return m_isList ? QLatin1String("toTimeList())") : QLatin1String("toTimeList() << QTime() ).first()"); - } - - if ( !quiet ) - qDebug() << "Unknown type:" << typeString(true); - - return QString(); -} - -void Property::setMaxCardinality(int value) -{ - m_maxCardinality = value; -} - -int Property::maxCardinality() const -{ - return m_maxCardinality; -} - -int Property::cardinality() const -{ - return m_cardinality; -} - -void Property::setCardinality(int value) -{ - m_cardinality = value; -} - diff --git a/nepomuk/rcgen/property.h b/nepomuk/rcgen/property.h deleted file mode 100644 index a09006d6..00000000 --- a/nepomuk/rcgen/property.h +++ /dev/null @@ -1,173 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#ifndef _NEPOMUK_PROPERTY_H_ -#define _NEPOMUK_PROPERTY_H_ - -#include -#include - -class ResourceClass; - -/** - * @short Represents the property of a resource. - * - * This class keeps all the information of a resource property - * that has been collected by the ontology parser. - */ -class Property -{ -public: - typedef QList ConstPtrList; - - /** - * Creates a new property. - */ - Property(); - - /** - * Creates a new property of a given type and with a given uri. - * - * @param uri The uri that defines the property. - * @param type The type the property is of. - */ - //Property( const QUrl& uri, const QString& type ); - - /** - * Sets the uri of the property. - */ - void setUri( const QUrl &uri ); - - /** - * Returns the uri of the property. - */ - QUrl uri() const; - - /** - * Sets the type of the property. - */ - void setRange( ResourceClass* type ); - - /** - * Set the literal range of the property. - * Cannot be used with setRange at the same time. - * - * \param Name of the Qt type to use - */ - void setLiteralRange( const QString& range ); - - /** - * Returns the scope of the property. - */ - ResourceClass* range() const; - - /** - * Returns the literal range of the property - * (the name of the Qt type to be used.) - */ - QString literalRange() const; - - /** - * Sets the comment of the property. - */ - void setComment( const QString &comment ); - - /** - * Returns the comment of the property. - */ - QString comment() const; - - /** - * Sets whether the property is a list of values. - */ - void setIsList( bool isList ); - - /** - * Returns whether the property is a list of values. - */ - bool isList() const; - - /** - * Sets the domain the property belongs to. - */ - void setDomain( ResourceClass *domain ); - - /** - * Returns the domain resource the property belongs to. - */ - ResourceClass* domain( bool onlyReturnGeneratedClass = false ) const; - - /** - * Sets the inverse property of this property. - */ - void setInverseProperty( Property *property ); - - /** - * Returns the inverse property of this property. - */ - Property* inverseProperty() const; - - /** - * Returns the name of the property. - */ - QString name() const; - - /** - * Returns the conversion method of the property. - */ - QString literalTypeConversionMethod() const; - - /** - * Retrieve a string representation of the range. Handles both literal ranges and class - * ranges. Also ResourceClass::generateClass is taken into account. - */ - QString typeString( bool simple = false, const QString &nameSpace = QString() ) const; - - /** - * Returns whether the property is of simple type. - */ - bool hasSimpleType() const; - - /** - * Sets the max cardinality of the property - */ - void setMaxCardinality( int value ); - - /** - * Returns the max cardinality of the property - */ - int maxCardinality() const; - - /** - * Sets the cardinality of the property - */ - void setCardinality( int value ); - - /** - * Returns the cardinality of the property - */ - int cardinality() const; -private: - QUrl m_uri; - ResourceClass* m_range; - QString m_literalRange; - QString m_comment; - bool m_isList; - ResourceClass* m_domain; - Property* m_inverseProperty; - int m_maxCardinality; - int m_cardinality; -}; - -#endif diff --git a/nepomuk/rcgen/rcgen.cpp b/nepomuk/rcgen/rcgen.cpp deleted file mode 100644 index 27af07d9..00000000 --- a/nepomuk/rcgen/rcgen.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2009 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#include -#include -#include -#include - -#include "kaboutdata.h" -#include "kcmdlineargs.h" -#include "kcomponentdata.h" - -#include "resourceclass.h" -#include "ontologyparser.h" -#include "codegenerator.h" - - -bool quiet = true; - -namespace { -/** - * To be backwards-compatible with older versions which used a space-separated list. - */ -QStringList extractOntologyFileList( const QStringList& args ) -{ - QStringList results; - foreach( const QString& a, args ) { - results << a.split( QRegExp("[\\s]") ); - } - return results; -} -} - -int main( int argc, char** argv ) -{ - KAboutData aboutData( "nepomuk-rcgen", - "nepomuk-rcgen", - ki18n("Nepomuk Resource Class Generator"), - "0.3", - ki18n("Nepomuk Resource Class Generator"), - KAboutData::License_GPL, - ki18n("(c) 2006-2009, Sebastian Trüg"), - KLocalizedString(), - "http://nepomuk.kde.org" ); - aboutData.addAuthor(ki18n("Sebastian Trüg"), ki18n("Maintainer"), "trueg@kde.org"); - aboutData.addAuthor(ki18n("Tobias Koenig"), ki18n("Major cleanup - Personal hero of maintainer"), "tokoe@kde.org"); - aboutData.setProgramIconName( "nepomuk" ); - KComponentData component( aboutData ); - - KCmdLineArgs::init( argc, argv, &aboutData ); - - KCmdLineOptions options; - options.add("verbose", ki18n("Verbose output debugging mode.")); - options.add("fast", ki18n("Generate simple and fast wrapper classes not based on Nepomuk::Resource which do not provide any data integrity checking")); - options.add("writeall", ki18n("Actually generate the code.")); - options.add("listincludes", ki18n("List all includes (deprecated).")); - options.add("listheaders", ki18n("List all header files that will be generated via the --writeall command.")); - options.add("listsources", ki18n("List all source files that will be generated via the --writeall command.")); - options.add("ontologies ", ki18n("The ontology files containing the ontologies to be generated, a space separated list (deprecated: use arguments instead.)")); - options.add("prefix ", ki18n("Include path prefix (deprecated)")); - options.add("target ", ki18n("Specify the target folder to store generated files into.")); - // (romain_kdab) : watch out for a regression with --templates : - // KCmdLineOptions doesn't allow empty option arguments, so e.g. "--templates --foo" will treat --foo as the argument to --templates - // Since the option is deprecated it's probably not worth changing the KCmdLineOptions behaviour only for this ? - options.add("templates ", ki18n("Templates to be used (deprecated).")); - options.add("class ", ki18n("Optionally specify the classes to be generated. Use option multiple times (defaults to all classes)")); - options.add("serialization ", ki18n("Serialization used in the ontology files. Will default to primitive file extension detection.")); - options.add("visibility ", ki18n("Set the used visibility in case the classes are to be used in public API. will be used to construct the export macro name and the export header. By default classes will not be exported.")); - options.add("+[ontologies]", ki18n("The ontology files containing the ontologies to be generated.")); - - KCmdLineArgs::addCmdLineOptions( options ); - QCoreApplication app( argc,argv ); - KCmdLineArgs* args = KCmdLineArgs::parsedArgs(); - - - // ===================================================== - // prepare configuration - // ===================================================== - bool writeAll = args->isSet("writeall"); - bool listHeader = args->isSet("listheaders"); - bool listSource = args->isSet("listsources"); - bool listIncludes = args->isSet("listincludes"); - bool fastMode = args->isSet("fast"); - quiet = !args->isSet("verbose"); - QStringList ontoFiles = extractOntologyFileList( args->getOptionList("ontologies") ); // backwards comp - for(int i = 0; i < args->count(); ++i ) - ontoFiles << args->arg(i); - QString targetDir = args->getOption("target"); - QString prefix = args->getOption("prefix"); - QStringList templates = args->getOptionList("templates"); - QStringList classesToGenerate = args->getOptionList( "class" ); - QString visibility = args->getOption("visibility"); - - // ===================================================== - // a few checks for valid parameters (not complete!) - // ===================================================== - if( ontoFiles.isEmpty() ) { - QTextStream s( stderr ); - s << "No ontology files specified." << endl; - return -1; - } - - foreach( const QString& ontoFile, ontoFiles ) { - if( !QFile::exists( ontoFile ) ) { - QTextStream s( stderr ); - s << "Ontology file " << ontoFile << " does not exist." << endl; - return -1; - } - } - - if( fastMode && !visibility.isEmpty() ) { - QTextStream s( stderr ); - s << "Cannot export fast classes. They are only meant to be used as private classes." << endl; - return -1; - } - - - if( writeAll ) { - if( !QFile::exists( targetDir ) ) { - QTextStream s( stderr ); - s << "Folder " << targetDir << " does not exist." << endl; - return -1; - } - } - - - // ===================================================== - // parse the data and determine the classes to generate - // ===================================================== - OntologyParser prsr; - foreach( const QString& ontoFile, ontoFiles ) { - if( !prsr.parse( ontoFile, args->getOption("serialization") ) ) { - QTextStream s( stderr ); - s << "Parsing ontology file " << ontoFile << " failed." << endl; - return -1; - } - } - - // if classes to be generated have been specified on the command line, reset all ResourceClass - // instances in terms of generation - if( !classesToGenerate.isEmpty() ) { - foreach( ResourceClass* rc, prsr.parsedClasses() ) { - rc->setGenerateClass( classesToGenerate.contains( rc->uri().toString() ) ); - } - } - - - // ===================================================== - // create the code generator which will take care of the rest - // ===================================================== - CodeGenerator codeGen( fastMode ? CodeGenerator::FastMode : CodeGenerator::SafeMode, prsr.parsedClasses() ); - codeGen.setVisibility( visibility ); - - if( writeAll ) { - if( !codeGen.writeSources( targetDir ) ) { - QTextStream s( stderr ); - s << "Writing sources to " << targetDir << " failed." << endl; - return -1; - } - } - else if( listSource ) { - QStringList l = codeGen.listSources(); - QTextStream s( stdout, QIODevice::WriteOnly ); - QStringListIterator it( l ); - while( it.hasNext() ) - s << prefix << it.next() << ";"; - - if( fastMode ) - s << prefix << "resource.cpp;"; - } - else if( listHeader ) { - QStringList l = codeGen.listHeader(); - QTextStream s( stdout, QIODevice::WriteOnly ); - QStringListIterator it( l ); - while( it.hasNext() ) - s << prefix << it.next() << ";"; - - if( fastMode ) - s << prefix << "resource.h;"; - } - else if( listIncludes ) { - QStringList l = codeGen.listHeader(); - QTextStream s( stdout, QIODevice::WriteOnly ); - QStringListIterator it( l ); - while( it.hasNext() ) - s << "#include " << endl; - } - - return 0; -} diff --git a/nepomuk/rcgen/resourceclass.cpp b/nepomuk/rcgen/resourceclass.cpp deleted file mode 100644 index ab6b1c91..00000000 --- a/nepomuk/rcgen/resourceclass.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#include "resourceclass.h" - -#include - -#include - -ResourceClass::ResourceClass() - : m_parentClass( 0 ), - m_generateClass( false ) -{ -} - -ResourceClass::ResourceClass( const QUrl& uri ) - : m_uri( uri ), - m_parentClass( 0 ), - m_generateClass( false ) -{ -} - -ResourceClass::~ResourceClass() -{ -} - -void ResourceClass::setUri( const QUrl &uri ) -{ - m_uri = uri; -} - -QUrl ResourceClass::uri() const -{ - return m_uri; -} - -void ResourceClass::setComment( const QString &comment ) -{ - m_comment = comment; -} - -QString ResourceClass::comment() const -{ - return m_comment; -} - -void ResourceClass::setParentResource( ResourceClass* parent ) -{ - m_parentClass = parent; -} - -ResourceClass* ResourceClass::parentClass( bool considerGenerateClass ) const -{ - ResourceClass* parent = m_parentClass; - if( considerGenerateClass && !parent->generateClass() ) { - // first check for another "top-level" parent class to be generated - foreach( ResourceClass* rc, m_allParentResources ) { - if( rc->generateClass() && - rc->uri() != Soprano::Vocabulary::RDFS::Resource() ) { - return rc; - } - } - // nothing found -> just use the first - while( !parent->generateClass() && - parent->uri() != Soprano::Vocabulary::RDFS::Resource() ) - parent = parent->parentClass(); - } - return parent; -} - -void ResourceClass::addParentResource( ResourceClass* parent ) -{ - m_allParentResources.append( parent ); -} - -QList ResourceClass::allParentResources() const -{ - return m_allParentResources; -} - -void ResourceClass::addProperty( Property* property ) -{ - m_properties.append( property ); -} - -Property::ConstPtrList ResourceClass::allProperties() const -{ - return m_properties; -} - -void ResourceClass::addReverseProperty( Property* property ) -{ - m_reverseProperties.append( property ); -} - -Property::ConstPtrList ResourceClass::allReverseProperties() const -{ - return m_reverseProperties; -} - -void ResourceClass::setGenerateClass( bool generate ) -{ - m_generateClass = generate; -} - -bool ResourceClass::generateClass() const -{ - return m_generateClass; -} - -QString ResourceClass::name( const QString &nameSpace ) const -{ - QString s = m_uri.toString().section( QRegExp( "[#/:]" ), -1 ); - if( !nameSpace.isEmpty() ) - s.prepend( nameSpace + "::" ); - return s; -} - -QString ResourceClass::headerName() const -{ - return name().toLower() + ".h"; -} - -QString ResourceClass::sourceName() const -{ - return name().toLower() + ".cpp"; -} diff --git a/nepomuk/rcgen/resourceclass.h b/nepomuk/rcgen/resourceclass.h deleted file mode 100644 index 0b084e78..00000000 --- a/nepomuk/rcgen/resourceclass.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#ifndef _NEPOMUK_RESOURCE_CLASS_H_ -#define _NEPOMUK_RESOURCE_CLASS_H_ - -#include -#include -#include - -#include "property.h" - -/** - * @short Represents a resource. - * - * This class keeps all the information of a resource - * that has been collected by the ontology parser. - */ -class ResourceClass -{ - public: - ResourceClass(); - ResourceClass( const QUrl& uri ); - ~ResourceClass(); - - /** - * Sets the uri of the resource. - */ - void setUri( const QUrl &uri ); - - /** - * Returns the uri of the resource. - */ - QUrl uri() const; - - /** - * Sets the comment of the resource. - */ - void setComment( const QString &comment ); - - /** - * Returns the comment of the resource. - */ - QString comment() const; - - /** - * Sets the parent resource of the resource. - */ - void setParentResource( ResourceClass* parent ); - - /** - * Returns the parent resource of the resource. - */ - ResourceClass* parentClass( bool considerGenerateClass = true ) const; - - /** - * Adds a parent resource to the resource. - */ - void addParentResource( ResourceClass* parent ); - - /** - * Returns all parent resource of the resource. - */ - QList allParentResources() const; - - /** - * Adds a new property to the resource. - */ - void addProperty( Property* property ); - - /** - * Returns the list of all properties of the resource. - */ - Property::ConstPtrList allProperties() const; - - /** - * Adds a reverse property to the resource. - */ - void addReverseProperty( Property* property ); - - /** - * Returns the list of all reverse properties of the resource. - */ - Property::ConstPtrList allReverseProperties() const; - - /** - * Sets whether code for this class shall be generated. - */ - void setGenerateClass( bool generate ); - - /** - * Returns @c true if this class should be generated. - * Normally this always returns true except for the base class - * Resource. - */ - bool generateClass() const; - - /** - * Returns the name of the resource. - * - * @param nameSpace The namespace that shall be included. - */ - QString name( const QString &nameSpace = QString() ) const; - - /** - * Returns the name of the header file for this resource. - */ - QString headerName() const; - - /** - * Returns the name of the source file for this resource. - */ - QString sourceName() const; - - private: - QUrl m_uri; - QString m_comment; - ResourceClass* m_parentClass; - QList m_allParentResources; - Property::ConstPtrList m_properties; - Property::ConstPtrList m_reverseProperties; - bool m_generateClass; -}; - -#endif diff --git a/nepomuk/rcgen/safecode.cpp b/nepomuk/rcgen/safecode.cpp deleted file mode 100644 index 0e350592..00000000 --- a/nepomuk/rcgen/safecode.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#include "safecode.h" - -#include "property.h" -#include "resourceclass.h" - -static const QString s_typeComment = -" // We always store all Resource types as plain Resource objects.\n" -" // It does not introduce any overhead (due to the implicit sharing of\n" -" // the data and has the advantage that we can mix setProperty calls\n" -" // with the special Resource subclass methods.\n" -" // More importantly Resource loads the data as Resource objects anyway.\n"; - -QString SafeCode::propertySetterDeclaration( const Property* property, const ResourceClass* rc, const QString &nameSpace ) const -{ - return QString( "void %1set%2%3%4( const %5& value )" ) - .arg( !nameSpace.isEmpty() ? QString("%1::%2::").arg(nameSpace).arg(rc->name()) : QString() ) - .arg( property->name()[0].toUpper() ) - .arg( property->name().mid(1) ) - .arg( property->isList() ? (property->name().endsWith('s') ? QLatin1String("es") : QLatin1String("s") ) : QString() ) - .arg( property->typeString( false, nameSpace ) ); -} - -QString SafeCode::propertyGetterDeclaration( const Property* property, const ResourceClass* rc, const QString &nameSpace ) const -{ - return QString( "%1 %2%3%4%5() const" ) - .arg( property->typeString( false, nameSpace ) ) - .arg( !nameSpace.isEmpty() ? QString("%1::%2::").arg(nameSpace).arg(rc->name()) : QString() ) - .arg( property->name()[0].toLower() ) - .arg( property->name().mid(1) ) - .arg( property->isList() ? (property->name().endsWith('s') ? QLatin1String("es") : QLatin1String("s") ) : QString() ); -} - -QString SafeCode::propertyAdderDeclaration( const Property* property, const ResourceClass* rc, const QString &nameSpace ) const -{ - return QString( "void %1add%2%3( const %4& value )" ) - .arg( !nameSpace.isEmpty() ? QString("%1::%2::").arg(nameSpace).arg(rc->name()) : QString() ) - .arg( property->name()[0].toUpper() ) - .arg( property->name().mid(1) ) - .arg( property->typeString( true, nameSpace ) ); -} - -QString SafeCode::propertyReversePropertyGetterDeclaration( const Property* property, const ResourceClass* rc, const QString &nameSpace ) const -{ - Q_ASSERT( rc ); - Q_ASSERT( property->domain() ); - return QString( "%1 %2%3%4Of() const" ) - .arg( QString("QList<") + property->domain(true)->name( nameSpace ) + QString(">") ) - .arg( !nameSpace.isEmpty() ? QString("%1::%2::").arg(nameSpace).arg(rc->name()) : QString() ) - .arg( property->name()[0].toLower() ) - .arg( property->name().mid(1) ); -} - -QString SafeCode::resourceAllResourcesDeclaration( const ResourceClass* rc, const QString &nameSpace ) const -{ - return QString( "QList<%1%2> %3all%2s()" ) - .arg( !nameSpace.isEmpty() ? nameSpace + "::" : QString() ) - .arg( rc->name() ) - .arg( !nameSpace.isEmpty() ? QString("%1::%2::").arg(nameSpace).arg( rc->name() ) : QString() ); -} - -QString SafeCode::resourcePseudoInheritanceDeclaration( const ResourceClass* baseRc, const ResourceClass* rc, const QString &nameSpace ) const -{ - return QString( "%1 %2to%3() const" ) - .arg( rc->name( nameSpace ) ) - .arg( !nameSpace.isEmpty() ? baseRc->name( "Nepomuk" ) + "::" : QString() ) - .arg( rc->name() ); -} - -QString SafeCode::propertySetterDefinition( const Property* property, const ResourceClass* rc ) const -{ - QString s = propertySetterDeclaration( property, rc, "Nepomuk" ) + '\n'; - - if( property->hasSimpleType() || property->typeString( true ) == "Resource" || !property->isList() ) { - s += QString("{\n" - " setProperty( QUrl::fromEncoded(\"%1\"), Variant( value ) );\n" - "}\n" ) - .arg( property->uri().toString() ); - } - else if( property->isList() ) { - s += QString("{\n" - "%1" - " QList l;\n" - " for( %2::const_iterator it = value.constBegin();\n" - " it != value.constEnd(); ++it ) {\n" - " l.append( Resource( (*it) ) );\n" - " }\n" - " setProperty( QUrl::fromEncoded(\"%3\"), Variant( l ) );\n" - "}\n" ) - .arg( s_typeComment ) - .arg( property->typeString() ) - .arg( property->uri().toString() ); - } - else { - s += QString("{\n" - "%1" - " setProperty( QUrl::fromEncoded(\"%2\"), Variant( Resource( value ) ) );\n" - "}\n" ) - .arg( s_typeComment ) - .arg( property->uri().toString() ); - } - - return s; -} - -QString SafeCode::propertyGetterDefinition( const Property* property, const ResourceClass* rc ) const -{ - QString s = propertyGetterDeclaration( property, rc, "Nepomuk" ) + '\n'; - - if( property->hasSimpleType() ) { - s += QString( "{\n" - " return ( property( QUrl::fromEncoded(\"%1\") ).%2;\n" - "}\n" ) - .arg( property->uri().toString() ) - .arg( property->literalTypeConversionMethod() ); - } - else if( property->isList() ) { - s += QString("{\n" - "%1" - " return convertResourceList<%3>( property( QUrl::fromEncoded(\"%2\") ).toResourceList() );\n" - "}\n" ) - .arg( s_typeComment ) - .arg( property->uri().toString() ) - .arg( property->typeString( true ) ); - } - else { - s += QString("{\n" - "%1" - " return %2( property( QUrl::fromEncoded(\"%3\") ).toResource().resourceUri() );\n" - "}\n" ) - .arg( s_typeComment ) - .arg( property->typeString( true ) ) - .arg( property->uri().toString() ); - } - - return s; -} - -QString SafeCode::propertyAdderDefinition( const Property* property, const ResourceClass* rc ) const -{ - QString s = propertyAdderDeclaration( property, rc, "Nepomuk" ) + '\n'; - - if( property->hasSimpleType() ) { - s += QString( "{\n" - " Variant v = property( QUrl::fromEncoded(\"%1\") );\n" - " v.append( value );\n" - " setProperty( QUrl::fromEncoded(\"%1\"), v );\n" - "}\n" ) - .arg( property->uri().toString() ); - } - else { - s += QString( "{\n" - "%1" - " Variant v = property( QUrl::fromEncoded(\"%2\") );\n" - " v.append( Resource( value ) );\n" - " setProperty( QUrl::fromEncoded(\"%2\"), v );\n" - "}\n" ) - .arg( s_typeComment ) - .arg( property->uri().toString() ); - } - - return s; -} - -QString SafeCode::propertyReversePropertyGetterDefinition( const Property* property, const ResourceClass* rc ) const -{ - QString s = propertyReversePropertyGetterDeclaration( property, rc, "Nepomuk" ) + '\n'; - - s += QString( "{\n" - " return convertResourceList<%2>( manager()->allResourcesWithProperty( QUrl::fromEncoded(\"%1\"), *this ) );\n" - "}\n" ) - .arg( property->uri().toString() ) - .arg( property->domain(true)->name() ); - - return s; -} - -QString SafeCode::resourceAllResourcesDefinition( const ResourceClass* rc ) const -{ - return QString( "%1\n" - "{\n" - " return Nepomuk::convertResourceList<%3>( ResourceManager::instance()->allResourcesOfType( QUrl::fromEncoded(\"%2\") ) );\n" - "}\n" ) - .arg( resourceAllResourcesDeclaration( rc, "Nepomuk" ) ) - .arg( rc->uri().toString() ) - .arg( rc->name() ); -} - -QString SafeCode::resourcePseudoInheritanceDefinition( const ResourceClass* baseRc, const ResourceClass* rc ) const -{ - return QString( "%1\n" - "{\n" - " return %2( *this );\n" - "}\n" ) - .arg( resourcePseudoInheritanceDeclaration( baseRc, rc, "Nepomuk" ) ) - .arg( rc->name( "Nepomuk" ) ); -} diff --git a/nepomuk/rcgen/safecode.h b/nepomuk/rcgen/safecode.h deleted file mode 100644 index fda66c70..00000000 --- a/nepomuk/rcgen/safecode.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * $Id: sourceheader 511311 2006-02-19 14:51:05Z trueg $ - * - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library 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. - * See the file "COPYING.LIB" for the exact licensing terms. - */ - -#ifndef _NEPOMUK_SAFECODE_H_ -#define _NEPOMUK_SAFECODE_H_ - -#include "abstractcode.h" - -/** - * @short Specific code implementation with full checks. - * - * This implementation of the AbstractCode interface returns generated - * code that uses Nepomuk::Property to full check syntax and semantic - * of the data before writing it to the Nepomuk storage. - */ -class SafeCode : public AbstractCode -{ - public: - QString propertySetterDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString propertyGetterDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString propertyAdderDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString propertyReversePropertyGetterDeclaration( const Property *property, - const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString resourceAllResourcesDeclaration( const ResourceClass* resourceClass, - const QString &nameSpace = QString() ) const; - - QString resourcePseudoInheritanceDeclaration( const ResourceClass* resourceBaseClass, - const ResourceClass* resourceClass, - const QString &nameSpace ) const; - - QString propertySetterDefinition( const Property *property, const ResourceClass* resourceClass ) const; - QString propertyGetterDefinition( const Property *property, const ResourceClass* resourceClass ) const; - QString propertyAdderDefinition( const Property *property, const ResourceClass* resourceClass ) const; - QString propertyReversePropertyGetterDefinition( const Property *property, - const ResourceClass* resourceClass ) const; - - QString resourceAllResourcesDefinition( const ResourceClass* resourceClass ) const; - QString resourcePseudoInheritanceDefinition( const ResourceClass* resourceBaseClass, - const ResourceClass* resourceClass ) const; -}; - -#endif diff --git a/nepomuk/rcgen/templates.qrc b/nepomuk/rcgen/templates.qrc deleted file mode 100644 index 8d95a631..00000000 --- a/nepomuk/rcgen/templates.qrc +++ /dev/null @@ -1,12 +0,0 @@ - - - - templates/gpl.tpl - templates/header_safe.tpl - templates/source_safe.tpl - templates/header_fast.tpl - templates/source_fast.tpl - templates/dummyresource_header_fast.tpl - templates/dummyresource_source_fast.tpl - - diff --git a/nepomuk/rcgen/templates/dummyresource_header_fast.tpl b/nepomuk/rcgen/templates/dummyresource_header_fast.tpl deleted file mode 100644 index 0bd40e77..00000000 --- a/nepomuk/rcgen/templates/dummyresource_header_fast.tpl +++ /dev/null @@ -1,46 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * - * This library 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. - * See the file "COPYING" for the exact licensing terms. - */ - -/* - * This file has been generated by the Nepomuk Resource class generator. - * DO NOT EDIT THIS FILE. - * ANY CHANGES WILL BE LOST. - */ - -#ifndef _NEPOMUK_FAST_RESOURCE_H_ -#define _NEPOMUK_FAST_RESOURCE_H_ - -#include - -#include - -namespace NepomukFast { - - class Resource - { - public: - QUrl uri() const; - QUrl graphUri() const; - QUrl type() const; - - void addProperty( const QUrl &uri, const Soprano::Node &node ); - void setLabel( const QString &label ); - - protected: - Resource( const QUrl& uri, const QUrl& graphUri, const QUrl& type ); - - private: - QUrl m_uri; - QUrl m_graphUri; - QUrl m_type; - }; -} - -#endif diff --git a/nepomuk/rcgen/templates/dummyresource_source_fast.tpl b/nepomuk/rcgen/templates/dummyresource_source_fast.tpl deleted file mode 100644 index 086fe764..00000000 --- a/nepomuk/rcgen/templates/dummyresource_source_fast.tpl +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * - * This library 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. - * See the file "COPYING" for the exact licensing terms. - */ - -/* - * This file has been generated by the Nepomuk Resource class generator. - * DO NOT EDIT THIS FILE. - * ANY CHANGES WILL BE LOST. - */ - -#include "resource.h" - -#include -#include -#include -#include -#include -#include - -using namespace NepomukFast; - -Resource::Resource( const QUrl& uri, const QUrl& graphUri, const QUrl& type ) - : m_uri( uri ), m_graphUri( graphUri ), m_type( type ) -{ - if ( m_uri.isEmpty() ) - m_uri = Nepomuk::ResourceManager::instance()->generateUniqueUri( QString() ); - - if ( m_graphUri.isEmpty() ) - m_graphUri = Nepomuk::ResourceManager::instance()->generateUniqueUri( QString() ); - - if ( m_type.isEmpty() ) - m_type = Soprano::Vocabulary::RDFS::Resource(); - else // add the type right away - Nepomuk::ResourceManager::instance()->mainModel()->addStatement( m_uri, Soprano::Vocabulary::RDF::type(), m_type, m_graphUri ); -} - -QUrl Resource::uri() const -{ - return m_uri; -} - -QUrl Resource::graphUri() const -{ - return m_graphUri; -} - -QUrl Resource::type() const -{ - return m_type; -} - -void Resource::addProperty( const QUrl &uri, const Soprano::Node &node ) -{ - Nepomuk::ResourceManager::instance()->mainModel()->addStatement( m_uri, uri, node, m_graphUri ); -} - -void Resource::setLabel( const QString &label ) -{ - addProperty( Soprano::Vocabulary::NAO::prefLabel(), Soprano::LiteralValue( label ) ); -} diff --git a/nepomuk/rcgen/templates/gpl.tpl b/nepomuk/rcgen/templates/gpl.tpl deleted file mode 100644 index b4bc0361..00000000 --- a/nepomuk/rcgen/templates/gpl.tpl +++ /dev/null @@ -1,15 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * - * This library 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. - * See the file "COPYING" for the exact licensing terms. - */ - -/* - * This file has been generated by the Nepomuk Resource class generator. - * DO NOT EDIT THIS FILE. - * ANY CHANGES WILL BE LOST. - */ diff --git a/nepomuk/rcgen/templates/header_fast.tpl b/nepomuk/rcgen/templates/header_fast.tpl deleted file mode 100644 index a3a974fc..00000000 --- a/nepomuk/rcgen/templates/header_fast.tpl +++ /dev/null @@ -1,33 +0,0 @@ - -#ifndef _NEPOMUK_RESOURCENAMEUPPER_H_ -#define _NEPOMUK_RESOURCENAMEUPPER_H_ - -class QDateTime; -class QDate; -class QTime; - -namespace NepomukFast { -NEPOMUK_OTHERCLASSES -} - -#include NEPOMUK_PARENT_INCLUDE - -namespace NepomukFast { - -NEPOMUK_RESOURCECOMMENT - class NEPOMUK_RESOURCENAME : public NEPOMUK_PARENTRESOURCE - { - public: - /** - * Create a new empty and invalid NEPOMUK_RESOURCENAME instance - */ - NEPOMUK_RESOURCENAME( const QUrl &uri = QUrl(), const QUrl &graphUri = QUrl() ); - -NEPOMUK_METHODS - - protected: - NEPOMUK_RESOURCENAME( const QUrl& uri, const QUrl& graphUri, const QUrl& type ); - }; -} - -#endif diff --git a/nepomuk/rcgen/templates/header_safe.tpl b/nepomuk/rcgen/templates/header_safe.tpl deleted file mode 100644 index dd096569..00000000 --- a/nepomuk/rcgen/templates/header_safe.tpl +++ /dev/null @@ -1,66 +0,0 @@ - -#ifndef _NEPOMUK_RESOURCENAMEUPPER_H_ -#define _NEPOMUK_RESOURCENAMEUPPER_H_ - -class QDateTime; -class QDate; -class QTime; - -namespace Nepomuk { -NEPOMUK_OTHERCLASSES -} - -#include NEPOMUK_PARENT_INCLUDE -NEPOMUK_VISIBILITY_HEADER_INCLUDE - -namespace Nepomuk { - -NEPOMUK_RESOURCECOMMENT - class NEPOMUK_VISIBILITY NEPOMUK_RESOURCENAME : public NEPOMUK_PARENTRESOURCE - { - public: - /** - * Create a new empty and invalid NEPOMUK_RESOURCENAME instance - */ - NEPOMUK_RESOURCENAME(); - NEPOMUK_RESOURCENAME( ResourceManager* ); - - /** - * Default copy constructor - */ - NEPOMUK_RESOURCENAME( const NEPOMUK_RESOURCENAME& ); - NEPOMUK_RESOURCENAME( const Resource& ); - - /** - * Create a new NEPOMUK_RESOURCENAME instance representing the resource - * referenced by \a uriOrIdentifier. - */ - NEPOMUK_RESOURCENAME( const QString& uriOrIdentifier ); - NEPOMUK_RESOURCENAME( const QString& uriOrIdentifier, ResourceManager* ); - - /** - * Create a new NEPOMUK_RESOURCENAME instance representing the resource - * referenced by \a uri. - */ - NEPOMUK_RESOURCENAME( const QUrl& uri ); - NEPOMUK_RESOURCENAME( const QUrl& uri, ResourceManager* ); - ~NEPOMUK_RESOURCENAME(); - - NEPOMUK_RESOURCENAME& operator=( const NEPOMUK_RESOURCENAME& ); - -NEPOMUK_METHODS - - /** - * \return The URI of the resource type that is used in NEPOMUK_RESOURCENAME instances. - */ - static QString resourceTypeUri(); - - protected: - NEPOMUK_RESOURCENAME( const QString& uri, const QUrl& type ); - NEPOMUK_RESOURCENAME( const QUrl& uri, const QUrl& type ); - NEPOMUK_RESOURCENAME( const QString& uri, const QUrl& type, ResourceManager* ); - NEPOMUK_RESOURCENAME( const QUrl& uri, const QUrl& type, ResourceManager* ); - }; -} - -#endif diff --git a/nepomuk/rcgen/templates/source_fast.tpl b/nepomuk/rcgen/templates/source_fast.tpl deleted file mode 100644 index 3d677fe9..00000000 --- a/nepomuk/rcgen/templates/source_fast.tpl +++ /dev/null @@ -1,22 +0,0 @@ - -#include - -#include "NEPOMUK_RESOURCENAMELOWER.h" - -NEPOMUK_INCLUDES - -#include -#include -#include - -NepomukFast::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QUrl &uri, const QUrl &graphUri ) - : NEPOMUK_PARENTRESOURCE( uri, graphUri, QUrl::fromEncoded("NEPOMUK_RESOURCETYPEURI", QUrl::StrictMode) ) -{ -} - -NepomukFast::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QUrl& uri, const QUrl& graphUri, const QUrl& type ) - : NEPOMUK_PARENTRESOURCE( uri, graphUri, type ) -{ -} - -NEPOMUK_METHODS diff --git a/nepomuk/rcgen/templates/source_safe.tpl b/nepomuk/rcgen/templates/source_safe.tpl deleted file mode 100644 index ef507548..00000000 --- a/nepomuk/rcgen/templates/source_safe.tpl +++ /dev/null @@ -1,93 +0,0 @@ - -#include -#include -#include -#include "NEPOMUK_RESOURCENAMELOWER.h" - -NEPOMUK_INCLUDES - -#include -#include -#include - - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME() - : NEPOMUK_PARENTRESOURCE( QUrl(), QUrl::fromEncoded("NEPOMUK_RESOURCETYPEURI") ) -{ -} - - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( ResourceManager* manager ) - : NEPOMUK_PARENTRESOURCE( QUrl(), QUrl::fromEncoded("NEPOMUK_RESOURCETYPEURI"), manager ) -{ -} - - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const NEPOMUK_RESOURCENAME& res ) - : NEPOMUK_PARENTRESOURCE( res ) -{ -} - - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const Nepomuk::Resource& res ) - : NEPOMUK_PARENTRESOURCE( res ) -{ -} - - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QString& uri ) - : NEPOMUK_PARENTRESOURCE( uri, QUrl::fromEncoded("NEPOMUK_RESOURCETYPEURI") ) -{ -} - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QString& uri, ResourceManager* manager ) - : NEPOMUK_PARENTRESOURCE( uri, QUrl::fromEncoded("NEPOMUK_RESOURCETYPEURI"), manager ) -{ -} - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QUrl& uri ) - : NEPOMUK_PARENTRESOURCE( uri, QUrl::fromEncoded("NEPOMUK_RESOURCETYPEURI") ) -{ -} - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QUrl& uri, ResourceManager* manager ) - : NEPOMUK_PARENTRESOURCE( uri, QUrl::fromEncoded("NEPOMUK_RESOURCETYPEURI"), manager ) -{ -} - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QString& uri, const QUrl& type ) - : NEPOMUK_PARENTRESOURCE( uri, type ) -{ -} - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QString& uri, const QUrl& type, ResourceManager* manager ) - : NEPOMUK_PARENTRESOURCE( uri, type, manager ) -{ -} - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QUrl& uri, const QUrl& type ) - : NEPOMUK_PARENTRESOURCE( uri, type ) -{ -} - -Nepomuk::NEPOMUK_RESOURCENAME::NEPOMUK_RESOURCENAME( const QUrl& uri, const QUrl& type, ResourceManager* manager ) - : NEPOMUK_PARENTRESOURCE( uri, type, manager ) -{ -} - -Nepomuk::NEPOMUK_RESOURCENAME::~NEPOMUK_RESOURCENAME() -{ -} - -Nepomuk::NEPOMUK_RESOURCENAME& Nepomuk::NEPOMUK_RESOURCENAME::operator=( const NEPOMUK_RESOURCENAME& res ) -{ - Resource::operator=( res ); - return *this; -} - -QString Nepomuk::NEPOMUK_RESOURCENAME::resourceTypeUri() -{ - return QLatin1String("NEPOMUK_RESOURCETYPEURI"); -} - -NEPOMUK_METHODS diff --git a/nepomuk/test/CMakeLists.txt b/nepomuk/test/CMakeLists.txt deleted file mode 100644 index d182d552..00000000 --- a/nepomuk/test/CMakeLists.txt +++ /dev/null @@ -1,108 +0,0 @@ -project(nepomuk_tests) - -set( EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR} ) - -include_directories( - ${CMAKE_CURRENT_BINARY_DIR}/.. -) - -add_definitions(-DDISABLE_NEPOMUK_LEGACY=1) -add_definitions(-DBUILDING_NEPOMUK_TESTS) - -# DISABLED IN THIS BRANCH - -# Query tests -# -------------------------------------------- -#set(queryparsertest_SRC queryparsertest.cpp) -#kde4_add_unit_test(queryparsertest TESTNAME nepomuk-queryparsertest NOGUI ${queryparsertest_SRC}) -#target_link_libraries(queryparsertest nepomuk nepomukquery -#${QT_QTTEST_LIBRARY} -#${SOPRANO_LIBRARIES} -#${KDE4_KDECORE_LIBS} -#) - -#set(querytest_SRC querytest.cpp) -#kde4_add_unit_test(querytest TESTNAME nepomuk-querytest NOGUI ${querytest_SRC}) -#target_link_libraries(querytest nepomuk nepomukquery -#${QT_QTTEST_LIBRARY} -#${SOPRANO_LIBRARIES} -#${KDE4_KDECORE_LIBS} -#) - -set(queryserializertest_SRC queryserializertest.cpp) -kde4_add_unit_test(queryserializertest TESTNAME nepomuk-queryserializertest NOGUI ${queryserializertest_SRC}) -target_link_libraries(queryserializertest nepomuk nepomukquery - ${QT_QTTEST_LIBRARY} - ${SOPRANO_LIBRARIES} - ${KDE4_KDECORE_LIBS} -) - - -# Ui tests -# -------------------------------------------- -kde4_add_executable(ratingpaintertestapp TEST ratingpaintertestapp.cpp ratingpaintertestwidget.cpp) -target_link_libraries(ratingpaintertestapp - ${KDE4_KIO_LIBS} - nepomuk - ) - -kde4_add_executable(tagwidgetapp TEST tagwidgetapp.cpp tagwidgettest.cpp) -target_link_libraries(tagwidgetapp - ${KDE4_KIO_LIBS} - nepomuk - ) - - -# Facet tests -# ----------------------------------- -kde4_add_unit_test(simplefacettest TESTNAME nepomuk-simplefacettest simplefacettest.cpp) -target_link_libraries(simplefacettest - ${QT_QTTEST_LIBRARY} - ${SOPRANO_LIBRARIES} - ${KDE4_KDECORE_LIBS} - nepomuk - nepomukquery - nepomukutils -) - -# DISABLED IN THIS BRANCH -#kde4_add_unit_test(dynamicresourcefacettest TESTNAME nepomuk-dynamicresourcefacettest dynamicresourcefacettest.cpp) -#target_link_libraries(dynamicresourcefacettest -#${QT_QTTEST_LIBRARY} -#${SOPRANO_LIBRARIES} -#${KDE4_KDECORE_LIBS} -#nepomuk -#nepomukquery -#nepomukutils -#) - -kde4_add_unit_test(proxyfacettest TESTNAME nepomuk-proxyfacettest proxyfacettest.cpp) -target_link_libraries(proxyfacettest - ${QT_QTTEST_LIBRARY} - ${SOPRANO_LIBRARIES} - ${KDE4_KDECORE_LIBS} - nepomuk - nepomukquery - nepomukutils -) - -kde4_add_unit_test(facetmodeltest TESTNAME nepomuk-facetmodeltest facetmodeltest.cpp) -target_link_libraries(facetmodeltest - ${QT_QTTEST_LIBRARY} - ${SOPRANO_LIBRARIES} - ${KDE4_KDECORE_LIBS} - nepomuk - nepomukquery - nepomukutils -) - -kde4_add_unit_test(typefacettest TESTNAME nepomuk-typefacettest typefacettest.cpp) -target_link_libraries(typefacettest - ${QT_QTTEST_LIBRARY} - ${SOPRANO_LIBRARIES} - ${KDE4_KDECORE_LIBS} - nepomuk - nepomukquery - nepomukutils -) - diff --git a/nepomuk/test/dynamicresourcefacettest.cpp b/nepomuk/test/dynamicresourcefacettest.cpp deleted file mode 100644 index 6dd2cb05..00000000 --- a/nepomuk/test/dynamicresourcefacettest.cpp +++ /dev/null @@ -1,416 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "dynamicresourcefacettest.h" -#include "qtest_querytostring.h" - -#include "dynamicresourcefacet.h" -#include "dynamicresourcefacet_p.h" -#include "comparisonterm.h" -#include "resourcetypeterm.h" -#include "resourceterm.h" -#include "andterm.h" -#include "orterm.h" - -#include "resourcemanager.h" -#include "tag.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include "qtest_kde.h" -#include "kdebug.h" - -using namespace Nepomuk; -using namespace Nepomuk::Utils; -using namespace Nepomuk::Query; -using namespace Nepomuk::Types; - - -class DynamicResourceTestFacet::TestPrivate : public DynamicResourceFacet::Private -{ -public: - void startQuery( const Nepomuk::Query::Query& query ) { - // we cannot use the query service since that would ignore our custom model - // thus, we perform a sync query and call _k_newEntries async from there - Nepomuk::Query::Query ourQuery(query); - // disable result restrictions since we do not support those in our custom model - ourQuery.setQueryFlags(Nepomuk::Query::Query::NoResultRestrictions); - Soprano::QueryResultIterator it = ResourceManager::instance()->mainModel()->executeQuery( ourQuery.toSparqlQuery(), Soprano::Query::QueryLanguageSparql ); - QList results; - while( it.next() ) { - results << Result( it[0].uri() ); - } - QMetaObject::invokeMethod( q, "_k_newEntries", Qt::QueuedConnection, Q_ARG(QList, results) ); - } -}; - - -DynamicResourceTestFacet::DynamicResourceTestFacet() - : DynamicResourceFacet() { - // replace the private thingi with our own implementation - delete d; - d = new TestPrivate; - d->q = this; -} - - -namespace { - - void waitForSignal( QObject* object, const char* signal, int timeout = 500 ) - { - QEventLoop loop; - loop.connect(object, signal, SLOT(quit())); - QTimer::singleShot(timeout, &loop, SLOT(quit())); - loop.exec(); - } - - Term buildTagTerm( const Tag& tag ) { - return Soprano::Vocabulary::NAO::hasTag() == ResourceTerm(tag); - } - - Term buildTagTermAll( const QList& tags ) { - AndTerm t; - foreach( const Tag& tag, tags ) - t.addSubTerm( buildTagTerm(tag) ); - return t.optimized(); - } - - Term buildTagTermAny( const QList& tags ) { - OrTerm t; - foreach( const Tag& tag, tags ) - t.addSubTerm( buildTagTerm(tag) ); - return t.optimized(); - } -} - - -void DynamicResourceFacetTest::initTestCase() -{ - // We create a dummy model with some simple test data in it - const Soprano::Backend* backend = Soprano::PluginManager::instance()->discoverBackendByName( "virtuosobackend" ); - QVERIFY( backend ); - m_storageDir = new KTempDir(); - m_model = backend->createModel( Soprano::BackendSettings() << Soprano::BackendSetting(Soprano::BackendOptionStorageDir, m_storageDir->name()) ); - QVERIFY( m_model ); - - Nepomuk::ResourceManager::instance()->setOverrideMainModel( m_model ); - - // We need basic ontology knowledge for the ResourceTypeTerm queries to work properly - const QUrl graph = Nepomuk::ResourceManager::instance()->generateUniqueUri(QString()); - m_model->addStatement(graph, Soprano::Vocabulary::RDF::type(), Soprano::Vocabulary::NRL::Ontology(), graph); - m_model->addStatement(graph, Soprano::Vocabulary::RDF::type(), Soprano::Vocabulary::NRL::InstanceBase(), graph); - m_model->addStatement(Soprano::Vocabulary::NAO::Tag(), Soprano::Vocabulary::RDFS::subClassOf(), Soprano::Vocabulary::NAO::Tag(), graph); - m_model->addStatement(Soprano::Vocabulary::NAO::hasTag(), Soprano::Vocabulary::RDF::type(), Soprano::Vocabulary::RDF::Property(), graph); - m_model->addStatement(Soprano::Vocabulary::NAO::hasTag(), Soprano::Vocabulary::RDFS::range(), Soprano::Vocabulary::NAO::Tag(), graph); - - // now some tags which will be our test resources - tag1 = Nepomuk::Tag( QLatin1String("Tag 1") ); - tag1.setLabel( QLatin1String("Tag 1") ); - kDebug() << tag1.resourceUri() << tag1.label(); - tag2 = Nepomuk::Tag( QLatin1String("Tag 2") ); - tag2.setLabel( QLatin1String("Tag 2") ); - kDebug() << tag2.resourceUri() << tag2.label(); - tag3 = Nepomuk::Tag( QLatin1String("Tag 3") ); - tag3.setLabel( QLatin1String("Tag 3") ); - kDebug() << tag3.resourceUri() << tag3.label(); - tag4 = Nepomuk::Tag( QLatin1String("Tag 4") ); - tag4.setLabel( QLatin1String("Tag 4") ); - kDebug() << tag4.resourceUri() << tag4.label(); - - // and some random resources that we will use for testing setClientQuery - Resource res1; - res1.addTag(tag1); - res1.addTag(tag2); - res1.addTag(tag3); - - Resource res2; - res2.addTag(tag2); - res2.addTag(tag3); - - Resource res3; - res3.addTag(tag4); - - // nothing is tagged with tag4 -} - - -void DynamicResourceFacetTest::cleanupTestCase() -{ - Nepomuk::ResourceManager::instance()->setOverrideMainModel( 0 ); - delete m_model; - delete m_storageDir; -} - - -void DynamicResourceFacetTest::testEmptyFacet() -{ - DynamicResourceFacet f; - QCOMPARE(f.count(), 0); - QCOMPARE(f.queryTerm(), Term()); -} - - -void DynamicResourceFacetTest::testSetRelation() -{ - DynamicResourceFacet f; - f.setRelation(Soprano::Vocabulary::NAO::hasTag()); - QCOMPARE(f.resourceType(), Nepomuk::Types::Class(Soprano::Vocabulary::NAO::Tag())); -} - - -void DynamicResourceFacetTest::testMatchOne() -{ - DynamicResourceTestFacet f; - f.setRelation(Soprano::Vocabulary::NAO::hasTag()); - f.setSelectionMode(Facet::MatchOne); - - // wait for the facet to be populated. Since this is happening async - // and there might be any number of layoutChanged() signals between 1 and 4 - // we can only wait for the number of choices to become 4 - int i = 4; - while( f.count() < 4 && i-- > 0 ) { - waitForSignal(&f, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*))); - } - QCOMPARE(f.count(), 4); - - // now the facet is initially populated - // test the matchone selection - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 1); - QCOMPARE(f.selectedResources().first(), f.resourceAt(0)); - QCOMPARE(f.queryTerm(), buildTagTerm(f.resourceAt(0))); - - f.setSelected(2); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 1); - QCOMPARE(f.selectedResources().first(), f.resourceAt(2)); - QCOMPARE(f.queryTerm(), buildTagTerm(f.resourceAt(2))); - - f.setSelected(2, false); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 1); - QCOMPARE(f.selectedResources().first(), f.resourceAt(0)); - QCOMPARE(f.queryTerm(), buildTagTerm(f.resourceAt(0))); - - f.setSelected(1); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 1); - QCOMPARE(f.selectedResources().first(), f.resourceAt(1)); - QCOMPARE(f.queryTerm(), buildTagTerm(f.resourceAt(1))); - - f.setSelected(3); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 1); - QCOMPARE(f.selectedResources().first(), f.resourceAt(3)); - QCOMPARE(f.queryTerm(), buildTagTerm(f.resourceAt(3))); - - f.clearSelection(); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 1); - QCOMPARE(f.selectedResources().first(), f.resourceAt(0)); - QCOMPARE(f.queryTerm(), buildTagTerm(f.resourceAt(0))); -} - - -void DynamicResourceFacetTest::testMatchAll() -{ - DynamicResourceTestFacet f; - f.setRelation(Soprano::Vocabulary::NAO::hasTag()); - f.setSelectionMode(Facet::MatchAll); - - // wait for the facet to be populated. Since this is happening async - // and there might be any number of layoutChanged() signals between 1 and 4 - // we can only wait for the number of choices to become 4 - int i = 4; - while( f.count() < 4 && i-- > 0 ) { - waitForSignal(&f, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*))); - } - QCOMPARE(f.count(), 4); - - // now the facet is initially populated - // test the matchall selection - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.queryTerm(), Term()); - QCOMPARE(f.selectedResources().count(), 0); - - f.setSelected(2); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 1); - QCOMPARE(f.selectedResources().first(), f.resourceAt(2)); - QCOMPARE(f.queryTerm(), buildTagTerm(f.resourceAt(2))); - - f.setSelected(1); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QVERIFY(f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 2); - QCOMPARE(f.queryTerm(), buildTagTermAll(QList() << f.resourceAt(1) << f.resourceAt(2))); - - f.setSelected(3); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QVERIFY(f.isSelected(2)); - QVERIFY(f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 3); - QCOMPARE(f.queryTerm(), buildTagTermAll(QList() << f.resourceAt(1) << f.resourceAt(2) << f.resourceAt(3))); - - f.setSelected(2, false); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 2); - QCOMPARE(f.queryTerm(), buildTagTermAll(QList() << f.resourceAt(1) << f.resourceAt(3))); - - f.clearSelection(); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.queryTerm(), Term()); - QCOMPARE(f.selectedResources().count(), 0); -} - - -void DynamicResourceFacetTest::testMatchAny() -{ - DynamicResourceTestFacet f; - f.setRelation(Soprano::Vocabulary::NAO::hasTag()); - f.setSelectionMode(Facet::MatchAny); - - // wait for the facet to be populated. Since this is happening async - // and there might be any number of layoutChanged() signals between 1 and 4 - // we can only wait for the number of choices to become 4 - int i = 4; - while( f.count() < 4 && i-- > 0 ) { - waitForSignal(&f, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*))); - } - QCOMPARE(f.count(), 4); - - // now the facet is initially populated - // test the matchall selection - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.queryTerm(), Term()); - QCOMPARE(f.selectedResources().count(), 0); - - f.setSelected(2); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 1); - QCOMPARE(f.selectedResources().first(), f.resourceAt(2)); - QCOMPARE(f.queryTerm(), buildTagTerm(f.resourceAt(2))); - - f.setSelected(1); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QVERIFY(f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 2); - QCOMPARE(f.queryTerm(), buildTagTermAny(QList() << f.resourceAt(1) << f.resourceAt(2))); - - f.setSelected(3); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QVERIFY(f.isSelected(2)); - QVERIFY(f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 3); - QCOMPARE(f.queryTerm(), buildTagTermAny(QList() << f.resourceAt(1) << f.resourceAt(2) << f.resourceAt(3))); - - f.setSelected(2, false); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(f.isSelected(3)); - QCOMPARE(f.selectedResources().count(), 2); - QCOMPARE(f.queryTerm(), buildTagTermAny(QList() << f.resourceAt(1) << f.resourceAt(3))); - - f.clearSelection(); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QVERIFY(!f.isSelected(2)); - QVERIFY(!f.isSelected(3)); - QCOMPARE(f.queryTerm(), Term()); - QCOMPARE(f.selectedResources().count(), 0); -} - - -void DynamicResourceFacetTest::testSetClientQuery() -{ -// DynamicResourceTestFacet f; -// f.setRelation(Soprano::Vocabulary::NAO::hasTag()); -// f.setSelectionMode(Facet::MatchAny); - -// // wait for the facet to be populated. Since this is happening async -// // and there might be any number of layoutChanged() signals between 1 and 4 -// // we can only wait for the number of choices to become 4 -// int i = 4; -// while( f.count() < 4 && i-- > 0 ) { -// waitForSignal(&f, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*))); -// } -// QCOMPARE(f.count(), 4); -} - -QTEST_KDEMAIN_CORE(DynamicResourceFacetTest) diff --git a/nepomuk/test/dynamicresourcefacettest.h b/nepomuk/test/dynamicresourcefacettest.h deleted file mode 100644 index 33497e64..00000000 --- a/nepomuk/test/dynamicresourcefacettest.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef DYNAMICRESOURCEFACETTEST_H -#define DYNAMICRESOURCEFACETTEST_H - -#include -#include "ktempdir.h" -#include "tag.h" -#include "dynamicresourcefacet.h" - -#include - -/** - * The only point of deriving from DynamicResourceFacet is to not use the query service - * which would ignore our custom model. This is done by touching the public API as little - * as possible. The only change necessary is a friend class declaration in the dynamicresourcefacet.h - * header. - */ -class DynamicResourceTestFacet : public Nepomuk::Utils::DynamicResourceFacet -{ -public: - DynamicResourceTestFacet(); - -private: - class TestPrivate; -}; - - -class DynamicResourceFacetTest : public QObject -{ - Q_OBJECT - -private slots: - void initTestCase(); - void cleanupTestCase(); - void testEmptyFacet(); - void testSetRelation(); - void testMatchOne(); - void testMatchAll(); - void testMatchAny(); - void testSetClientQuery(); - -private: - KTempDir* m_storageDir; - Soprano::Model* m_model; - Nepomuk::Tag tag1, tag2, tag3, tag4; -}; - -#endif // DYNAMICRESOURCEFACETTEST_H diff --git a/nepomuk/test/facetmodeltest.cpp b/nepomuk/test/facetmodeltest.cpp deleted file mode 100644 index b2d75ddf..00000000 --- a/nepomuk/test/facetmodeltest.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "facetmodeltest.h" -#include "qtest_kde.h" -#include "qtest_querytostring.h" - -#include "facetmodel.h" -#include "simplefacet.h" -#include "comparisonterm.h" -#include "resourcetypeterm.h" -#include "literalterm.h" -#include "proxyfacet.h" -#include "nfo.h" - -#include - - -using namespace Nepomuk::Utils; -using namespace Nepomuk::Query; - - -void FacetModelTest::testExtractFacetsFromTermWithVaryingSelectionMode() -{ - const Term term1 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()); - const Term term2 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Party()); - - SimpleFacet* f = new SimpleFacet; - f->addTerm( QLatin1String("t1"), term1 ); - f->addTerm( QLatin1String("t2"), term2 ); - - FacetModel model; - model.addFacet(f); - - // Test AND combination of terms for each selection mode - // ===================================================== - - // in MatchOne mode only one term should be extracted - f->setSelectionMode(Facet::MatchOne); - QCOMPARE( model.extractFacetsFromQuery(Query(term1 && term2)), Query(term2) ); - QCOMPARE( model.queryTerm(), term1 ); - - // in MatchAll mode both terms should be extracted - f->setSelectionMode(Facet::MatchAll); - QCOMPARE( model.extractFacetsFromQuery(Query(term1 && term2)), Query() ); - QCOMPARE( model.queryTerm(), term1 && term2 ); - - // in MatchAny mode no term should be extracted - f->setSelectionMode(Facet::MatchAny); - QCOMPARE( model.extractFacetsFromQuery(Query(term1 && term2)), Query(term2) ); - QCOMPARE( model.queryTerm(), term1 ); - - - // Test OR combination of terms for each selection mode - // ===================================================== - - // in MatchOne mode no term should be selected - f->setSelectionMode(Facet::MatchOne); - QCOMPARE( model.extractFacetsFromQuery(Query(term1 || term2)), Query(term1 || term2) ); - QCOMPARE( model.queryTerm(), term1 ); - - // in MatchAll mode no term should be extracted - f->setSelectionMode(Facet::MatchAll); - QCOMPARE( model.extractFacetsFromQuery(Query(term1 || term2)), Query(term1 || term2) ); - QCOMPARE( model.queryTerm(), Term() ); - - // in MatchAny mode both terms should be extracted - f->setSelectionMode(Facet::MatchAny); - QCOMPARE( model.extractFacetsFromQuery(Query(term1 || term2)), Query() ); - QCOMPARE( model.queryTerm(), term1 || term2 ); -} - - -void FacetModelTest::testExtractFacetsFromTermWithMultipleFacets() -{ - FacetModel model; - - SimpleFacet* f1 = new SimpleFacet; - f1->setSelectionMode(Facet::MatchOne); - f1->addTerm( QLatin1String("t1"), Term() ); - f1->addTerm( QLatin1String("t2"), ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()) ); - f1->addTerm( QLatin1String("t3"), ResourceTypeTerm(Soprano::Vocabulary::NAO::Party()) ); - f1->addTerm( QLatin1String("t4"), ResourceTypeTerm(Soprano::Vocabulary::NAO::Symbol()) ); - model.addFacet(f1); - - SimpleFacet* f2 = new SimpleFacet; - f2->setSelectionMode(Facet::MatchAll); - f2->addTerm( QLatin1String("t2"), Soprano::Vocabulary::NAO::numericRating() == LiteralTerm(2) ); - f2->addTerm( QLatin1String("t3"), Soprano::Vocabulary::NAO::numericRating() == LiteralTerm(3) ); - f2->addTerm( QLatin1String("t4"), Soprano::Vocabulary::NAO::numericRating() == LiteralTerm(4) ); - model.addFacet(f2); - - SimpleFacet* f3 = new SimpleFacet; - f3->setSelectionMode(Facet::MatchAny); - f3->addTerm( QLatin1String("t2"), Soprano::Vocabulary::NAO::prefLabel() == LiteralTerm(QLatin1String("l1")) ); - f3->addTerm( QLatin1String("t3"), Soprano::Vocabulary::NAO::prefLabel() == LiteralTerm(QLatin1String("l2")) ); - f3->addTerm( QLatin1String("t4"), Soprano::Vocabulary::NAO::prefLabel() == LiteralTerm(QLatin1String("l3")) ); - model.addFacet(f3); - - // now we test all kinds of combinations of the above terms to see if they are extracted correctly - - model.clearSelection(); - Term testTerm = f1->termAt(1) && f2->termAt(0) && f3->termAt(0); - Term restTerm; - Term queryTerm = testTerm; - QCOMPARE( model.extractFacetsFromQuery(Query(testTerm)), Query(restTerm) ); - QCOMPARE( model.queryTerm(), queryTerm ); - QCOMPARE( model.queryTerm() && restTerm, testTerm ); - - model.clearSelection(); - testTerm = f2->termAt(0) && f2->termAt(1) && f3->termAt(0); - restTerm = Term(); - queryTerm = testTerm; - QCOMPARE( model.extractFacetsFromQuery(Query(testTerm)), Query(restTerm) ); - QCOMPARE( model.queryTerm(), queryTerm ); - QCOMPARE( model.queryTerm() && restTerm, testTerm ); - - model.clearSelection(); - testTerm = f1->termAt(1) && f2->termAt(0) && f3->termAt(0) && f3->termAt(1); - restTerm = f3->termAt(1); - queryTerm = f1->termAt(1) && f2->termAt(0) && f3->termAt(0); - QCOMPARE( model.extractFacetsFromQuery(Query(testTerm)), Query(restTerm) ); - QCOMPARE( model.queryTerm(), queryTerm ); - QCOMPARE( model.queryTerm() && restTerm, testTerm ); - - model.clearSelection(); - testTerm = f1->termAt(1) && f2->termAt(0) && ( f3->termAt(0) || f3->termAt(1) ); - restTerm = Term(); - queryTerm = testTerm; - QCOMPARE( model.extractFacetsFromQuery(Query(testTerm)), Query(restTerm) ); - QCOMPARE( model.queryTerm(), queryTerm ); - QCOMPARE( model.queryTerm() && restTerm, testTerm ); - - model.clearSelection(); - testTerm = f3->termAt(0) || f3->termAt(1) || f3->termAt(2); - restTerm = Term(); - queryTerm = testTerm; - QCOMPARE( model.extractFacetsFromQuery(Query(testTerm)), Query(restTerm) ); - QCOMPARE( model.queryTerm(), queryTerm ); - QCOMPARE( model.queryTerm() && restTerm, testTerm ); - - model.clearSelection(); - testTerm = f3->termAt(0) || f3->termAt(1) || f3->termAt(2) || f1->termAt(1); - restTerm = testTerm; - queryTerm = Term(); - QCOMPARE( model.extractFacetsFromQuery(Query(testTerm)), Query(restTerm) ); - QCOMPARE( model.queryTerm(), queryTerm ); - QCOMPARE( model.queryTerm() && restTerm, testTerm ); - - model.clearSelection(); - testTerm = f3->termAt(0) && f3->termAt(1); - restTerm = f3->termAt(1); - queryTerm = f3->termAt(0); - QCOMPARE( model.extractFacetsFromQuery(Query(testTerm)), Query(restTerm) ); - QCOMPARE( model.queryTerm(), queryTerm ); - QCOMPARE( model.queryTerm() && restTerm, testTerm ); -} - - -void FacetModelTest::testExtractFacetsFromTermWithProxyFacet() -{ - FacetModel model; - - SimpleFacet* f1 = new SimpleFacet; - f1->setSelectionMode(Facet::MatchAny); - f1->addTerm( QLatin1String("t1"), ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()) ); - f1->addTerm( QLatin1String("t2"), ResourceTypeTerm(Nepomuk::Vocabulary::NFO::FileDataObject()) ); - model.addFacet(f1); - - SimpleFacet* f2 = new SimpleFacet; - f2->setSelectionMode(Facet::MatchAny); - f2->addTerm( QLatin1String("t1"), ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Image()) ); - f2->addTerm( QLatin1String("t2"), ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Document()) ); - - ProxyFacet* f2p = new ProxyFacet; - f2p->setSourceFacet(f2); - f2p->setFacetCondition(f1->termAt(1)); - model.addFacet(f2p); - - model.clearSelection(); - Term testTerm = f1->termAt(0) && f2->termAt(0); - Term restTerm = f2->termAt(0); - Term queryTerm = f1->termAt(0); - QCOMPARE( model.extractFacetsFromQuery(Query(testTerm)), Query(restTerm) ); - QCOMPARE( model.queryTerm(), queryTerm ); - QCOMPARE( model.queryTerm() && restTerm, testTerm ); - - model.clearSelection(); - testTerm = f1->termAt(1) && f2->termAt(0); - restTerm = Term(); - queryTerm = testTerm; - QCOMPARE( model.extractFacetsFromQuery(Query(testTerm)), Query(restTerm) ); - QCOMPARE( model.queryTerm(), queryTerm ); - QCOMPARE( model.queryTerm() && restTerm, testTerm ); -} - -QTEST_KDEMAIN_CORE(FacetModelTest) diff --git a/nepomuk/test/facetmodeltest.h b/nepomuk/test/facetmodeltest.h deleted file mode 100644 index 42544b4b..00000000 --- a/nepomuk/test/facetmodeltest.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef FACETMODELTEST_H -#define FACETMODELTEST_H - -#include - -class FacetModelTest : public QObject -{ - Q_OBJECT - -private slots: - void testExtractFacetsFromTermWithVaryingSelectionMode(); - void testExtractFacetsFromTermWithMultipleFacets(); - void testExtractFacetsFromTermWithProxyFacet(); -}; - -#endif // FACETMODELTEST_H diff --git a/nepomuk/test/proxyfacettest.cpp b/nepomuk/test/proxyfacettest.cpp deleted file mode 100644 index ac61523c..00000000 --- a/nepomuk/test/proxyfacettest.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "proxyfacettest.h" -#include "qtest_querytostring.h" - -#include "simplefacet.h" -#include "proxyfacet.h" -#include "comparisonterm.h" -#include "resourcetypeterm.h" -#include "query.h" - -#include - -#include -#include "qtest_kde.h" - -using namespace Nepomuk::Utils; -using namespace Nepomuk::Query; - -Q_DECLARE_METATYPE(Nepomuk::Utils::Facet*) - -void ProxyFacetTest::initTestCase() -{ - qRegisterMetaType(); -} - -void ProxyFacetTest::testForward() -{ - SimpleFacet f; - f.setSelectionMode(Facet::MatchOne); - - QString label1 = QLatin1String("Label 1"); - Term term1; - QString label2 = QLatin1String("Label 2"); - Term term2 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()); - - f.addTerm(label1, term1); - f.addTerm(label2, term2); - - ProxyFacet pf; - pf.setSourceFacet(&f); - - QCOMPARE(f.count(), pf.count()); - - QCOMPARE(f.text(0), pf.text(0)); - QCOMPARE(f.text(1), pf.text(1)); - - QCOMPARE(f.queryTerm(), pf.queryTerm()); - - f.setSelected(1); - QCOMPARE(f.isSelected(0), pf.isSelected(0)); - QCOMPARE(f.isSelected(1), pf.isSelected(1)); - QCOMPARE(f.queryTerm(), pf.queryTerm()); -} - -void ProxyFacetTest::testSignals() -{ - SimpleFacet f; - f.setSelectionMode(Facet::MatchOne); - - QString label1 = QLatin1String("Label 1"); - Term term1; - QString label2 = QLatin1String("Label 2"); - Term term2 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()); - - f.addTerm(label1, term1); - f.addTerm(label2, term2); - - ProxyFacet pf; - pf.setSourceFacet(&f); - - QSignalSpy selectionSpy(&pf, SIGNAL(selectionChanged(Nepomuk::Utils::Facet*))); - QSignalSpy termChangedSpy(&pf, SIGNAL(queryTermChanged(Nepomuk::Utils::Facet*,Nepomuk::Query::Term))); - - pf.setSelected(1); - QCOMPARE(selectionSpy.count(), 1); - selectionSpy.takeFirst(); - QCOMPARE(termChangedSpy.count(), 1); - termChangedSpy.takeFirst(); - - pf.clearSelection(); - QCOMPARE(selectionSpy.count(), 1); - selectionSpy.takeFirst(); - QCOMPARE(termChangedSpy.count(), 1); - termChangedSpy.takeFirst(); - - QSignalSpy laySpy(&pf, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*))); - f.addTerm(QLatin1String("Hello World"), Term()); - QCOMPARE(laySpy.count(), 1); - laySpy.takeFirst(); -} - -void ProxyFacetTest::testFacetCondition() -{ - SimpleFacet f; - f.setSelectionMode(Facet::MatchOne); - - QString label1 = QLatin1String("Label 1"); - Term term1; - QString label2 = QLatin1String("Label 2"); - Term term2 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()); - - f.addTerm(label1, term1); - f.addTerm(label2, term2); - - ProxyFacet pf; - pf.setSourceFacet(&f); - - QSignalSpy laySpy(&pf, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*))); - - pf.setFacetCondition(ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag())); - - QCOMPARE(laySpy.count(), 1); - laySpy.takeFirst(); - - QCOMPARE(pf.count(), 0); - QCOMPARE(pf.queryTerm(), Term()); - - pf.setClientQuery(Query(ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()))); - - QCOMPARE(laySpy.count(), 1); - laySpy.takeFirst(); - - QCOMPARE(f.count(), pf.count()); - - QCOMPARE(f.text(0), pf.text(0)); - QCOMPARE(f.text(1), pf.text(1)); - - QCOMPARE(f.queryTerm(), pf.queryTerm()); -} - -QTEST_KDEMAIN_CORE(ProxyFacetTest) diff --git a/nepomuk/test/proxyfacettest.h b/nepomuk/test/proxyfacettest.h deleted file mode 100644 index 9075dd21..00000000 --- a/nepomuk/test/proxyfacettest.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef PROXYFACETTEST_H -#define PROXYFACETTEST_H - -#include - -class ProxyFacetTest : public QObject -{ - Q_OBJECT - -private slots: - void initTestCase(); - void testForward(); - void testSignals(); - void testFacetCondition(); -}; - -#endif // PROXYFACETTEST_H diff --git a/nepomuk/test/qtest_querytostring.h b/nepomuk/test/qtest_querytostring.h deleted file mode 100644 index 6e01f637..00000000 --- a/nepomuk/test/qtest_querytostring.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QTEST_QUERY_TO_STRING_H_ -#define _NEPOMUK_QTEST_QUERY_TO_STRING_H_ - -#include "query.h" -#include "term.h" -#include "class.h" - -#include - -namespace QTest { - template<> - char* toString(const Nepomuk::Query::Query& query) { - return qstrdup( query.toString().toUtf8().data() ); - } - - template<> - char* toString(const Nepomuk::Query::Term& term) { - return qstrdup( term.toString().toUtf8().data() ); - } - - template<> - char* toString(const Nepomuk::Types::Class& e) { - return qstrdup( e.uri().toString().toUtf8().data() ); - } -} - -#endif diff --git a/nepomuk/test/queryparsertest.cpp b/nepomuk/test/queryparsertest.cpp deleted file mode 100644 index 6c059cf0..00000000 --- a/nepomuk/test/queryparsertest.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "queryparsertest.h" -#include "qtest_querytostring.h" -#include "queryparser.h" -#include "query.h" -#include "literalterm.h" -#include "resourceterm.h" -#include "andterm.h" -#include "orterm.h" -#include "negationterm.h" -#include "comparisonterm.h" -#include "nfo.h" - -#include -#include - -#include "ktempdir.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "property.h" -#include "resourcemanager.h" - -Q_DECLARE_METATYPE( Nepomuk::Query::Query ) - -using namespace Nepomuk::Query; - -void QueryParserTest::initTestCase() -{ - // we need to use a Virtuoso model as tmp model since redland misses important SPARQL features - // that are used by libnepomuk below - const Soprano::Backend* backend = Soprano::PluginManager::instance()->discoverBackendByName( "virtuosobackend" ); - QVERIFY( backend ); - m_storageDir = new KTempDir(); - m_model = backend->createModel( Soprano::BackendSettings() << Soprano::BackendSetting(Soprano::BackendOptionStorageDir, m_storageDir->name()) ); - QVERIFY( m_model ); - - // we create one fake ontology - QUrl graph("graph:/onto"); - m_model->addStatement( graph, Soprano::Vocabulary::RDF::type(), Soprano::Vocabulary::NRL::Ontology(), graph ); - - m_model->addStatement( QUrl("onto:/label"), Soprano::Vocabulary::RDF::type(), Soprano::Vocabulary::RDF::Property(), graph ); - m_model->addStatement( QUrl("onto:/label"), Soprano::Vocabulary::RDFS::label(), Soprano::LiteralValue::createPlainLiteral("label"), graph ); - m_model->addStatement( QUrl("onto:/label"), Soprano::Vocabulary::RDFS::range(), Soprano::Vocabulary::XMLSchema::string(), graph ); - - m_model->addStatement( QUrl("onto:/hasTag"), Soprano::Vocabulary::RDF::type(), Soprano::Vocabulary::RDF::Property(), graph ); - m_model->addStatement( QUrl("onto:/hasTag"), Soprano::Vocabulary::RDFS::label(), Soprano::LiteralValue::createPlainLiteral("has tag"), graph ); - m_model->addStatement( QUrl("onto:/hasTag"), Soprano::Vocabulary::RDFS::range(), QUrl("onto:/Tag"), graph ); - - m_model->addStatement( QUrl("onto:/tag"), Soprano::Vocabulary::RDF::type(), Soprano::Vocabulary::RDF::Property(), graph ); - m_model->addStatement( QUrl("onto:/tag"), Soprano::Vocabulary::RDFS::label(), Soprano::LiteralValue::createPlainLiteral("hastag"), graph ); - m_model->addStatement( QUrl("onto:/tag"), Soprano::Vocabulary::RDFS::range(), QUrl("onto:/Tag"), graph ); - - m_model->addStatement( QUrl("onto:/Tag"), Soprano::Vocabulary::RDF::type(), Soprano::Vocabulary::RDFS::Class(), graph ); - - m_model->addStatement( QUrl("onto:/int"), Soprano::Vocabulary::RDF::type(), Soprano::Vocabulary::RDF::Property(), graph ); - m_model->addStatement( QUrl("onto:/int"), Soprano::Vocabulary::RDFS::label(), Soprano::LiteralValue::createPlainLiteral("int value"), graph ); - m_model->addStatement( QUrl("onto:/int"), Soprano::Vocabulary::RDFS::range(), Soprano::Vocabulary::XMLSchema::integer(), graph ); - - Nepomuk::ResourceManager::instance()->setOverrideMainModel( m_model ); -} - - -void QueryParserTest::cleanupTestCase() -{ - Nepomuk::ResourceManager::instance()->setOverrideMainModel( 0 ); - delete m_model; - delete m_storageDir; -} - - -void QueryParserTest::testQueryParser_data() -{ - QTest::addColumn( "queryString" ); - QTest::addColumn( "query" ); - - // the invalid query - QTest::newRow( "empty query string" ) << QString() << Query(); - - // simple literal queries - QTest::newRow( "simple literal query" ) << QString( "Hello" ) << Query( LiteralTerm( "Hello" ) ); - QTest::newRow( "literal with spaces without quotes" ) << QString( "Hello World" ) << Query( LiteralTerm("Hello AND World" ) ); - QTest::newRow( "literal with spaces with quotes" ) << QString( "'Hello World'" ) << Query( LiteralTerm( "'Hello World'" ) ); - - // comparison queries - QTest::newRow( "simple field query" ) << QString( "hastag:nepomuk" ) - << Query( OrTerm( ComparisonTerm( QUrl("onto:/hasTag"), LiteralTerm( "nepomuk" ) ), - ComparisonTerm( QUrl("onto:/tag"), LiteralTerm( "nepomuk" ) ) ) ); - QTest::newRow( "simple property query" ) << QString( ":nepomuk" ) - << Query( ComparisonTerm( QUrl("onto:/hasTag"), LiteralTerm( "nepomuk" ) ) ); -#ifdef QUERY_PARSER_SUPPORTS_RESOURCE_VALUES - QTest::newRow( "resource field query" ) << QString( "hastag:" ) - << Query( ComparisonTerm( "hastag", ResourceTerm( QUrl( "nepomuk:/Nepomuk" ) ) ) ); -#endif - QTest::newRow( "nested resource query" ) << QString( "hastag:(label:nepomuk)" ) - << Query( OrTerm( ComparisonTerm( QUrl("onto:/hasTag"), ComparisonTerm( QUrl("onto:/label"), LiteralTerm( "nepomuk" ) ) ), - ComparisonTerm( QUrl("onto:/tag"), ComparisonTerm( QUrl("onto:/label"), LiteralTerm( "nepomuk" ) ) ) ) ); - QTest::newRow( "int property query" ) << QString( "'int value':42" ) - << Query( ComparisonTerm( QUrl("onto:/int"), LiteralTerm( 42 ) ) ); - QTest::newRow( "int property query 2" ) << QString( "int:\"42\"" ) - << Query( ComparisonTerm( QUrl("onto:/int"), LiteralTerm( 42 ) ) ); - - - // negation - QTest::newRow( "simple negation" ) << QString( "-Hello" ) << Query( NegationTerm::negateTerm( LiteralTerm( "Hello" ) ) ); - QTest::newRow( "field negation" ) << QString( "-label:nepomuk" ) << Query( NegationTerm::negateTerm( ComparisonTerm( QUrl("onto:/label"), LiteralTerm( "nepomuk" ) ) ) ); - - // and query - QTest::newRow( "and: two literals" ) << QString( "Hello World" ) << Query( LiteralTerm( "Hello AND World" ) ); - QTest::newRow( "and: two literals with AND" ) << QString( "Hello AND World" ) << Query( LiteralTerm( "Hello AND World" ) ) ; - - // or queries - QTest::newRow( "or: two literals" ) << QString( "Hello OR World" ) << Query( OrTerm( LiteralTerm( "Hello" ), LiteralTerm( "World" ) ) ); -} - - -void QueryParserTest::testQueryParser() -{ - QFETCH( QString, queryString ); - QFETCH( Nepomuk::Query::Query, query ); - - Query q = QueryParser::parseQuery( queryString ); - - QCOMPARE( q, query ); -} - - -void QueryParserTest::testQueryParserWithGlobbing_data() -{ - QTest::addColumn( "queryString" ); - QTest::addColumn( "query" ); - - // simple literal queries - QTest::newRow( "simple literal query" ) << QString( "Hello" ) << Query( LiteralTerm( "Hello*" ) ); - QTest::newRow( "simple literal query" ) << QString( "\"Hello\"" ) << Query( LiteralTerm( "\"Hello\"" ) ); - QTest::newRow( "literal with spaces without quotes" ) << QString( "Hello World" ) << Query( LiteralTerm("Hello* AND World*" ) ); - QTest::newRow( "literal with spaces with quotes" ) << QString( "'Hello World'" ) << Query( LiteralTerm( "'Hello World'" ) ); -} - - -void QueryParserTest::testQueryParserWithGlobbing() -{ - QFETCH( QString, queryString ); - QFETCH( Nepomuk::Query::Query, query ); - - QueryParser p; - Query q = p.parse( queryString, QueryParser::QueryTermGlobbing ); - - QCOMPARE( q, query ); -} - - -void QueryParserTest::testQueryParserDetectFilenamePattern_data() -{ - QTest::addColumn( "queryString" ); - QTest::addColumn( "query" ); - - QTest::newRow( "DetectFilenamePattern1" ) << QString( "*.mp3" ) << Query( ComparisonTerm( Nepomuk::Vocabulary::NFO::fileName(), - LiteralTerm( "^.*\\\\.mp3$" ), - ComparisonTerm::Regexp ) ); - QTest::newRow( "DetectFilenamePattern2" ) << QString( "hello?.txt" ) << Query( ComparisonTerm( Nepomuk::Vocabulary::NFO::fileName(), - LiteralTerm( "^hello.\\\\.txt$" ), - ComparisonTerm::Regexp ) ); - QTest::newRow( "DetectFilenamePattern3" ) << QString( "*.???" ) << Query( ComparisonTerm( Nepomuk::Vocabulary::NFO::fileName(), - LiteralTerm( "^.*\\\\....$" ), - ComparisonTerm::Regexp ) ); -} - - -void QueryParserTest::testQueryParserDetectFilenamePattern() -{ - QFETCH( QString, queryString ); - QFETCH( Nepomuk::Query::Query, query ); - - QueryParser p; - Query q = p.parse( queryString, QueryParser::DetectFilenamePattern ); - - QCOMPARE( q, query ); -} - -QTEST_KDEMAIN_CORE( QueryParserTest ) - -#include "queryparsertest.moc" diff --git a/nepomuk/test/queryparsertest.h b/nepomuk/test/queryparsertest.h deleted file mode 100644 index 920d8568..00000000 --- a/nepomuk/test/queryparsertest.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_PARSER_TEST_H_ -#define _NEPOMUK_QUERY_PARSER_TEST_H_ - -#include -#include "ktempdir.h" - -#include - -class QueryParserTest : public QObject -{ - Q_OBJECT - -private Q_SLOTS: - void initTestCase(); - void cleanupTestCase(); - void testQueryParser_data(); - void testQueryParser(); - void testQueryParserWithGlobbing_data(); - void testQueryParserWithGlobbing(); - void testQueryParserDetectFilenamePattern_data(); - void testQueryParserDetectFilenamePattern(); - -private: - KTempDir* m_storageDir; - Soprano::Model* m_model; -}; - -#endif - - diff --git a/nepomuk/test/queryserializertest.cpp b/nepomuk/test/queryserializertest.cpp deleted file mode 100644 index 781f02ce..00000000 --- a/nepomuk/test/queryserializertest.cpp +++ /dev/null @@ -1,292 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "queryserializertest.h" - -#include "filequery.h" -#include "literalterm.h" -#include "resourceterm.h" -#include "andterm.h" -#include "orterm.h" -#include "negationterm.h" -#include "comparisonterm.h" -#include "resourcetypeterm.h" -#include "optionalterm.h" -#include "nie.h" -#include "nfo.h" -#include "nco.h" -#include "pimo.h" -#include "property.h" - -#include - -#include -#include -#include -#include -#include - -#include -#include - -Q_DECLARE_METATYPE( Nepomuk::Query::Query ) - -using namespace Nepomuk::Query; - - -void QuerySerializerTest::testSerialization_data() -{ - QTest::addColumn( "query" ); - - QTest::newRow( "simple literal query" ) - << Query( LiteralTerm( "Hello" ) ); - - QTest::newRow( "simple literal query with space" ) - << Query( LiteralTerm( "Hello World" ) ); - QTest::newRow( "simple literal query with space and quotes" ) - << Query( LiteralTerm( "'Hello World'" ) ); - QTest::newRow( "simple literal query with space and quotes" ) - << Query( LiteralTerm( "\"Hello World\"" ) ); - - QTest::newRow( "literal query with depth 2" ) - << Query( AndTerm( LiteralTerm("foo"), ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ComparisonTerm( Soprano::Vocabulary::NAO::prefLabel(), LiteralTerm("bar") ) ) ) ); - - QTest::newRow( "type query" ) - << Query( ResourceTypeTerm( Soprano::Vocabulary::NAO::Tag() ) ); - - QTest::newRow( "negated resource type" ) - << Query( NegationTerm::negateTerm( ResourceTypeTerm( Soprano::Vocabulary::NAO::Tag() ) ) ); - - QDateTime now = QDateTime::currentDateTime(); - QTest::newRow( "nie:lastModified" ) - << Query( ComparisonTerm( Nepomuk::Vocabulary::NIE::lastModified(), LiteralTerm( now ), ComparisonTerm::GreaterOrEqual ) ); - - QTest::newRow( "hastag with literal term" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), LiteralTerm( QLatin1String("nepomuk")) ) ); - - QTest::newRow( "hastag with resource" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) )); - - QTest::newRow( "negated hastag with resource" ) - << Query( NegationTerm::negateTerm(ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) ))); - - QTest::newRow( "comparators <" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Smaller ) ); - - QTest::newRow( "comparators <=" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::SmallerOrEqual ) ); - - QTest::newRow( "comparators >" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Greater ) ); - - QTest::newRow( "comparators >=" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::GreaterOrEqual ) ); - - QTest::newRow( "inverted comparisonterm" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) ).inverted() ); - - QTest::newRow( "optional term" ) - << Query(OptionalTerm::optionalizeTerm(ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) ))); - - QTest::newRow( "and term" ) - << Query( AndTerm( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Greater ), - ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm(QUrl("nepomuk:/test")) ) ) ); - - ComparisonTerm setVarNameTerm1( Soprano::Vocabulary::NAO::hasTag(), ResourceTypeTerm( Soprano::Vocabulary::NAO::Tag() ) ); - setVarNameTerm1.setVariableName("myvar"); - QTest::newRow( "set variable name 1" ) - << Query( setVarNameTerm1 ); - - ComparisonTerm setVarNameTerm2( Soprano::Vocabulary::NAO::hasTag(), LiteralTerm( "nepomuk" ) ); - setVarNameTerm2.setVariableName( "myvar" ); - QTest::newRow( "set variable name 2" ) - << Query( setVarNameTerm2 ); - - ComparisonTerm setVarNameTerm3( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Smaller ); - setVarNameTerm3.setVariableName("myvar"); - QTest::newRow( "set variable name 3" ) - << Query( setVarNameTerm3 ); - - ComparisonTerm setVarNameTerm4( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Smaller ); - setVarNameTerm3.setVariableName("myvar" ); - setVarNameTerm3.setAggregateFunction(ComparisonTerm::Count); - QTest::newRow( "set variable name 4 (with aggregate function count)" ) - << Query( setVarNameTerm3 ); - - ComparisonTerm orderByTerm1( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Smaller ); - orderByTerm1.setSortWeight( 1 ); - QTest::newRow( "order by 1" ) - << Query( orderByTerm1 ); - - orderByTerm1.setSortWeight( 1, Qt::DescendingOrder ); - QTest::newRow( "order by 2" ) - << Query( orderByTerm1 ); - - ComparisonTerm orderByTerm2( Soprano::Vocabulary::NAO::prefLabel(), LiteralTerm("hello") ); - orderByTerm2.setSortWeight( 2 ); - - QTest::newRow( "order by 3" ) - << Query( AndTerm( orderByTerm1, orderByTerm2 ) ); - - orderByTerm1.setVariableName("myvar"); - QTest::newRow( "order by 4" ) - << Query( orderByTerm1 ); - - QTest::newRow( "ComparisonTerm with invalid property" ) - << Query( ComparisonTerm( Nepomuk::Types::Property(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) )); - - QTest::newRow( "ComparisonTerm with invalid subterm" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), Term() ) ); - - QTest::newRow( "ComparisonTerm with invalid property and subterm" ) - << Query( ComparisonTerm( Nepomuk::Types::Property(), Term() ) ); - - ComparisonTerm orderByTerm5( Soprano::Vocabulary::NAO::numericRating(), Term() ); - orderByTerm5.setSortWeight( 1 ); - orderByTerm5.setAggregateFunction( ComparisonTerm::Max ); - QTest::newRow( "order by 5 (with aggregate function and invalid subterm)" ) - << Query( orderByTerm5 ); - - orderByTerm5.setVariableName( "myvar" ); - QTest::newRow( "order by 5 (with aggregate function and invalid subterm and varname)" ) - << Query( orderByTerm5 ); - - orderByTerm5.setVariableName( QString() ); - orderByTerm5.setAggregateFunction( ComparisonTerm::DistinctCount ); - QTest::newRow( "order by 5 (with aggregate function and invalid subterm and varname)" ) - << Query( orderByTerm5 ); - - - FileQuery fileQuery( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm(QUrl("nepomuk:/res/foobar")) ) ); - QTest::newRow( "file query" ) - << Query(fileQuery); - - fileQuery.setFileMode(FileQuery::QueryFiles); - QTest::newRow( "file query (only files)" ) - << Query(fileQuery); - - fileQuery.setFileMode(FileQuery::QueryFolders); - QTest::newRow( "file query (only folders)" ) - << Query(fileQuery); - - fileQuery.setFileMode(FileQuery::QueryFolders|FileQuery::QueryFiles); - fileQuery.addIncludeFolder( KUrl("/tmp"), true ); - fileQuery.addIncludeFolder( KUrl("/wurst"), false ); - fileQuery.addExcludeFolder( KUrl("/tmp/hello") ); - QTest::newRow( "file query with include and exclude folders" ) - << Query(fileQuery); - - // - // A more complex example - // - QUrl res("nepomuk:/res/foobar"); - AndTerm mainTerm; - OrTerm typeOr; - typeOr.addSubTerm( ResourceTypeTerm( Nepomuk::Vocabulary::NFO::RasterImage() ) ); - typeOr.addSubTerm( ResourceTypeTerm( Nepomuk::Vocabulary::NFO::Audio() ) ); - mainTerm.addSubTerm( typeOr ); - mainTerm.addSubTerm( NegationTerm::negateTerm( ComparisonTerm( Nepomuk::Types::Property(), ResourceTerm( res ) ).inverted() ) ); - - // an empty comparisonterm results in "?r ?v1 ?v2" - ComparisonTerm ct; - - // change the var name: "?r ?v1 ?cnt" - ct.setVariableName( "cnt" ); - ct.setAggregateFunction( ComparisonTerm::Count ); - - // by default all have 0, Query::toSparqlQuery will add ORDER BY for all ComparisonTerm with sortweight != 0 - ct.setSortWeight( 1, Qt::DescendingOrder ); - - mainTerm.addSubTerm(ct.inverted()); - - QTest::newRow( "a complex one" ) - << Query( mainTerm ); - - - // try to combine it all - Query allQuery( OrTerm( - NegationTerm::negateTerm( ResourceTypeTerm( Soprano::Vocabulary::NAO::Tag() ) ), - OptionalTerm::optionalizeTerm( LiteralTerm("hello 3") ), - AndTerm( - LiteralTerm("hello"), - LiteralTerm("hello 2"), - ResourceTerm( QUrl("nepomuk:/res/foobar") ), - ResourceTypeTerm( Soprano::Vocabulary::NAO::Tag() ), - ComparisonTerm( Nepomuk::Types::Property(), - ResourceTerm( QUrl("nepomuk:/res/foobar") ) ), - ComparisonTerm( Nepomuk::Types::Property(), - OrTerm( ResourceTerm( QUrl("nepomuk:/res/foobar1") ), - ResourceTerm( QUrl("nepomuk:/res/foobar2") ) ) ) ) ) ); - allQuery.setLimit( 10 ); - allQuery.setOffset( 2 ); - - QTest::newRow( "all" ) - << allQuery; - - FileQuery fileAllQuery( allQuery ); - fileAllQuery.addIncludeFolder( KUrl("/home/trueg/1") ); - fileAllQuery.addIncludeFolder( KUrl("/home/trueg/2") ); - fileAllQuery.addExcludeFolder( KUrl("/home/trueg/3") ); - fileAllQuery.addExcludeFolder( KUrl("/home/trueg/4") ); - QTest::newRow( "fileall" ) - << Query(fileAllQuery); - - - Query flagsQuery; - flagsQuery.setQueryFlags( Query::NoResultRestrictions ); - QTest::newRow( "flags" ) - << flagsQuery; - - flagsQuery.setQueryFlags( Query::WithoutFullTextExcerpt ); - QTest::newRow( "flags2" ) - << flagsQuery; - - flagsQuery.setQueryFlags( Query::NoResultRestrictions|Query::WithoutFullTextExcerpt ); - QTest::newRow( "flags3" ) - << flagsQuery; - - flagsQuery.setFullTextScoringEnabled( true ); - QTest::newRow( "fullTextScoring 1" ) - << flagsQuery; - - flagsQuery.setFullTextScoringEnabled( true ); - flagsQuery.setFullTextScoringSortOrder( Qt::DescendingOrder ); - QTest::newRow( "fullTextScoring 2" ) - << flagsQuery; - -} - - -void QuerySerializerTest::testSerialization() -{ - QFETCH( Nepomuk::Query::Query, query ); - -// qDebug() << "Before:" << serializeQuery( query ); -// qDebug() << "After: " << serializeQuery( parseQuery( serializeQuery( query ) ) ); - - QCOMPARE( Query::fromString( query.toString() ), query ); - QCOMPARE( Term::fromString( query.term().toString() ), query.term() ); - QCOMPARE( Query::fromString( query.toString() ).toSparqlQuery(), query.toSparqlQuery() ); -} - -QTEST_KDEMAIN_CORE( QuerySerializerTest ) - -#include "queryserializertest.moc" diff --git a/nepomuk/test/queryserializertest.h b/nepomuk/test/queryserializertest.h deleted file mode 100644 index 04f482a1..00000000 --- a/nepomuk/test/queryserializertest.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_SERIALIZER_TEST_H_ -#define _NEPOMUK_QUERY_SERIALIZER_TEST_H_ - -#include - -class QuerySerializerTest : public QObject -{ - Q_OBJECT - -private Q_SLOTS: - void testSerialization_data(); - void testSerialization(); -}; - -#endif - - diff --git a/nepomuk/test/querytest.cpp b/nepomuk/test/querytest.cpp deleted file mode 100644 index 0a23a41e..00000000 --- a/nepomuk/test/querytest.cpp +++ /dev/null @@ -1,664 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "querytest.h" -#include "qtest_querytostring.h" - -#include "query.h" -#include "filequery.h" -#include "literalterm.h" -#include "resourceterm.h" -#include "andterm.h" -#include "orterm.h" -#include "negationterm.h" -#include "comparisonterm.h" -#include "resourcetypeterm.h" -#include "optionalterm.h" -#include "nie.h" -#include "nfo.h" -#include "nco.h" -#include "pimo.h" -#include "property.h" -#include "variant.h" -#include "resource.h" - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -Q_DECLARE_METATYPE( Nepomuk::Query::Query ) - -using namespace Nepomuk::Query; -using namespace Nepomuk::Vocabulary; - - -// this is a tricky one as we nee to match the variable names and order of the queries exactly. -void QueryTest::testToSparql_data() -{ - QTest::addColumn( "query" ); - QTest::addColumn( "queryString" ); - - Query simpleLiteralQuery( LiteralTerm( "Hello" ) ); - simpleLiteralQuery.setFullTextScoringEnabled( true ); - QTest::newRow( "simple literal query" ) - << simpleLiteralQuery - << QString::fromLatin1( "select distinct ?r max(?v5) as ?_n_f_t_m_s_ where { { ?r ?v1 ?v3 . ?v3 bif:contains \"'Hello'\" OPTION (score ?v5) . } " - "UNION { ?r ?v1 ?v4 . ?v4 ?v2 ?v3 . ?v2 %1 %2 . ?v3 bif:contains \"'Hello'\" OPTION (score ?v5) . } . } ORDER BY DESC ( ?_n_f_t_m_s_ )" ) - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::subPropertyOf()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::label()) ); - - - QTest::newRow( "simple literal query with space" ) - << Query( LiteralTerm( "Hello World" ) ) - << QString::fromLatin1( "select distinct ?r where { { ?r ?v1 ?v3 . FILTER(bif:contains(?v3, \"'Hello' AND 'World'\")) . } " - "UNION " - "{ ?r ?v1 ?v4 . ?v4 ?v2 ?v3 . ?v2 %1 %2 . FILTER(bif:contains(?v3, \"'Hello' AND 'World'\")) . } . }" ) - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::subPropertyOf()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::label()) ); - const QString helloWorldQuery = QString::fromLatin1( "select distinct ?r where { { ?r ?v1 ?v3 . FILTER(bif:contains(?v3, \"'Hello World'\")) . } " - "UNION " - "{ ?r ?v1 ?v4 . ?v4 ?v2 ?v3 . ?v2 %1 %2 . FILTER(bif:contains(?v3, \"'Hello World'\")) . } . }" ) - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::subPropertyOf()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::label()) ); - QTest::newRow( "simple literal query with space and quotes" ) - << Query( LiteralTerm( "'Hello World'" ) ) - << helloWorldQuery; - QTest::newRow( "simple literal query with space and double quotes" ) - << Query( LiteralTerm( "\"Hello World\"" ) ) - << helloWorldQuery; - - QTest::newRow( "simple literal query with wildcard 1" ) - << Query( LiteralTerm( "Hello*" ) ) - << QString::fromLatin1( "select distinct ?r where { { ?r ?v1 ?v3 . FILTER(bif:contains(?v3, \"'Hello*'\")) . } " - "UNION " - "{ ?r ?v1 ?v4 . ?v4 ?v2 ?v3 . ?v2 %1 %2 . FILTER(bif:contains(?v3, \"'Hello*'\")) . } . }" ) - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::subPropertyOf()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::label()) ); - QTest::newRow( "simple literal query with wildcard 2" ) - << Query( LiteralTerm( "*Hello" ) ) - << QString::fromLatin1( "select distinct ?r where { { ?r ?v1 ?v3 . FILTER(REGEX(?v3, \".*Hello\")) . } " - "UNION " - "{ ?r ?v1 ?v4 . ?v4 ?v2 ?v3 . ?v2 %1 %2 . FILTER(REGEX(?v3, \".*Hello\")) . } . }" ) - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::subPropertyOf()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::label()) ); - QTest::newRow( "simple literal query with wildcard 3" ) - << Query( LiteralTerm( "Hel?o" ) ) - << QString::fromLatin1( "select distinct ?r where { { ?r ?v1 ?v3 . FILTER(REGEX(?v3, \"Hel.o\")) . } " - "UNION " - "{ ?r ?v1 ?v4 . ?v4 ?v2 ?v3 . ?v2 %1 %2 . FILTER(REGEX(?v3, \"Hel.o\")) . } . }" ) - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::subPropertyOf()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::label()) ); - - Query literalQueryWithDepth2( - AndTerm( LiteralTerm("foo"), - ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), - ComparisonTerm( Soprano::Vocabulary::NAO::prefLabel(), LiteralTerm("bar") ) ) ) ); - literalQueryWithDepth2.setFullTextScoringEnabled( true ); - literalQueryWithDepth2.setFullTextScoringSortOrder( Qt::DescendingOrder ); - QTest::newRow( "literal query with depth 2" ) - << literalQueryWithDepth2 - << QString::fromLatin1("select distinct ?r max((?v8/2)+?v5) as ?_n_f_t_m_s_ where { " - "{ { ?r ?v1 ?v2 . ?v2 bif:contains \"'foo'\" OPTION (score ?v5) . } " - "UNION " - "{ ?r ?v1 ?v3 . ?v3 ?v4 ?v2 . " - "?v4 . ?v2 bif:contains \"'foo'\" OPTION (score ?v5) . } . " - "?r ?v6 . ?v6 ?v7 . " - "?v7 bif:contains \"'bar'\" OPTION (score ?v8) . } . } ORDER BY DESC ( ?_n_f_t_m_s_ )"); - - QTest::newRow( "type query" ) - << Query( ResourceTypeTerm( Soprano::Vocabulary::NAO::Tag() ) ) - << QString::fromLatin1("select distinct ?r where { ?r a %1 . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::Tag())); - - QTest::newRow( "negated resource type" ) - << Query( NegationTerm::negateTerm( ResourceTypeTerm( Soprano::Vocabulary::NAO::Tag() ) ) ) - << QString::fromLatin1("select distinct ?r where { ?r a ?v1 . FILTER(!bif:exists((select (1) where { ?r a %1 . }))) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::Tag())); - - QDateTime now = QDateTime::currentDateTime(); - QTest::newRow( "nie:lastModified" ) - << Query( ComparisonTerm( Nepomuk::Vocabulary::NIE::lastModified(), LiteralTerm( now ), ComparisonTerm::GreaterOrEqual ) ) - << QString::fromLatin1("select distinct ?r where { ?r %1 ?v1 . FILTER(?v1>=%2) . }") - .arg(Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NIE::lastModified()), - Soprano::Node::literalToN3(now)); - - QTest::newRow( "hastag with literal term" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), LiteralTerm( QLatin1String("nepomuk")) ) ) - << QString::fromLatin1("select distinct ?r where { ?r %1 ?v1 . ?v1 ?v2 ?v3 . ?v2 %2 %3 . FILTER(bif:contains(?v3, \"'nepomuk'\")) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag())) - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::subPropertyOf())) - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::label())); - - QTest::newRow( "hastag with resource" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) )) - << QString::fromLatin1("select distinct ?r where { ?r %1 . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag())); - - QTest::newRow( "negated hastag with resource" ) - << Query( NegationTerm::negateTerm(ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) ))) - << QString::fromLatin1("select distinct ?r where { ?r a ?v1 . FILTER(!bif:exists((select (1) where { ?r %1 . }))) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag())); - - QTest::newRow( "comparators <" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Smaller ) ) - << QString::fromLatin1("select distinct ?r where { ?r %1 ?v1 . FILTER(?v1<\"4\"^^%2) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()) ); - - QTest::newRow( "comparators <=" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::SmallerOrEqual ) ) - << QString::fromLatin1("select distinct ?r where { ?r %1 ?v1 . FILTER(?v1<=\"4\"^^%2) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()) ); - - QTest::newRow( "comparators >" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Greater ) ) - << QString::fromLatin1("select distinct ?r where { ?r %1 ?v1 . FILTER(?v1>\"4\"^^%2) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()) ); - - QTest::newRow( "comparators >=" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::GreaterOrEqual ) ) - << QString::fromLatin1("select distinct ?r where { ?r %1 ?v1 . FILTER(?v1>=\"4\"^^%2) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()) ); - - QTest::newRow( "inverted comparisonterm" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) ).inverted() ) - << QString::fromLatin1("select distinct ?r where { %1 ?r . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag())); - - QTest::newRow( "inverted comparisonterm 2" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), Term() ).inverted() ) - << QString::fromLatin1("select distinct ?r where { ?v1 %1 ?r . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag())); - - QTest::newRow( "optional term" ) - << Query(OptionalTerm::optionalizeTerm(ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) ))) - << QString::fromLatin1("select distinct ?r where { OPTIONAL { ?r %1 . } }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag())); - - QTest::newRow( "and term" ) - << Query( AndTerm( ComparisonTerm( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Greater ), - ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm(QUrl("nepomuk:/test")) ) ) ) - << QString::fromLatin1("select distinct ?r where { { ?r %1 ?v1 . FILTER(?v1>\"4\"^^%2) . ?r %3 . } . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag())); - - ComparisonTerm setVarNameTerm1( Soprano::Vocabulary::NAO::hasTag(), ResourceTypeTerm( Soprano::Vocabulary::NAO::Tag() ) ); - setVarNameTerm1.setVariableName("myvar"); - QTest::newRow( "set variable name 1" ) - << Query( setVarNameTerm1 ) - << QString::fromLatin1("select distinct ?r ?myvar where { ?r %1 ?myvar . ?myvar a %2 . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::Tag())); - - ComparisonTerm setVarNameTerm2( Soprano::Vocabulary::NAO::hasTag(), LiteralTerm( "nepomuk" ) ); - setVarNameTerm2.setVariableName( "myvar" ); - QTest::newRow( "set variable name 2" ) - << Query( setVarNameTerm2 ) - << QString::fromLatin1("select distinct ?r ?myvar where { ?r %1 ?myvar . ?myvar ?v1 ?v2 . ?v1 %2 %3 . FILTER(bif:contains(?v2, \"'nepomuk'\")) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::subPropertyOf()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::RDFS::label())); - - ComparisonTerm setVarNameTerm3( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Smaller ); - setVarNameTerm3.setVariableName("myvar"); - QTest::newRow( "set variable name 3" ) - << Query( setVarNameTerm3 ) - << QString::fromLatin1("select distinct ?r ?myvar where { ?r %1 ?myvar . FILTER(?myvar<\"4\"^^%2) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()) ); - - ComparisonTerm setVarNameTerm4( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Smaller ); - setVarNameTerm3.setVariableName("myvar" ); - setVarNameTerm3.setAggregateFunction(ComparisonTerm::Count); - QTest::newRow( "set variable name 4 (with aggregate function count)" ) - << Query( setVarNameTerm3 ) - << QString::fromLatin1("select distinct ?r count(?v1) as ?myvar where { ?r %1 ?v1 . FILTER(?v1<\"4\"^^%2) . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()) ); - - ComparisonTerm orderByTerm1( Soprano::Vocabulary::NAO::numericRating(), LiteralTerm(4), ComparisonTerm::Smaller ); - orderByTerm1.setSortWeight( 1 ); - QTest::newRow( "order by 1" ) - << Query( orderByTerm1 ) - << QString::fromLatin1("select distinct ?r ?v1 where { ?r %1 ?v1 . FILTER(?v1<\"4\"^^%2) . } ORDER BY ASC ( ?v1 )") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()) ); - - orderByTerm1.setSortWeight( 1, Qt::DescendingOrder ); - QTest::newRow( "order by 2" ) - << Query( orderByTerm1 ) - << QString::fromLatin1("select distinct ?r ?v1 where { ?r %1 ?v1 . FILTER(?v1<\"4\"^^%2) . } ORDER BY DESC ( ?v1 )") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()) ); - - ComparisonTerm orderByTerm2( Soprano::Vocabulary::NAO::prefLabel(), LiteralTerm("hello") ); - orderByTerm2.setSortWeight( 2 ); - - QTest::newRow( "order by 3" ) - << Query( AndTerm( orderByTerm1, orderByTerm2 ) ) - << QString::fromLatin1("select distinct ?r ?v1 ?v2 where { { ?r %1 ?v1 . FILTER(?v1<\"4\"^^%2) . ?r %3 ?v2 . FILTER(bif:contains(?v2, \"'hello'\")) . } . } ORDER BY ASC ( ?v2 ) DESC ( ?v1 )") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::prefLabel()) ); - - orderByTerm1.setVariableName("myvar"); - QTest::newRow( "order by 4" ) - << Query( orderByTerm1 ) - << QString::fromLatin1("select distinct ?r ?myvar where { ?r %1 ?myvar . FILTER(?myvar<\"4\"^^%2) . } ORDER BY DESC ( ?myvar )") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::XMLSchema::xsdInt()) ); - - QTest::newRow( "ComparisonTerm with invalid property" ) - << Query( ComparisonTerm( Nepomuk::Types::Property(), ResourceTerm( QUrl("nepomuk:/res/foobar") ) )) - << QString::fromLatin1("select distinct ?r where { ?r ?v1 . }"); - - QTest::newRow( "ComparisonTerm with invalid subterm" ) - << Query( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), Term() ) ) - << QString::fromLatin1("select distinct ?r where { ?r %1 ?v1 . }") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag())); - - QTest::newRow( "ComparisonTerm with invalid property and subterm" ) - << Query( ComparisonTerm( Nepomuk::Types::Property(), Term() ) ) - << QString::fromLatin1("select distinct ?r where { ?r ?v1 ?v2 . }"); - - ComparisonTerm orderByTerm5( Soprano::Vocabulary::NAO::numericRating(), Term() ); - orderByTerm5.setSortWeight( 1 ); - orderByTerm5.setAggregateFunction( ComparisonTerm::Max ); - QTest::newRow( "order by 5 (with aggregate function and invalid subterm)" ) - << Query( orderByTerm5 ) - << QString::fromLatin1("select distinct ?r where { ?r %1 ?v1 . } ORDER BY ASC ( max(?v1) )") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()) ); - - orderByTerm5.setVariableName( "myvar" ); - QTest::newRow( "order by 5 (with aggregate function and invalid subterm and varname)" ) - << Query( orderByTerm5 ) - << QString::fromLatin1("select distinct ?r max(?v1) as ?myvar where { ?r %1 ?v1 . } ORDER BY ASC ( ?myvar )") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()) ); - - orderByTerm5.setVariableName( QString() ); - orderByTerm5.setAggregateFunction( ComparisonTerm::DistinctCount ); - QTest::newRow( "order by 5 (with aggregate function and invalid subterm and varname)" ) - << Query( orderByTerm5 ) - << QString::fromLatin1("select distinct ?r where { ?r %1 ?v1 . } ORDER BY ASC ( count(distinct ?v1) )") - .arg(Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::numericRating()) ); - - - // the empty file query should query all files - FileQuery emptyFileQuery; - QTest::newRow( "empty file query" ) - << Query(emptyFileQuery) - << QString::fromLatin1("select distinct ?r where { ?r a ?v1 . FILTER(?v1 in (%1,%2)) . }") - .arg( Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::Folder()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::FileDataObject()) ); - - - FileQuery fileQuery( ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), ResourceTerm(QUrl("nepomuk:/res/foobar")) ) ); - QTest::newRow( "file query" ) - << Query(fileQuery) - << QString::fromLatin1("select distinct ?r where { { ?r %1 . ?r a ?v1 . FILTER(?v1 in (%2,%3)) . } . }") - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::Folder()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::FileDataObject()) ); - - fileQuery.setFileMode(FileQuery::QueryFiles); - QTest::newRow( "file query (only files)" ) - << Query(fileQuery) - << QString::fromLatin1("select distinct ?r where { { ?r %1 . ?r a %2 . FILTER(!bif:exists((select (1) where { ?r a %3 . }))) . } . }") - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::FileDataObject()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::Folder()) ); - - fileQuery.setFileMode(FileQuery::QueryFolders); - QTest::newRow( "file query (only folders)" ) - << Query(fileQuery) - << QString::fromLatin1("select distinct ?r where { { ?r %1 . ?r a %2 . FILTER(!bif:exists((select (1) where { ?r a %3 . }))) . } . }") - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::Folder()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::FileDataObject()) ); - - - fileQuery.setFileMode(FileQuery::QueryFilesAndFolders); - fileQuery.addIncludeFolder(KUrl(QLatin1String("/home/test/includeme"))); - fileQuery.addExcludeFolder(KUrl(QLatin1String("/home/test/includeme/excludeme"))); - fileQuery.addRequestProperty(Query::RequestProperty(NIE::url(), false)); - QTest::newRow( "file query with include folder" ) - << Query(fileQuery) - << QString::fromLatin1("select distinct ?r ?reqProp1 where { { " - "?r %4 ?reqProp1 . " - "?r %1 . " - "?r a ?v1 . FILTER(?v1 in (%2,%3)) . " - "FILTER(REGEX(STR(?reqProp1), '(^file:///home/test/includeme/)', 'i')) . " - "FILTER(!REGEX(STR(?reqProp1), '^(file:///home/test/includeme/excludeme/)', 'i')) . } . }") - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::Folder()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::FileDataObject()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NIE::url()) ); - - - QTest::newRow( "Query one resource" ) - << Query(ResourceTerm(QUrl("nepomuk:/A"))) - << QString::fromLatin1("select distinct ?r where { ?r a ?v1 . FILTER(?r=) . }"); - - QTest::newRow( "Query several resources resource" ) - << Query(OrTerm(ResourceTerm(QUrl("nepomuk:/A")), ResourceTerm(QUrl("nepomuk:/B")), ResourceTerm(QUrl("nepomuk:/C")))) - << QString::fromLatin1("select distinct ?r where { { ?r a ?v1 . FILTER(?r=) . } UNION { ?r a ?v2 . FILTER(?r=) . } UNION { ?r a ?v3 . FILTER(?r=) . } . }"); - - QTest::newRow( "Pointless but correct: Query several resources resource 2" ) - << Query(AndTerm(ResourceTerm(QUrl("nepomuk:/A")), ResourceTerm(QUrl("nepomuk:/B")), ResourceTerm(QUrl("nepomuk:/C")))) - << QString::fromLatin1("select distinct ?r where { { ?r a ?v1 . FILTER(?r=) . ?r a ?v2 . FILTER(?r=) . ?r a ?v3 . FILTER(?r=) . } . }"); - - QTest::newRow("query several types") - << Query(OrTerm(ResourceTypeTerm(QUrl("onto:/typeA")), ResourceTypeTerm(QUrl("onto:/typeB")))) - << QString(QLatin1String("select distinct ?r where { ?r a ?v1 . FILTER(?v1 in (,)) . }")); - - // - // A more complex example - // - QUrl res("nepomuk:/res/foobar"); - AndTerm mainTerm; - OrTerm typeOr; - typeOr.addSubTerm( ResourceTypeTerm( Nepomuk::Vocabulary::NFO::RasterImage() ) ); - typeOr.addSubTerm( ResourceTypeTerm( Nepomuk::Vocabulary::NFO::Audio() ) ); - mainTerm.addSubTerm( typeOr ); - mainTerm.addSubTerm( NegationTerm::negateTerm( ComparisonTerm( Nepomuk::Types::Property(), ResourceTerm( res ) ).inverted() ) ); - - // an empty comparisonterm results in "?r ?v1 ?v2" - ComparisonTerm ct; - - // change the var name: "?r ?v1 ?cnt" - ct.setVariableName( "cnt" ); - ct.setAggregateFunction( ComparisonTerm::Count ); - - // by default all have 0, Query::toSparqlQuery will add ORDER BY for all ComparisonTerm with sortweight != 0 - ct.setSortWeight( 1, Qt::DescendingOrder ); - - mainTerm.addSubTerm(ct.inverted()); - - QString sparql = QString::fromLatin1("select distinct ?r count(?v3) as ?cnt where { { " - "?v3 ?v2 ?r . " - "?r a ?v4 . FILTER(?v4 in (%2,%1)) . " - "FILTER(!bif:exists((select (1) where { ?v1 ?r . }))) . " - "} . } ORDER BY DESC ( ?cnt )") - .arg(Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::RasterImage()), - Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::Audio())); - - QTest::newRow( "a complex one" ) - << Query( mainTerm ) - << sparql; - -#if 0 -// subquery to match grouding occurrences of nepomuk:/TEST - ComparisonTerm goterm( Nepomuk::Vocabulary::PIMO::groundingOccurrence(), - ResourceTerm( Nepomuk::Resource( QUrl("nepomuk:/TEST")) ) ); - goterm.setInverted(true); - -// combine that with only nco:PersonContacts - AndTerm pcgoterm( ResourceTypeTerm( Nepomuk::Vocabulary::NCO::PersonContact() ), - goterm ); - -// now look for im accounts of those grounding occurrences (pcgoterm will become the subject of this comparison, -// thus the comparison will match the im accounts) - ComparisonTerm impcgoterm( Nepomuk::Vocabulary::NCO::hasIMAccount(), - pcgoterm ); - impcgoterm.setInverted(true); - -// now look for all buddies of the accounts - ComparisonTerm buddyTerm( QUrl("http://kde.org/telepathy#isBuddyOf")/*Nepomuk::Vocabulary::Telepathy::isBuddyOf()*/, - impcgoterm ); - -// set the name of the variable (i.e. the buddies) to be able to match it later - buddyTerm.setVariableName("t"); - -// same comparison, other property, but use the same variable name to match them - ComparisonTerm ppterm( QUrl("http://kde.org/telepathy#publishesPresenceTo")/*Nepomuk::Vocabulary::Telepathy::publishesPresenceTo()*/, - ResourceTypeTerm( Nepomuk::Vocabulary::NCO::IMAccount() ) ); - ppterm.setVariableName("t"); - -// combine both to complete the matching of the im account ?account - AndTerm accountTerm( ResourceTypeTerm( Nepomuk::Vocabulary::NCO::IMAccount() ), - buddyTerm, - ppterm ); - -// match the account and select it for the results - ComparisonTerm imaccountTerm( Nepomuk::Vocabulary::NCO::hasIMAccount(), accountTerm ); - imaccountTerm.setVariableName("account"); - -// and finally the exclusion of those person contacts that already have a pimo person attached - ComparisonTerm personTerm( Nepomuk::Vocabulary::PIMO::groundingOccurrence(), - ResourceTypeTerm( Nepomuk::Vocabulary::PIMO::Person() ) ); - personTerm.setInverted(true); - -// and all combined - Query theQuery( AndTerm( ResourceTypeTerm( Nepomuk::Vocabulary::NCO::PersonContact() ), - imaccountTerm, - NegationTerm::negateTerm(personTerm)) ); - - - QTest::newRow( "and term" ) - << theQuery - << QString::fromLatin1(""); -#endif -} - - -namespace { -/** - * Changes the ordering of ?vN variables in the given query string - * to always start at 1 and go up from there depending on the first - * occurrence. - * - * This allows to use an arbitrary variable naming in the tests and - * in the SPARQL query generation code. - */ -QString normalizeVariables(const QString& s) { - QList variableNumbers; - QRegExp varExp(QLatin1String("\\?v(\\d+)")); - int pos = -1; - - // extract all generated variables - while((pos = s.indexOf(varExp, pos+1)) >= 0) { - const int varNum = varExp.cap(1).toInt(); - if( !variableNumbers.contains(varNum) ) { - variableNumbers << varNum; - } - } - - // replace all generated var numbers with a normalized order - QString newQuery(s); - for(int i = 0; i < variableNumbers.count(); ++i) { - newQuery.replace(QString::fromLatin1("?v%1").arg(variableNumbers[i]), QString::fromLatin1("?$$%1").arg(i+1)); - } - newQuery.replace(QLatin1String("?$$"), QLatin1String("?v")); - - return newQuery; -} -} -void QueryTest::testToSparql() -{ - QFETCH( Nepomuk::Query::Query, query ); - QFETCH( QString, queryString ); - - // we test without result restrictions which always look the same anyway - query.setQueryFlags( Query::NoResultRestrictions|Query::WithoutFullTextExcerpt ); - - QCOMPARE( normalizeVariables(query.toSparqlQuery().simplified()), normalizeVariables(queryString) ); - - // test fromQueryUrl - QCOMPARE( Query::fromQueryUrl(query.toSearchUrl()), query ); - QCOMPARE( Query::fromQueryUrl(query.toSearchUrl(QLatin1String("Hello World"))), query ); -} - - -void QueryTest::testOptimization() -{ - LiteralTerm literal("Hello World"); - AndTerm and1; - and1.addSubTerm(literal); - QCOMPARE( Query(and1).optimized(), Query(literal) ); - - AndTerm and2; - and2.addSubTerm(and1); - QCOMPARE( Query(and2).optimized(), Query(literal) ); - - Term invalidTerm; - and2.addSubTerm(invalidTerm); - QCOMPARE( Query(and2).optimized(), Query(literal) ); - - and1.setSubTerms(QList() << invalidTerm); - and2.setSubTerms(QList() << and1 << literal); - QCOMPARE( Query(and2).optimized(), Query(literal) ); - - // make sure duplicate negations are removed - QCOMPARE( Query( - NegationTerm::negateTerm( - NegationTerm::negateTerm( - ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()))) - ).optimized(), - Query( ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()) ) ); - - // make sure more than two negations are removed - QCOMPARE( Query( - NegationTerm::negateTerm( - NegationTerm::negateTerm( - NegationTerm::negateTerm( - NegationTerm::negateTerm( - ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()))))) - ).optimized(), - Query( ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()) ) ); - - // test negation removal while keeping one - QCOMPARE( Query( - NegationTerm::negateTerm( - NegationTerm::negateTerm( - NegationTerm::negateTerm( - ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag())))) - ).optimized(), - Query( NegationTerm::negateTerm(ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag())) ) ); - - - // make sure duplicate optionals are removed - QCOMPARE( Query( - OptionalTerm::optionalizeTerm( - OptionalTerm::optionalizeTerm( - OptionalTerm::optionalizeTerm( - ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag())))) - ).optimized(), - Query( OptionalTerm::optionalizeTerm( - ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()))) ); -} - - -void QueryTest::testLogicalOperators() -{ - // test negation - ComparisonTerm ct1( Soprano::Vocabulary::NAO::hasTag(), LiteralTerm("bla") ); - QCOMPARE( NegationTerm::negateTerm(ct1), !ct1 ); - - // test logical and - ComparisonTerm ct2( Soprano::Vocabulary::NAO::hasTag(), LiteralTerm("foo") ); - LiteralTerm lt1( "bar" ); - QCOMPARE( ct1 && ct2 && lt1, Term(AndTerm( ct1, ct2, lt1 )) ); - - // test logical or - QCOMPARE( ct1 || ct2 || lt1, Term(OrTerm( ct1, ct2, lt1 )) ); -} - - -void QueryTest::testComparison_data() -{ - QTest::addColumn( "q1" ); - QTest::addColumn( "q2" ); - - // invalid queries should always be similar - trivial but worth checking anyway - Query q1, q2; - QTest::newRow("invalid") << q1 << q2; - - // file queries with differently sorted folder lists - FileQuery fq1, fq2; - fq1.addIncludeFolder( KUrl("/tmp") ); - fq1.addIncludeFolder( KUrl("/wurst") ); - fq2.addIncludeFolder( KUrl("/wurst") ); - fq2.addIncludeFolder( KUrl("/tmp") ); - QTest::newRow("file query include sorting") << Query(fq1) << Query(fq2); -} - - -void QueryTest::testComparison() -{ - QFETCH( Nepomuk::Query::Query, q1 ); - QFETCH( Nepomuk::Query::Query, q2 ); - - QCOMPARE( q1, q2 ); -} - - -void QueryTest::testTermFromProperty() -{ - QCOMPARE( Term::fromProperty(Soprano::Vocabulary::NAO::hasTag(), Nepomuk::Variant( QString::fromLatin1("Hello World") )), - Term( - ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), - LiteralTerm( QLatin1String("Hello World") ), - ComparisonTerm::Equal ) ) - ); - - QCOMPARE( Term::fromProperty(Soprano::Vocabulary::NAO::hasTag(), Nepomuk::Variant( 42 )), - Term( - ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), - LiteralTerm( 42 ), - ComparisonTerm::Equal ) ) - ); - - Nepomuk::Resource res( QUrl("nepomuk:/res/foobar") ); - QCOMPARE( Term::fromProperty(Soprano::Vocabulary::NAO::hasTag(), Nepomuk::Variant( res )), - Term( - ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), - ResourceTerm( res ), - ComparisonTerm::Equal ) ) - ); - - Nepomuk::Resource res2( QUrl("nepomuk:/res/foobar2") ); - QCOMPARE( Term::fromProperty(Soprano::Vocabulary::NAO::hasTag(), Nepomuk::Variant( QList() << res << res2 )), - Term( - AndTerm( - ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), - ResourceTerm( res ), - ComparisonTerm::Equal ), - ComparisonTerm( Soprano::Vocabulary::NAO::hasTag(), - ResourceTerm( res2 ), - ComparisonTerm::Equal ) ) ) - ); -} - -QTEST_KDEMAIN_CORE( QueryTest ) - -#include "querytest.moc" diff --git a/nepomuk/test/querytest.h b/nepomuk/test/querytest.h deleted file mode 100644 index 881b2bb0..00000000 --- a/nepomuk/test/querytest.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_TEST_H_ -#define _NEPOMUK_QUERY_TEST_H_ - -#include -#include "query.h" -#include "term.h" - -class QueryTest : public QObject -{ - Q_OBJECT - -private Q_SLOTS: - void testToSparql_data(); - void testToSparql(); - void testOptimization(); - void testLogicalOperators(); - void testComparison_data(); - void testComparison(); - void testTermFromProperty(); -}; - -#endif - - diff --git a/nepomuk/test/ratingpaintertestapp.cpp b/nepomuk/test/ratingpaintertestapp.cpp deleted file mode 100644 index 62327713..00000000 --- a/nepomuk/test/ratingpaintertestapp.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "ratingpaintertestwidget.h" - -#include -#include - - -int main( int argc, char** argv ) -{ - QApplication app( argc, argv ); - KComponentData data( "NepomukRatingPainterTest" ); - RatingPainterTestWidget ratingW; - ratingW.show(); - return app.exec(); -} diff --git a/nepomuk/test/ratingpaintertestwidget.cpp b/nepomuk/test/ratingpaintertestwidget.cpp deleted file mode 100644 index c36dcd16..00000000 --- a/nepomuk/test/ratingpaintertestwidget.cpp +++ /dev/null @@ -1,138 +0,0 @@ -#include "ratingpaintertestwidget.h" -#include "kratingwidget.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - - -RatingPainterTestWidget::RatingPainterTestWidget() - : QWidget( 0 ) -{ - QVBoxLayout* layout = new QVBoxLayout( this ); - m_ratingWidget = new KRatingWidget( this ); - m_ratingWidget->setFrameStyle( QFrame::StyledPanel|QFrame::Sunken ); - m_checkHalfSteps = new QCheckBox( "Enable half steps", this ); - m_checkEnalbed = new QCheckBox( "Rating disabled", this ); - m_spinMaxRating = new KIntSpinBox( this ); - m_spinRating = new KIntSpinBox( this ); - m_spinSpacing = new KIntSpinBox( this ); - - m_comboAlignmentH = new QComboBox( this ); - m_comboAlignmentV = new QComboBox( this ); - - m_buttonIcon = new QPushButton( "Change Icon...", this ); - - m_comboAlignmentH->addItem( "Left" ); - m_comboAlignmentH->addItem( "Right" ); - m_comboAlignmentH->addItem( "Center" ); - m_comboAlignmentH->addItem( "Justify" ); - - m_comboAlignmentV->addItem( "Top" ); - m_comboAlignmentV->addItem( "Bottom" ); - m_comboAlignmentV->addItem( "Center" ); - - layout->addWidget( m_ratingWidget, 1 ); - layout->addWidget( new QLabel( "Alignment:" ) ); - layout->addWidget( m_comboAlignmentH ); - layout->addWidget( m_comboAlignmentV ); - layout->addWidget( m_checkHalfSteps ); - layout->addWidget( m_checkEnalbed ); - - QHBoxLayout* ratingLayout = new QHBoxLayout; - ratingLayout->addWidget( new QLabel( "Rating:", this ) ); - ratingLayout->addWidget( m_spinRating ); - layout->addLayout( ratingLayout ); - - QHBoxLayout* maxRatingLayout = new QHBoxLayout; - maxRatingLayout->addWidget( new QLabel( "Max Rating:", this ) ); - maxRatingLayout->addWidget( m_spinMaxRating ); - layout->addLayout( maxRatingLayout ); - - QHBoxLayout* spacingLayout = new QHBoxLayout; - spacingLayout->addWidget( new QLabel( "Spacing:", this ) ); - spacingLayout->addWidget( m_spinSpacing ); - layout->addLayout( spacingLayout ); - - layout->addWidget( m_buttonIcon ); - - connect( m_comboAlignmentH, SIGNAL(activated(int)), - this, SLOT(slotAlignmentChanged()) ); - connect( m_comboAlignmentV, SIGNAL(activated(int)), - this, SLOT(slotAlignmentChanged()) ); - connect( m_spinMaxRating, SIGNAL(valueChanged(int)), - m_ratingWidget, SLOT(setMaxRating(int)) ); - connect( m_spinRating, SIGNAL(valueChanged(int)), - m_ratingWidget, SLOT(setRating(int)) ); - connect( m_spinSpacing, SIGNAL(valueChanged(int)), - m_ratingWidget, SLOT(setSpacing(int)) ); - connect( m_checkHalfSteps, SIGNAL(toggled(bool)), - m_ratingWidget, SLOT(setHalfStepsEnabled(bool)) ); - connect( m_checkEnalbed, SIGNAL(toggled(bool)), - m_ratingWidget, SLOT(setDisabled(bool)) ); - connect( m_ratingWidget, SIGNAL(ratingChanged(int)), - m_spinRating, SLOT(setValue(int)) ); - connect( m_buttonIcon, SIGNAL(clicked()), - this, SLOT(slotChangeIcon()) ); - - m_comboAlignmentH->setCurrentIndex( 2 ); - m_comboAlignmentV->setCurrentIndex( 2 ); - m_spinMaxRating->setValue( m_ratingWidget->maxRating() ); - m_spinRating->setValue( m_ratingWidget->rating() ); - m_spinSpacing->setValue( m_ratingWidget->spacing() ); - m_checkHalfSteps->setChecked( m_ratingWidget->halfStepsEnabled() ); -} - - -RatingPainterTestWidget::~RatingPainterTestWidget() -{ -} - - -void RatingPainterTestWidget::slotAlignmentChanged() -{ - Qt::Alignment align = Qt::AlignLeft; - if ( m_comboAlignmentH->currentText() == "Left" ) { - align = Qt::AlignLeft; - } - else if ( m_comboAlignmentH->currentText() == "Right" ) { - align = Qt::AlignRight; - } - else if ( m_comboAlignmentH->currentText() == "Center" ) { - align = Qt::AlignHCenter; - } - else if ( m_comboAlignmentH->currentText() == "Justify" ) { - align = Qt::AlignJustify; - } - - if ( m_comboAlignmentV->currentText() == "Top" ) { - align |= Qt::AlignTop; - } - else if ( m_comboAlignmentV->currentText() == "Bottom" ) { - align |= Qt::AlignBottom; - } - else if ( m_comboAlignmentV->currentText() == "Center" ) { - align |= Qt::AlignVCenter; - } - - m_ratingWidget->setAlignment( align ); -} - - -void RatingPainterTestWidget::slotChangeIcon() -{ - QString icon = KIconDialog::getIcon(); - if ( !icon.isEmpty() ) { - m_ratingWidget->setIcon( KIcon( icon ) ); - m_buttonIcon->setIcon( KIcon( icon ) ); - } -} - -#include "ratingpaintertestwidget.moc" diff --git a/nepomuk/test/ratingpaintertestwidget.h b/nepomuk/test/ratingpaintertestwidget.h deleted file mode 100644 index 74cac7f2..00000000 --- a/nepomuk/test/ratingpaintertestwidget.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef _RATING_PAINTER_TEST_WIDGET_H_ -#define _RATING_PAINTER_TEST_WIDGET_H_ - -#include - -class QComboBox; -class QCheckBox; -class KRatingWidget; -class KIntSpinBox; -class QPushButton; - -class RatingPainterTestWidget : public QWidget -{ - Q_OBJECT - -public: - RatingPainterTestWidget(); - ~RatingPainterTestWidget(); - -private Q_SLOTS: - void slotChangeIcon(); - void slotAlignmentChanged(); - -private: - KIntSpinBox* m_spinMaxRating; - KIntSpinBox* m_spinRating; - KIntSpinBox* m_spinSpacing; - - QComboBox* m_comboAlignmentH; - QComboBox* m_comboAlignmentV; - QCheckBox* m_checkHalfSteps; - QCheckBox* m_checkEnalbed; - - QPushButton* m_buttonIcon; - - KRatingWidget* m_ratingWidget; -}; - -#endif diff --git a/nepomuk/test/simplefacettest.cpp b/nepomuk/test/simplefacettest.cpp deleted file mode 100644 index 4e084ad4..00000000 --- a/nepomuk/test/simplefacettest.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "simplefacettest.h" -#include "qtest_querytostring.h" - -#include "simplefacet.h" -#include "comparisonterm.h" -#include "resourcetypeterm.h" - -#include - -#include -#include "qtest_kde.h" - - -using namespace Nepomuk::Utils; -using namespace Nepomuk::Query; - -void SimpleFacetTest::testAddTerm() -{ - SimpleFacet f; - - QCOMPARE(f.count(), 0); - - QString label1 = QLatin1String("Label 1"); - Term term1; - QString label2 = QLatin1String("Label 2"); - Term term2 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()); - - f.addTerm(label1, term1); - QCOMPARE(f.count(), 1); - - f.addTerm(label2, term2); - QCOMPARE(f.count(), 2); - - QCOMPARE(f.text(0), label1); - QCOMPARE(f.text(1), label2); - - QCOMPARE(f.termAt(0), term1); - QCOMPARE(f.termAt(1), term2); -} - -void SimpleFacetTest::testMatchOne() -{ - SimpleFacet f; - f.setSelectionMode(Facet::MatchOne); - - QString label1 = QLatin1String("Label 1"); - Term term1; - QString label2 = QLatin1String("Label 2"); - Term term2 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()); - - f.addTerm(label1, term1); - f.addTerm(label2, term2); - - // by default the first entry needs to be selected - QVERIFY(f.isSelected(0)); - QCOMPARE(f.queryTerm(), term1); - - // re-selecting it should not change anything - f.setSelected(0, true); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1); - - // de-selecting the first entry should also revert to it being selected - f.setSelected(0, false); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1); - - // selecting the second - f.setSelected(1, true); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term2); - - // clearing the selection should result in the first being selected - f.clearSelection(); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1); -} - -void SimpleFacetTest::testMatchAll() -{ - SimpleFacet f; - f.setSelectionMode(Facet::MatchAll); - - QString label1 = QLatin1String("Label 1"); - Term term1 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Party()); - QString label2 = QLatin1String("Label 2"); - Term term2 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()); - - f.addTerm(label1, term1); - f.addTerm(label2, term2); - - // by default nothing should be selected - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), Term()); - - // selecting the first - f.setSelected(0, true); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1); - - // de-selecting the first entry should revert to no selection - f.setSelected(0, false); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), Term()); - - // selecting the second - f.setSelected(1, true); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term2); - - // selecting the first and the second - f.setSelected(0, true); - QVERIFY(f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1 && term2); - - // clearing the selection should result in nothing being selected - f.clearSelection(); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), Term()); -} - -void SimpleFacetTest::testMatchAny() -{ - SimpleFacet f; - f.setSelectionMode(Facet::MatchAny); - - QString label1 = QLatin1String("Label 1"); - Term term1 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Party()); - QString label2 = QLatin1String("Label 2"); - Term term2 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()); - - f.addTerm(label1, term1); - f.addTerm(label2, term2); - - // by default nothing should be selected - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), Term()); - - // selecting the first - f.setSelected(0, true); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1); - - // de-selecting the first entry should revert to no selection - f.setSelected(0, false); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), Term()); - - // selecting the second - f.setSelected(1, true); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term2); - - // selecting the first and the second - f.setSelected(0, true); - QVERIFY(f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1 || term2); -} - -void SimpleFacetTest::testSelectFromTerm() -{ - SimpleFacet f; - f.setSelectionMode(Facet::MatchOne); - - QString label1 = QLatin1String("Label 1"); - Term term1 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Party()); - QString label2 = QLatin1String("Label 2"); - Term term2 = ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()); - - f.addTerm(label1, term1); - f.addTerm(label2, term2); - - - // in MatchOne mode we should be able to select term1 and term2 but no combination - QVERIFY(f.selectFromTerm(term1)); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1); - - QVERIFY(f.selectFromTerm(term2)); - QVERIFY(!f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term2); - - QVERIFY(!f.selectFromTerm(term1 && term2)); - QVERIFY(!f.selectFromTerm(term1 || term2)); - - - // in MatchAll mode we should be able to select term1, term2, and an AndTerm combination of both - f.setSelectionMode(Facet::MatchAll); - - QVERIFY(f.selectFromTerm(term1)); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1); - - QVERIFY(f.selectFromTerm(term2)); - QVERIFY(f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1 && term2); - - f.clearSelection(); - - QVERIFY(f.selectFromTerm(term1 && term2)); - QVERIFY(f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1 && term2); - - QVERIFY(!f.selectFromTerm(term1 || term2)); - // the selection should not have changed - QCOMPARE(f.queryTerm(), term1 && term2); - - - // in MatchAny more we should be able to select term1, term2, and an OrTerm combination of both - f.setSelectionMode(Facet::MatchAny); - - QVERIFY(f.selectFromTerm(term1)); - QVERIFY(f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1); - - QVERIFY(f.selectFromTerm(term2)); - QVERIFY(f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1 || term2); - - f.clearSelection(); - - QVERIFY(f.selectFromTerm(term1 || term2)); - QVERIFY(f.isSelected(0)); - QVERIFY(f.isSelected(1)); - QCOMPARE(f.queryTerm(), term1 || term2); - - QVERIFY(!f.selectFromTerm(term1 && term2)); - // the selection should not have changed - QCOMPARE(f.queryTerm(), term1 || term2); - - // clearing the selection should result in nothing being selected - f.clearSelection(); - QVERIFY(!f.isSelected(0)); - QVERIFY(!f.isSelected(1)); - QCOMPARE(f.queryTerm(), Term()); -} - -QTEST_KDEMAIN_CORE(SimpleFacetTest) diff --git a/nepomuk/test/simplefacettest.h b/nepomuk/test/simplefacettest.h deleted file mode 100644 index f22156bd..00000000 --- a/nepomuk/test/simplefacettest.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef SIMPLEFACETTEST_H -#define SIMPLEFACETTEST_H - -#include - -class SimpleFacetTest : public QObject -{ - Q_OBJECT - -private slots: - void testAddTerm(); - void testMatchOne(); - void testMatchAll(); - void testMatchAny(); - void testSelectFromTerm(); -}; - -#endif // SIMPLEFACETTEST_H diff --git a/nepomuk/test/tagwidgetapp.cpp b/nepomuk/test/tagwidgetapp.cpp deleted file mode 100644 index c2a832f7..00000000 --- a/nepomuk/test/tagwidgetapp.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "tagwidgettest.h" - -#include -#include - - -int main( int argc, char** argv ) -{ - QApplication app( argc, argv ); - KComponentData data( "TagWidgetApp" ); - TagWidgetTest tw; - tw.show(); - return app.exec(); -} diff --git a/nepomuk/test/tagwidgettest.cpp b/nepomuk/test/tagwidgettest.cpp deleted file mode 100644 index 72e9b596..00000000 --- a/nepomuk/test/tagwidgettest.cpp +++ /dev/null @@ -1,95 +0,0 @@ -#include "tagwidgettest.h" -#include "tagwidget.h" - -#include -#include -#include - - -TagWidgetTest::TagWidgetTest() - : QWidget() -{ - m_tagWidget = new Nepomuk::TagWidget(this); - m_tagWidget->setMaxTagsShown(8); - QVBoxLayout* lay = new QVBoxLayout(this); - lay->addWidget(m_tagWidget); - connect(m_tagWidget, SIGNAL(tagClicked(Nepomuk::Tag)), - this, SLOT(slotTagClicked(Nepomuk::Tag))); - connect(m_tagWidget, SIGNAL(selectionChanged(QList)), - this, SLOT(slotSelectionChanged(QList))); - - QCheckBox* box = new QCheckBox( "Minimode", this ); - connect(box, SIGNAL(toggled(bool)), this, SLOT(enableMinimode(bool))); - lay->addWidget(box); - - box = new QCheckBox( "Align Right", this ); - connect(box, SIGNAL(toggled(bool)), this, SLOT(alignRight(bool))); - lay->addWidget(box); - - box = new QCheckBox( "Disable clicking", this ); - connect(box, SIGNAL(toggled(bool)), this, SLOT(disableClicking(bool))); - lay->addWidget(box); - - box = new QCheckBox( "Read only", this ); - connect(box, SIGNAL(toggled(bool)), this, SLOT(setReadOnly(bool))); - lay->addWidget(box); -} - -TagWidgetTest::~TagWidgetTest() -{ -} - - -void TagWidgetTest::slotTagClicked(const Nepomuk::Tag& tag) -{ - kDebug() << "Tag clicked:" << tag.resourceUri() << tag.genericLabel(); -} - - -void TagWidgetTest::slotSelectionChanged( const QList& tags ) -{ - QStringList ts; - foreach(const Nepomuk::Tag& tag, tags) - ts << tag.genericLabel(); - kDebug() << "Selection changed:" << ts; -} - - -void TagWidgetTest::enableMinimode( bool enable ) -{ - Nepomuk::TagWidget::ModeFlags flags = m_tagWidget->modeFlags(); - if( enable ) { - flags |= Nepomuk::TagWidget::MiniMode; - flags &= ~Nepomuk::TagWidget::StandardMode; - } - else { - flags |= Nepomuk::TagWidget::StandardMode; - flags &= ~Nepomuk::TagWidget::MiniMode; - } - m_tagWidget->setModeFlags( flags ); -} - - -void TagWidgetTest::alignRight( bool enable ) -{ - if( enable ) - m_tagWidget->setAlignment( Qt::AlignRight ); - else - m_tagWidget->setAlignment( Qt::AlignLeft ); -} - - -void TagWidgetTest::disableClicking( bool enable ) -{ - Nepomuk::TagWidget::ModeFlags flags = m_tagWidget->modeFlags(); - m_tagWidget->setModeFlags( enable ? flags | Nepomuk::TagWidget::DisableTagClicking : flags & ~Nepomuk::TagWidget::DisableTagClicking ); -} - - -void TagWidgetTest::setReadOnly( bool enable ) -{ - Nepomuk::TagWidget::ModeFlags flags = m_tagWidget->modeFlags(); - m_tagWidget->setModeFlags( enable ? flags | Nepomuk::TagWidget::ReadOnly : flags & ~Nepomuk::TagWidget::ReadOnly ); -} - -#include "tagwidgettest.moc" diff --git a/nepomuk/test/tagwidgettest.h b/nepomuk/test/tagwidgettest.h deleted file mode 100644 index c4911a61..00000000 --- a/nepomuk/test/tagwidgettest.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef TAGWIDGETTEST_H -#define TAGWIDGETTEST_H - -#include -#include "tag.h" -#include "tagwidget.h" - -class TagWidgetTest : public QWidget -{ - Q_OBJECT - -public: - TagWidgetTest(); - ~TagWidgetTest(); - -public slots: - void slotTagClicked(const Nepomuk::Tag&); - void slotSelectionChanged( const QList& tags ); - -private slots: - void enableMinimode( bool enable ); - void alignRight( bool enable ); - void disableClicking( bool enable ); - void setReadOnly( bool enable ); - -private: - Nepomuk::TagWidget* m_tagWidget; -}; - -#endif diff --git a/nepomuk/test/typefacettest.cpp b/nepomuk/test/typefacettest.cpp deleted file mode 100644 index 72a374e7..00000000 --- a/nepomuk/test/typefacettest.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "typefacettest.h" -#include "qtest_querytostring.h" - -#include "typefacet.h" -#include "resourcetypeterm.h" -#include "nfo.h" -#include "class.h" -#include "negationterm.h" -#include "class.h" - -#include - -#include -#include -#include "qtest_kde.h" - - -using namespace Nepomuk::Utils; -using namespace Nepomuk::Query; -using namespace Nepomuk::Vocabulary; -using namespace Nepomuk::Types; - -void TypeFacetTest::testBasicLayout() -{ - QScopedPointer f( Facet::createTypeFacet() ); - QCOMPARE(f->count(), 2); - QCOMPARE(f->queryTerm(), Term()); -} - -void TypeFacetTest::testFileRootSelection() -{ - QScopedPointer f( Facet::createTypeFacet() ); - f->setSelected(0); - QCOMPARE(f->count(), 5); // The checked file and the file choices - QCOMPARE(f->queryTerm(), Term(ResourceTypeTerm(NFO::FileDataObject()))); - f->setSelected(0, false); - QCOMPARE(f->count(), 2); - QCOMPARE(f->queryTerm(), Term()); -} - -void TypeFacetTest::testOtherRootSelection() -{ - QScopedPointer f( Facet::createTypeFacet() ); - f->setSelected(1); - QCOMPARE(f->count(), 5); - QCOMPARE(f->queryTerm(), Term(NegationTerm::negateTerm(ResourceTypeTerm(NFO::FileDataObject())))); - f->setSelected(0, false); - QCOMPARE(f->count(), 2); - QCOMPARE(f->queryTerm(), Term()); -} - -void TypeFacetTest::testCustomTypes() -{ - QScopedPointer f( Facet::createTypeFacet() ); - f->selectFromTerm(ResourceTypeTerm(NFO::Application())); - QCOMPARE(f->count(), 6); - QVERIFY(f->isSelected(0)); - QCOMPARE(f->text(5), Class(NFO::Application()).label()); - QVERIFY(f->isSelected(5)); - QCOMPARE(f->queryTerm(), Term(ResourceTypeTerm(NFO::Application()))); -} - -void TypeFacetTest::testSelectFromTerm() -{ - QScopedPointer f( Facet::createTypeFacet() ); - - // test nfo:FileDataObject which should only select the file thing - f->selectFromTerm(ResourceTypeTerm(NFO::FileDataObject())); - QCOMPARE(f->count(), 5); - QVERIFY(f->isSelected(0)); - QVERIFY(!f->isSelected(1)); - QVERIFY(!f->isSelected(2)); - QVERIFY(!f->isSelected(3)); - QVERIFY(!f->isSelected(4)); - QCOMPARE(f->queryTerm(), Term(ResourceTypeTerm(NFO::FileDataObject()))); - - // in file mode non-file types should not be selectable - QVERIFY(!f->selectFromTerm(ResourceTypeTerm(NFO::Application()))); -} - -QTEST_KDEMAIN_CORE(TypeFacetTest) - -#include "typefacettest.moc" diff --git a/nepomuk/test/typefacettest.h b/nepomuk/test/typefacettest.h deleted file mode 100644 index 5d6d1ab9..00000000 --- a/nepomuk/test/typefacettest.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef TYPEFACETTEST_H -#define TYPEFACETTEST_H - -#include - -class TypeFacetTest : public QObject -{ - Q_OBJECT - -private Q_SLOTS: - void testBasicLayout(); - void testFileRootSelection(); - void testOtherRootSelection(); - void testCustomTypes(); - void testSelectFromTerm(); -}; - -#endif // TYPEFACETTEST_H diff --git a/nepomuk/types/class.cpp b/nepomuk/types/class.cpp deleted file mode 100644 index 052fef6e..00000000 --- a/nepomuk/types/class.cpp +++ /dev/null @@ -1,665 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "class.h" -#include "class_p.h" -#include "ontology.h" -#include "resourcemanager.h" -#include "property.h" -#include "entitymanager.h" - -#include - -#include - -#include -#include -#include -#include -#include -#include - -#undef D -#define D static_cast( d.data() ) - -Nepomuk::Types::ClassPrivate::ClassPrivate( const QUrl& uri ) - : EntityPrivate( uri ), - propertiesAvailable( uri.isValid() ? -1 : 0 ) -{ -} - - -bool Nepomuk::Types::ClassPrivate::load() -{ - // - // Nearly all here can be done in a very clean way. There is only - // one special case: rdfs:Resource, the base class of them all - // - if ( EntityPrivate::load() ) { - // undefined super class means that we are derived from rdfs:Resource directly - if ( parents.isEmpty() ) { - if ( uri != Soprano::Vocabulary::RDFS::Resource() ) { - parents += Soprano::Vocabulary::RDFS::Resource(); - } - } - return true; - } - else { - return false; - } -} - - -bool Nepomuk::Types::ClassPrivate::loadAncestors() -{ - // - // Nearly all here can be done in a very clean way. There is only - // one special case: rdfs:Resource, the base class of them all - // - if ( uri == Soprano::Vocabulary::RDFS::Resource() ) { - // - // All classes that do not explicetely state a superclass are - // derived from rdfs:Resource. This query selects those classes - // (might fail on redland though) - // - Soprano::QueryResultIterator it - = ResourceManager::instance()->mainModel()->executeQuery( QString("select distinct ?s where { " - "{ ?s a <%1> . } UNION { ?s a <%2> . } " - "OPTIONAL { graph ?g { ?s <%3> ?ss . } . " - "{ ?g a <%4> . } UNION { ?g a <%5> . } . } . " - "FILTER(!BOUND(?ss)) . }") - .arg( Soprano::Vocabulary::RDFS::Class().toString() ) - .arg( Soprano::Vocabulary::OWL::Class().toString() ) - .arg( Soprano::Vocabulary::RDFS::subClassOf().toString() ) - .arg( Soprano::Vocabulary::NRL::Ontology().toString() ) - .arg( Soprano::Vocabulary::NRL::KnowledgeBase().toString() ), - Soprano::Query::QueryLanguageSparql ); - while ( it.next() ) { - QUrl resUri = it.binding( "s" ).uri(); - if ( resUri != Soprano::Vocabulary::RDFS::Resource() ) { - children.append( resUri ); - } - } - } - - return EntityPrivate::loadAncestors(); -} - - -bool Nepomuk::Types::ClassPrivate::addProperty( const QUrl& property, const Soprano::Node& value ) -{ - // we avoid subclassing loops (as created for crappy inferencing) by checking for our own uri - if( value.isResource() && value.uri() == uri ) { - return false; - } - - if( property == Soprano::Vocabulary::RDFS::subClassOf() ) { - parents.append( Class( value.uri() ) ); - return true; - } - - return false; -} - - -bool Nepomuk::Types::ClassPrivate::addAncestorProperty( const QUrl& ancestorResource, const QUrl& property ) -{ - // we avoid subclassing loops (as created for crappy inferencing) by checking for our own uri - if ( property == Soprano::Vocabulary::RDFS::subClassOf() && - ancestorResource != uri ) { - children.append( Class( ancestorResource ) ); - return true; - } - - return false; -} - - -void Nepomuk::Types::ClassPrivate::initProperties() -{ - QMutexLocker lock( &mutex ); - - if ( propertiesAvailable < 0 ) { - propertiesAvailable = loadProperties() ? 1 : 0; - } -} - - -bool Nepomuk::Types::ClassPrivate::loadProperties() -{ - // load domains with a hack to get at least a subset of properties that inherit their domain from parents - Soprano::QueryResultIterator it - = ResourceManager::instance()->mainModel()->executeQuery( QString("select distinct ?p where { " - "{ ?p <%1> <%2> . } " - "UNION " - "{ ?p <%3> ?p1 . " - "OPTIONAL { ?p <%1> ?undefdom . } . " - "?p1 <%1> <%2> . " - "FILTER(!bound(?undefdom)) . } " - "UNION " - "{ ?p <%3> ?p1 . " - "OPTIONAL { ?p <%1> ?undefdom1 . } . " - "?p1 <%3> ?p2 . " - "OPTIONAL { ?p1 <%1> ?undefdom2 . } . " - "?p2 <%1> <%2> . " - "FILTER(!bound(?undefdom1) && !bound(?undefdom2)) . } " - "}") - .arg( Soprano::Vocabulary::RDFS::domain().toString() ) - .arg( QString::fromLatin1( uri.toEncoded() ) ) - .arg( Soprano::Vocabulary::RDFS::subPropertyOf().toString() ), - Soprano::Query::QueryLanguageSparql ); - - // redland cannot handle UNION queries! So fallback to the "old" query - if( it.lastError() ) { - it = ResourceManager::instance()->mainModel()->executeQuery( QString("select ?p where { " - "?p <%1> <%2> . }") - .arg( Soprano::Vocabulary::RDFS::domain().toString() ) - .arg( QString::fromLatin1( uri.toEncoded() ) ), - Soprano::Query::QueryLanguageSparql ); - } - - while ( it.next() ) { - domainOf.append( Property( it.binding( "p" ).uri() ) ); - } - - - // load ranges - it = ResourceManager::instance()->mainModel()->executeQuery( QString("select ?p where { " - "?p <%1> <%2> . }") - .arg( Soprano::Vocabulary::RDFS::range().toString() ) - .arg( QString::fromLatin1( uri.toEncoded() ) ), - Soprano::Query::QueryLanguageSparql ); - while ( it.next() ) { - rangeOf.append( Property( it.binding( "p" ).uri() ) ); - } - - return !it.lastError(); -} - - -void Nepomuk::Types::ClassPrivate::reset( bool recursive ) -{ - kDebug(); - - QMutexLocker lock( &mutex ); - - if ( propertiesAvailable != -1 ) { - if ( recursive ) { - foreach( Property p, domainOf ) { - p.reset( true ); - } - foreach( Property p, rangeOf ) { - p.reset( true ); - } - } - - domainOf.clear(); - rangeOf.clear(); - propertiesAvailable = -1; - } - - if ( available != -1 ) { - if ( recursive ) { - foreach( Class c, parents ) { - c.reset( true ); - } - } - parents.clear(); - available = -1; - } - - if ( ancestorsAvailable != -1 ) { - if ( recursive ) { - foreach( Class c, children ) { - c.reset( true ); - } - } - children.clear(); - ancestorsAvailable = -1; - } - - EntityPrivate::reset( recursive ); -} - - -QSet Nepomuk::Types::ClassPrivate::findParentClasses( ClassPrivate* requestingClass ) -{ - QSet allParents; - - for ( QList::iterator it = parents.begin(); it != parents.end(); ++it ) { - ClassPrivate* p = static_cast( it->d.data() ); - if ( p != requestingClass ) { - p->init(); - allParents += p->findParentClasses( requestingClass ); - allParents += *it; - } - } - - return allParents; -} - - -QSet Nepomuk::Types::ClassPrivate::findSubClasses( ClassPrivate* requestingClass ) -{ - QSet allChildren; - - for ( QList::iterator it = children.begin(); it != children.end(); ++it ) { - ClassPrivate* p = static_cast( it->d.data() ); - if ( p != requestingClass ) { - p->initAncestors(); - allChildren += p->findSubClasses( requestingClass ); - allChildren += *it; - } - } - - return allChildren; -} - - - -Nepomuk::Types::Class::Class() - : Entity() -{ - d = 0; -} - - -Nepomuk::Types::Class::Class( const QUrl& uri ) - : Entity() -{ - d = EntityManager::self()->getClass( uri ); -} - - -Nepomuk::Types::Class::Class( const Class& other ) - : Entity( other ) -{ -} - - -Nepomuk::Types::Class::~Class() -{ -} - - -Nepomuk::Types::Class& Nepomuk::Types::Class::operator=( const Class& other ) -{ - d = other.d; - return *this; -} - - -QList Nepomuk::Types::Class::rangeOf() -{ - if ( d ) { - D->initProperties(); - return D->rangeOf; - } - else { - return QList(); - } -} - - -QList Nepomuk::Types::Class::rangeOf() const -{ - return const_cast(this)->rangeOf(); -} - - -QList Nepomuk::Types::Class::domainOf() -{ - if ( d ) { - D->initProperties(); - return D->domainOf; - } - else { - return QList(); - } -} - - -QList Nepomuk::Types::Class::domainOf() const -{ - return const_cast(this)->domainOf(); -} - - -Nepomuk::Types::Property Nepomuk::Types::Class::findPropertyByName( const QString& name ) -{ - if ( d ) { - D->initProperties(); - for ( QList::const_iterator it = D->domainOf.constBegin(); - it != D->domainOf.constEnd(); ++it ) { - const Property& p = *it; - if ( p.name() == name ) { - return p; - } - } - } - - return Property(); -} - - -Nepomuk::Types::Property Nepomuk::Types::Class::findPropertyByName( const QString& name ) const -{ - return const_cast(this)->findPropertyByName(name); -} - - -Nepomuk::Types::Property Nepomuk::Types::Class::findPropertyByLabel( const QString& label, const QString& language ) -{ - if ( d ) { - D->initProperties(); - for ( QList::iterator it = D->domainOf.begin(); - it != D->domainOf.end(); ++it ) { - Property& p = *it; - if ( p.label( language ) == label ) { - return p; - } - } - } - - return Property(); -} - - -Nepomuk::Types::Property Nepomuk::Types::Class::findPropertyByLabel( const QString& label, const QString& language ) const -{ - return const_cast(this)->findPropertyByLabel( label, language ); -} - - -QList Nepomuk::Types::Class::parentClasses() -{ - if ( d ) { - D->init(); - return D->parents; - } - else { - return QList(); - } -} - - -QList Nepomuk::Types::Class::parentClasses() const -{ - return const_cast(this)->parentClasses(); -} - - -QList Nepomuk::Types::Class::subClasses() -{ - if ( d ) { - D->initAncestors(); - return D->children; - } - else { - return QList(); - } -} - - -QList Nepomuk::Types::Class::subClasses() const -{ - return const_cast(this)->subClasses(); -} - - -QList Nepomuk::Types::Class::allParentClasses() -{ - if ( d ) { - D->init(); - return D->findParentClasses( D ).toList(); - } - else { - return QList(); - } -} - - -QList Nepomuk::Types::Class::allParentClasses() const -{ - return const_cast(this)->allParentClasses(); -} - - -QList Nepomuk::Types::Class::allSubClasses() -{ - if ( d ) { - D->initAncestors(); - return D->findSubClasses( D ).toList(); - } - else { - return QList(); - } -} - - -QList Nepomuk::Types::Class::allSubClasses() const -{ - return const_cast(this)->allSubClasses(); -} - - -bool Nepomuk::Types::Class::isParentOf( const Class& other ) -{ - if ( d ) { - D->initAncestors(); - - if ( D->children.contains( other ) ) { - return true; - } - else { - for ( QList::iterator it = D->children.begin(); - it != D->children.end(); ++it ) { - if ( ( *it ).isParentOf( other ) ) { - return true; - } - } - } - } - - return false; -} - - -bool Nepomuk::Types::Class::isParentOf( const Class& other ) const -{ - return const_cast(this)->isParentOf( other ); -} - - -bool Nepomuk::Types::Class::isSubClassOf( const Class& other ) -{ - if ( d ) { - D->init(); - - if ( D->parents.contains( other ) ) { - return true; - } - else { - for ( QList::iterator it = D->parents.begin(); - it != D->parents.end(); ++it ) { - if ( ( *it ).isSubClassOf( other ) ) { - return true; - } - } - } - } - - return false; -} - - -bool Nepomuk::Types::Class::isSubClassOf( const Class& other ) const -{ - return const_cast(this)->isSubClassOf( other ); -} - - - - -#ifndef DISABLE_NEPOMUK_LEGACY -// Start of code for deprecated Class -// ---------------------------------- - -#include "global.h" -#include "ontologymanager.h" - -Nepomuk::Class::Class() - : Entity() -{ - d = new Private(); -} - - -Nepomuk::Class::Class( const Class& other ) - : Entity( other ) -{ - d = other.d; -} - - -Nepomuk::Class::~Class() -{ -} - - -Nepomuk::Class& Nepomuk::Class::operator=( const Class& other ) -{ - d = other.d; - return *this; -} - - -QList Nepomuk::Class::allProperties() const -{ - return d->domainOf.values(); -} - - -const Nepomuk::Property* Nepomuk::Class::findPropertyByName( const QString& name ) const -{ - for ( QHash::const_iterator it = d->domainOf.constBegin(); - it != d->domainOf.constEnd(); ++it ) { - const Property* p = it.value(); - if ( p->name() == name ) { - return p; - } - } - - return 0; -} - - -const Nepomuk::Property* Nepomuk::Class::findPropertyByLabel( const QString& label, const QString& language ) const -{ - for ( QHash::const_iterator it = d->domainOf.constBegin(); - it != d->domainOf.constEnd(); ++it ) { - const Property* p = it.value(); - if ( p->label( language ) == label ) { - return p; - } - } - - return 0; -} - - -const Nepomuk::Property* Nepomuk::Class::findPropertyByUri( const QUrl& uri ) const -{ - QHash::const_iterator it = d->domainOf.find( uri ); - if ( it != d->domainOf.constEnd() ) { - return it.value(); - } - else { - return 0; - } -} - - -QList Nepomuk::Class::parentClasses() const -{ - return d->parents; -} - - -QList Nepomuk::Class::subClasses() const -{ - return d->children; -} - - -bool Nepomuk::Class::isParentOf( const Class* other ) const -{ - if ( d->children.contains( other ) ) { - return true; - } - else { - for ( QList::const_iterator it = d->children.constBegin(); - it != d->children.constEnd(); ++it ) { - if ( ( *it )->isParentOf( other ) ) { - return true; - } - } - return false; - } -} - - -bool Nepomuk::Class::isSubClassOf( const Class* other ) const -{ - if ( d->parents.contains( other ) ) { - return true; - } - else { - for ( QList::const_iterator it = d->parents.constBegin(); - it != d->parents.constEnd(); ++it ) { - if ( ( *it )->isSubClassOf( other ) ) { - return true; - } - } - return false; - } -} - - -const Nepomuk::Class* Nepomuk::Class::load( const QUrl& uri ) -{ - Q_ASSERT( !uri.isEmpty() ); - - QUrl ns = extractNamespace( uri ); - - // load the ontology in the cache - const Ontology* ont = OntologyManager::instance()->getOntology( ns ); - - // return the requested class or an invalid one if the ontology - // was not found - if ( ont ) { - return ont->findClassByUri( uri ); - } - else { - return 0; - } -} - -#endif //DISABLE_NEPOMUK_LEGACY - diff --git a/nepomuk/types/class.h b/nepomuk/types/class.h deleted file mode 100644 index a17a1c65..00000000 --- a/nepomuk/types/class.h +++ /dev/null @@ -1,400 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007-2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_CLASS_H_ -#define _NEPOMUK_CLASS_H_ - -#include -#include -#include -#include - -#include "entity.h" -#include "nepomuk_export.h" - - -namespace Nepomuk { - namespace Types { - class Property; - - /** - * \class Class class.h Nepomuk/Types/Class - * - * \brief A Class is a resource of type rdf:Class. - * - * Class instances are explicitly shared. Two instances created - * with the same uri reference the same data. - * - * While Resource objects can be changed Class instances are considered - * to be static and never changed during their lifetime. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT Class : public Entity - { - friend class ClassPrivate; - - public: - /** - * Default constructor. Creates an empty Class. - */ - Class(); - - /** - * Create the class referred to by \p uri. - * The result is either a valid class which could be loaded from the - * Nepomuk store or a simple class which only contains the uri. - * - * Be aware that the data is only loaded once read. - * - * Subsequent calls result in a simple hash lookup of cached data. - */ - Class( const QUrl& uri ); - - /** - * Default copy constructor - */ - Class( const Class& ); - - /** - * Destructor - */ - ~Class(); - - /** - * Copy operator. - */ - Class& operator=( const Class& ); - - /** - * A Property has a certain range which is a Class or a Literal. - * \return A list of all properties that have this Class as a range. - * \sa Property::range() - */ - QList rangeOf(); - - /** - * A Property has a certain range which is a Class or a Literal. - * \return A list of all properties that have this Class as a range. - * \sa Property::range() - * - * Const version. - * - * \since 4.4 - */ - QList rangeOf() const; - - /** - * A Property has a certain domain which is a Class. - * \return A list of all properties that have this Class as a domain. - * \sa Property::domain() - */ - QList domainOf(); - - /** - * A Property has a certain domain which is a Class. - * \return A list of all properties that have this Class as a domain. - * \sa Property::domain() - * - * Const version. - * - * \since 4.4 - */ - QList domainOf() const; - - /** - * Search for a property in the class by its name. - * \param name The name of the property. - * \return the Property object identified by name or an invalid property if it could not be found. - */ - Property findPropertyByName( const QString& name ); - - /** - * Search for a property in the class by its name. - * \param name The name of the property. - * \return the Property object identified by name or an invalid property if it could not be found. - * - * Const version. - * - * \since 4.4 - */ - Property findPropertyByName( const QString& name ) const; - - /** - * Search for a property in the class by its label. - * \param label The label of the property (i.e. rdfs:label) - * \param language The language in which the label was specified. If empty the default rdfs:label - * is returned. - * \return the Property object identified by label or an invalid property if it could not be found. - */ - Property findPropertyByLabel( const QString& label, const QString& language = QString() ); - - /** - * Search for a property in the class by its label. - * \param label The label of the property (i.e. rdfs:label) - * \param language The language in which the label was specified. If empty the default rdfs:label - * is returned. - * \return the Property object identified by label or an invalid property if it could not be found. - * - * Const version. - * - * \since 4.4 - */ - Property findPropertyByLabel( const QString& label, const QString& language = QString() ) const; - - /** - * Each class can have multiple parent classes. This method - * provides a list of all direct parents. - * \return A list of all parent classes of this class. - * If the list is emppty it means that the class has no direct - * parents, i.e. it is derived from rdf:Resource. - * \sa allParentClasses() - */ - QList parentClasses(); - - /** - * Each class can have multiple parent classes. This method - * provides a list of all direct parents. - * \return A list of all parent classes of this class. - * If the list is emppty it means that the class has no direct - * parents, i.e. it is derived from rdf:Resource. - * \sa allParentClasses() - * - * Const version. - * - * \since 4.4 - */ - QList parentClasses() const; - - /** - * \return A list of all classes that have this class as a parent. - * Be aware that this list can never be final since other ontologies - * that have not been loaded yet may contain classes that are derived - * from this class. - */ - QList subClasses(); - - /** - * \return A list of all classes that have this class as a parent. - * Be aware that this list can never be final since other ontologies - * that have not been loaded yet may contain classes that are derived - * from this class. - * - * Const version. - * - * \since 4.4 - */ - QList subClasses() const; - - /** - * Recursively determines all parent classes of this class, not - * only the direct ones. - * \return A list of parent classes of this class. - * \sa parentClasses() - */ - QList allParentClasses(); - - /** - * Recursively determines all parent classes of this class, not - * only the direct ones. - * \return A list of parent classes of this class. - * \sa parentClasses() - * - * Const version. - * - * \since 4.4 - */ - QList allParentClasses() const; - - /** - * Recursively determines all sub classes of this class, not - * only the direct ones. - * \return A list of sub classes of this class. - * \sa subClasses() - */ - QList allSubClasses(); - - /** - * Recursively determines all sub classes of this class, not - * only the direct ones. - * \return A list of sub classes of this class. - * \sa subClasses() - * - * Const version. - * - * \since 4.4 - */ - QList allSubClasses() const; - - /** - * Check if a class inherits this class. This is a recursive method which - * does not only check direct child classes. - * - * \return true if other is derived from this class, false otherwise. - */ - bool isParentOf( const Class& other ); - - /** - * Check if a class inherits this class. This is a recursive method which - * does not only check direct child classes. - * - * \return true if other is derived from this class, false otherwise. - * - * Const version. - * - * \since 4.4 - */ - bool isParentOf( const Class& other ) const; - - /** - * Check if this class is derived from another class. This is a recursive method which - * does not only check direct child classes. - * - * \return true if this class is derived from other, false otherwise. - */ - bool isSubClassOf( const Class& other ); - - /** - * Check if this class is derived from another class. This is a recursive method which - * does not only check direct child classes. - * - * \return true if this class is derived from other, false otherwise. - * - * Const version. - * - * \since 4.4 - */ - bool isSubClassOf( const Class& other ) const; - }; - } -} - - -#ifndef DISABLE_NEPOMUK_LEGACY - -namespace Nepomuk { - - class Ontology; - class Property; - - /** - * A Class is a resource of type rdf:Class. - * - * \deprecated in favor of Nepomuk::Types::Class - */ - class KDE_DEPRECATED NEPOMUK_EXPORT Class : public Entity - { - public: - /** - * Default constructor. Creates an empty Class. - */ - Class(); - - /** - * Default copy constructor - */ - Class( const Class& ); - - /** - * Destructor - */ - ~Class(); - - Class& operator=( const Class& ); - - // an alternative would be: QList rangeOf() and QList domainOf() - QList allProperties() const; - - /** - * Search for a property in the class by its name. - * \param name The name of the property. - * \return the Property object identified by name or 0 if the property could not be found. - */ - const Property* findPropertyByName( const QString& name ) const; - - /** - * Search for a property in the class by its label. - * \param label The label of the property (i.e. rdfs:label) - * \param language The language in which the label was specified. If empty the default rdfs:label - * is returned. - * \return the Property object identified by label or 0 if the property could not be found. - */ - const Property* findPropertyByLabel( const QString& label, const QString& language = QString() ) const; - - /** - * Search for a property in the class by its name. - * \param uri the URI of the property - * \return the Property object identified by uri or 0 if the property could not be found. - */ - const Property* findPropertyByUri( const QUrl& uri ) const; - - /** - * Each class can have multiple parent classes. - * \return A list of all parent classes of this class. - * If the list is emppty it means that the class has no direct - * parents, i.e. it is derived from rdf:Resource. - */ - QList parentClasses() const; - - /** - * \return A list of all classes that have this class as a parent. - * Be aware that this list can never be final since other ontologies - * that have not been loaded yet may contain classes that are derived - * from this class. - */ - QList subClasses() const; - - /** - * Check if a class inherits this class. This is a recursive method which - * does not only check direct child classes. - * - * \return true if other is derived from this class, false otherwise. - */ - bool isParentOf( const Class* other ) const; - - /** - * Check if this class is derived from another class. This is a recursive method which - * does not only check direct child classes. - * - * \return true if this class is derived from other, false otherwise. - */ - bool isSubClassOf( const Class* other ) const; - - /** - * Loads a class actually including the whole ontology - * it is declared in. - * - * Dependancies are resolved automatically if possible. - * - * \return A Class object representing the class identified - * by uri or an invalid Class object if the resource identified - * by uri is either not a class or does not exist. - */ - static const Class* load( const QUrl& uri ); - - private: - class Private; - QSharedDataPointer d; - - friend class OntologyManager; - }; -} - -#endif -#endif diff --git a/nepomuk/types/class_p.h b/nepomuk/types/class_p.h deleted file mode 100644 index e786b81f..00000000 --- a/nepomuk/types/class_p.h +++ /dev/null @@ -1,85 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_CLASS_PRIVATE_H_ -#define _NEPOMUK_CLASS_PRIVATE_H_ - -#include "entity_p.h" -#include "class.h" -#include "property.h" - -#include -#include - - -namespace Nepomuk { - namespace Types { - class ClassPrivate : public EntityPrivate - { - public: - ClassPrivate( const QUrl& uri = QUrl() ); - - QList domainOf; - QList rangeOf; - - QList parents; - QList children; - - // -1 - unknown - // 0 - no - // 1 - yes - int propertiesAvailable; - - bool addProperty( const QUrl& property, const Soprano::Node& value ); - bool addAncestorProperty( const QUrl& ancestorResource, const QUrl& property ); - - void initProperties(); - bool loadProperties(); - - void reset( bool recursive ); - - // recursively find all parent or sub classes but stop at requestingClass to avoid endless loops - QSet findParentClasses( ClassPrivate* requestingClass ); - QSet findSubClasses( ClassPrivate* requestingClass ); - - protected: - virtual bool load(); - virtual bool loadAncestors(); - }; - } -} - -#ifndef DISABLE_NEPOMUK_LEGACY -namespace Nepomuk { - - class Property; - - class Class::Private : public QSharedData - { - public: - QHash domainOf; - QHash rangeOf; - - QList parents; - QList children; - }; -} -#endif - -#endif diff --git a/nepomuk/types/desktopontologyloader.cpp b/nepomuk/types/desktopontologyloader.cpp deleted file mode 100644 index 863bad30..00000000 --- a/nepomuk/types/desktopontologyloader.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "desktopontologyloader.h" -#include "fileontologyloader.h" - -#include -#include -#include -#include -#include - -#include - -#include - -struct OntoBuffer -{ - QString fileName; - Soprano::RdfSerialization serialization; -}; - - -class Nepomuk::DesktopOntologyLoader::Private -{ -public: - Private() { - } - - void updateOntologyCache() { -// ontoCache.clear(); - - QStringList allOntologies = KGlobal::dirs()->findAllResources( "data", "nepomuk/ontologies/*.desktop" ); - foreach( const QString &ontoDesktopFilePath, allOntologies ) { - KDesktopFile ontoDesktopFile( ontoDesktopFilePath ); - - if ( ontoDesktopFile.hasLinkType() ) { - QUrl uri = ontoDesktopFile.readUrl(); - - if ( !ontoCache.contains( uri ) ) { - QString path = ontoDesktopFile.readPath(); - - // make it an absolute path - if ( path[0] != QDir::separator() ) { - path.prepend( ontoDesktopFilePath.section( QDir::separator(), - 0, -2, - QString::SectionIncludeLeadingSep|QString::SectionIncludeTrailingSep ) ); - } - - OntoBuffer onto; - onto.fileName = path; - onto.serialization = Soprano::mimeTypeToSerialization( ontoDesktopFile.desktopGroup().readEntry( "MimeType", "application/rdf+xml" ) ); - - kDebug() << "(Nepomuk::DesktopOntologyLoader) found ontology " << uri; - ontoCache.insert( uri, onto ); - } - } - } - } - - // contains the filename for each cached ontology - QHash ontoCache; -}; - - -Nepomuk::DesktopOntologyLoader::DesktopOntologyLoader() - : OntologyLoader(), - d( new Private() ) -{ -} - - -Nepomuk::DesktopOntologyLoader::~DesktopOntologyLoader() -{ - delete d; -} - - -QList Nepomuk::DesktopOntologyLoader::allOntologies() -{ - d->updateOntologyCache(); - return d->ontoCache.keys(); -} - - -QList Nepomuk::DesktopOntologyLoader::loadOntology( const QUrl& url ) -{ - d->updateOntologyCache(); - if ( d->ontoCache.contains( url ) ) { - const OntoBuffer& onto = d->ontoCache[url]; - FileOntologyLoader loader( onto.fileName, onto.serialization ); - return loader.loadOntology( url ); - } - else { - kDebug() << "(Nepomuk::DesktopOntologyLoader) could not find ontology " << url; - return QList(); - } -} diff --git a/nepomuk/types/desktopontologyloader.h b/nepomuk/types/desktopontologyloader.h deleted file mode 100644 index 75bb1f29..00000000 --- a/nepomuk/types/desktopontologyloader.h +++ /dev/null @@ -1,62 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_DESKTOP_ONTOLOGY_LOADER_H_ -#define _NEPOMUK_DESKTOP_ONTOLOGY_LOADER_H_ - -#include "ontologyloader.h" -#include "nepomuk_export.h" - -#include -#include - -namespace Nepomuk { - /** - * The DesktopOntologyLoader reads ontologies from the installed - * ontologies on the desktop using KStandardDirs. - * All possible ontology installation folders are searched for - * ontology desktop files. - * - * \deprecated Ontologies should now be handled using the classes - * in the Nepomuk::Types namespace. - */ - class KDE_DEPRECATED NEPOMUK_EXPORT DesktopOntologyLoader : public OntologyLoader - { - public: - DesktopOntologyLoader(); - ~DesktopOntologyLoader(); - - /** - * Get a list of all ontology URIs that could be found - * on the system. - */ - QList allOntologies(); - - /** - * reimplemented from OntologyLoader - */ - QList loadOntology( const QUrl& url ); - - private: - class Private; - Private* const d; - }; -} - -#endif diff --git a/nepomuk/types/entity.cpp b/nepomuk/types/entity.cpp deleted file mode 100644 index 42f4232e..00000000 --- a/nepomuk/types/entity.cpp +++ /dev/null @@ -1,406 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "entity.h" -#include "entity_p.h" -#include "resourcemanager.h" - -#include -#include - -#include -#include -#include -#include -#include - -#include - - -Nepomuk::Types::EntityPrivate::EntityPrivate( const QUrl& uri_ ) - : mutex(QMutex::Recursive), - uri( uri_ ), - userVisible( true ), - available( uri_.isValid() ? -1 : 0 ), - ancestorsAvailable( uri_.isValid() ? -1 : 0 ) -{ -} - - -void Nepomuk::Types::EntityPrivate::init() -{ - QMutexLocker lock( &mutex ); - - if ( available < 0 ) { - available = load() ? 1 : 0; - } -} - - -void Nepomuk::Types::EntityPrivate::initAncestors() -{ - QMutexLocker lock( &mutex ); - - if ( ancestorsAvailable < 0 ) { - ancestorsAvailable = loadAncestors() ? 1 : 0; - } -} - - -bool Nepomuk::Types::EntityPrivate::load() -{ - const QString query = QString::fromLatin1( "select ?p ?o where { " - "graph ?g { <%1> ?p ?o . } . " - "{ ?g a %2 . } UNION { ?g a %3 . } . }" ) - .arg( QString::fromLatin1( uri.toEncoded() ), - Soprano::Node::resourceToN3( Soprano::Vocabulary::NRL::Ontology() ), - Soprano::Node::resourceToN3( Soprano::Vocabulary::NRL::KnowledgeBase() ) ); - - Soprano::QueryResultIterator it - = ResourceManager::instance()->mainModel()->executeQuery( query, Soprano::Query::QueryLanguageSparql ); - while ( it.next() ) { - QUrl property = it.binding( "p" ).uri(); - Soprano::Node value = it.binding( "o" ); - - if ( property == Soprano::Vocabulary::RDFS::label() ) { - if ( value.language().isEmpty() ) { - label = value.toString(); - } - else if( value.language() == KGlobal::locale()->language() ) { - l10nLabel = value.toString(); - } - } - - else if ( property == Soprano::Vocabulary::RDFS::comment() ) { - if ( value.language().isEmpty() ) { - comment = value.toString(); - } - else if( value.language() == KGlobal::locale()->language() ) { - l10nComment = value.toString(); - } - } - - else if ( property == Soprano::Vocabulary::NAO::hasSymbol() ) { - icon = KIcon( value.toString() ); - } - - else if ( property == Soprano::Vocabulary::NAO::userVisible() ) { - userVisible = value.literal().toBool(); - } - - else { - addProperty( property, value ); - } - } - - return !it.lastError(); -} - - -bool Nepomuk::Types::EntityPrivate::loadAncestors() -{ - const QString query = QString::fromLatin1( "select ?s ?p where { " - "graph ?g { ?s ?p <%1> . } . " - "{ ?g a %2 . } UNION { ?g a %3 . } . }" ) - .arg( QString::fromLatin1( uri.toEncoded() ), - Soprano::Node::resourceToN3( Soprano::Vocabulary::NRL::Ontology() ), - Soprano::Node::resourceToN3( Soprano::Vocabulary::NRL::KnowledgeBase() ) ); - - Soprano::QueryResultIterator it - = ResourceManager::instance()->mainModel()->executeQuery( query, Soprano::Query::QueryLanguageSparql ); - while ( it.next() ) { - addAncestorProperty( it.binding( "s" ).uri(), it.binding( "p" ).uri() ); - } - - return !it.lastError(); -} - - - -void Nepomuk::Types::EntityPrivate::reset( bool ) -{ - QMutexLocker lock( &mutex ); - - label.clear(); - comment.clear(); - l10nLabel.clear(); - l10nComment.clear();; - - icon = QIcon(); - - available = -1; - ancestorsAvailable = -1; -} - - -Nepomuk::Types::Entity::Entity() -{ -} - - -Nepomuk::Types::Entity::Entity( const Entity& other ) -{ - d = other.d; -} - - -Nepomuk::Types::Entity::~Entity() -{ -} - - -Nepomuk::Types::Entity& Nepomuk::Types::Entity::operator=( const Entity& other ) -{ - d = other.d; - return *this; -} - - -QUrl Nepomuk::Types::Entity::uri() const -{ - return d ? d->uri : QUrl(); -} - - -QString Nepomuk::Types::Entity::name() const -{ - return d ? (d->uri.fragment().isEmpty() ? d->uri.toString().section('/',-1) : d->uri.fragment() ) : QString(); -} - - -QString Nepomuk::Types::Entity::label( const QString& language ) -{ - if ( d ) { - d->init(); - - if ( language == KGlobal::locale()->language() && - !d->l10nLabel.isEmpty() ) { - return d->l10nLabel; - } - else if( !d->label.isEmpty() ) { - return d->label; - } - else { - return name(); - } - } - else { - return QString(); - } -} - - -QString Nepomuk::Types::Entity::label( const QString& language ) const -{ - return const_cast(this)->label( language ); -} - - -QString Nepomuk::Types::Entity::comment( const QString& language ) -{ - if ( d ) { - d->init(); - - if ( language == KGlobal::locale()->language() && - !d->l10nComment.isEmpty() ) { - return d->l10nComment; - } - else { - return d->comment; - } - } - else { - return QString(); - } -} - - -QString Nepomuk::Types::Entity::comment( const QString& language ) const -{ - return const_cast(this)->comment( language ); -} - - -QIcon Nepomuk::Types::Entity::icon() -{ - if ( d ) { - d->init(); - - return d->icon; - } - else { - return QIcon(); - } -} - - -QIcon Nepomuk::Types::Entity::icon() const -{ - return const_cast(this)->icon(); -} - - -bool Nepomuk::Types::Entity::isValid() const -{ - return d ? d->uri.isValid() : false; -} - - -bool Nepomuk::Types::Entity::isAvailable() -{ - if ( d ) { - d->init(); - return d->available == 1; - } - else { - return false; - } -} - - -bool Nepomuk::Types::Entity::isAvailable() const -{ - return const_cast(this)->isAvailable(); -} - - -void Nepomuk::Types::Entity::reset( bool recursive ) -{ - if( d ) - d->reset( recursive ); -} - - -bool Nepomuk::Types::Entity::userVisible() const -{ - if ( d ) { - d->init(); - return d->userVisible; - } - else { - return true; - } -} - - -bool Nepomuk::Types::Entity::operator==( const Entity& other ) const -{ - // since we use one instace cache we can improve comparation operations - // intensly by not comparing URLs but pointers. - return( d.constData() == other.d.constData() ); -} - - -bool Nepomuk::Types::Entity::operator==( const QUrl& other ) const -{ - if( d ) - return( d->uri == other ); - else - return other.isEmpty(); -} - - -bool Nepomuk::Types::Entity::operator!=( const Entity& other ) const -{ - // since we use one instace cache we can improve comparation operations - // intensly by not comparing URLs but pointers. - return( d.constData() != other.d.constData() ); -} - - -bool Nepomuk::Types::Entity::operator!=( const QUrl& other ) const -{ - if( d ) - return( d->uri != other ); - else - return !other.isEmpty(); -} - - - -#ifndef DISABLE_NEPOMUK_LEGACY - -// Code for old deprecated Entity class -// ------------------------------------------- -Nepomuk::Entity::Entity() -{ - d = new Private(); -} - -Nepomuk::Entity::Entity( const Entity& other ) -{ - d = other.d; -} - - -Nepomuk::Entity::~Entity() -{ -} - - -Nepomuk::Entity& Nepomuk::Entity::operator=( const Entity& other ) -{ - d = other.d; - return *this; -} - - -const Nepomuk::Ontology* Nepomuk::Entity::definingOntology() const -{ - return d->ontology; -} - - -QUrl Nepomuk::Entity::uri() const -{ - return d->uri; -} - - -QString Nepomuk::Entity::name() const -{ - return d->uri.fragment(); -} - - -QString Nepomuk::Entity::label( const QString& language ) const -{ - QHash::const_iterator it = d->l10nLabels.find( language ); - if ( it != d->l10nLabels.constEnd() ) { - return it.value(); - } - else { - return d->label; - } -} - - -QString Nepomuk::Entity::comment( const QString& language ) const -{ - QHash::const_iterator it = d->l10nComments.find( language ); - if ( it != d->l10nComments.constEnd() ) { - return it.value(); - } - else { - return d->comment; - } -} - -#endif // DISABLE_NEPOMUK_LEGACY - diff --git a/nepomuk/types/entity.h b/nepomuk/types/entity.h deleted file mode 100644 index 597a76b8..00000000 --- a/nepomuk/types/entity.h +++ /dev/null @@ -1,309 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_ENTITY_H_ -#define _NEPOMUK_ENTITY_H_ - -#include -#include -#include -#include - -#include - -#include -#include - -#include "nepomuk_export.h" - -class QIcon; - - -namespace Nepomuk { - namespace Types { - class EntityPrivate; - - /** - * \brief Abstract base class for Class and Property; - * - * Base class for static ontology entities Class and Property. - * It encapsulates the generic labels and comments that both - * types have. - * - * Due to internal optimizations comparing two Entities is much - * faster than comparing two QUrl objects. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT Entity - { - public: - /** - * Default copy constructor. - */ - Entity( const Entity& ); - - /** - * Destructor. - */ - virtual ~Entity(); - - /** - * Copy operator. - */ - Entity& operator=( const Entity& ); - - /** - * The name of the resource. The name equals the fragment of the - * URI. - */ - QString name() const; - - /** - * The URI of the resource - */ - QUrl uri() const; - - /** - * Retrieve the label of the entity (rdfs:label) - * - * \param language The code of the language to use. Defaults to the session - * language configured in KDE. As of KDE 4.3 only the currently - * configured language is loaded to save memory. - * - * \return The label translated into \p language or the default fallback label - * if no translation is available or the name() if no label could be found - * at all. - */ - QString label( const QString& language = KGlobal::locale()->language() ); - - /** - * Retrieve the label of the entity (rdfs:label) - * - * \param language The code of the language to use. Defaults to the session - * language configured in KDE. As of KDE 4.3 only the currently - * configured language is loaded to save memory. - * - * \return The label translated into \p language or the default fallback label - * if no translation is available or the name() if no label could be found - * at all. - * - * Const version - * - * \since 4.4 - */ - QString label( const QString& language = KGlobal::locale()->language() ) const; - - /** - * Retrieve the comment of the entity (rdfs:comment) - * - * \param language The code of the language to use. Defaults to the session - * language configured in KDE. As of KDE 4.3 only the currently - * configured language is loaded to save memory. - * - * \return The comment translated into \p language or the default fallback comment - * if no translation is available or an empty string if no comment could be found - * at all. - */ - QString comment( const QString& language = KGlobal::locale()->language() ); - - /** - * Retrieve the comment of the entity (rdfs:comment) - * - * \param language The code of the language to use. Defaults to the session - * language configured in KDE. As of KDE 4.3 only the currently - * configured language is loaded to save memory. - * - * \return The comment translated into \p language or the default fallback comment - * if no translation is available or an empty string if no comment could be found - * at all. - * - * Const version - * - * \since 4.4 - */ - QString comment( const QString& language = KGlobal::locale()->language() ) const; - - /** - * Retrieve the icon stored for the entity (nao:hasSymbol) - * - * If no symbol is defined for the entity a null icon will be returned. - * - * \since 4.1 - */ - QIcon icon(); - - /** - * Retrieve the icon stored for the entity (nao:hasSymbol) - * - * If no symbol is defined for the entity a null icon will be returned. - * - * Const version. - * - * \since 4.4 - */ - QIcon icon() const; - - /** - * Is this a valid Entity, i.e. has it a valid URI. - * A valid Entity does not necessarily have a label and a comment, it - * does not even have to exist in the Nepomuk store. - * - * \sa isAvailable - */ - bool isValid() const; - - /** - * Is this Entity available locally, i.e. could its properties - * be loaded from the Nepomuk store. - */ - bool isAvailable(); - - /** - * Is this Entity available locally, i.e. could its properties - * be loaded from the Nepomuk store. - * - * Const version. - * - * \since 4.4 - */ - bool isAvailable() const; - - /** - * The Types classes are optimized for performance under the - * aasumption that ontologies never change during the execution - * time of an application. - * - * Since there might be situations where this does not apply - * the internal cache can be reset via this method. - * - * \param recursive If \p true all related entities will be reset - * as well. - * - * \since 4.1 - */ - void reset( bool recursive = false ); - - /** - * nao:userVisible can be used to hide certain properties and - * resources of a certain type from the user. - * - * \return \p true if this entity should be visible to the user. - * - * \since 4.6 - */ - bool userVisible() const; - - /** - * An Entity can be used as a QUrl automagically. - */ - operator QUrl() const { return uri(); } - - /** - * Compares two Entity instances. This is faster than simply - * comparing the URIs. - */ - bool operator==( const Entity& other ) const; - - /** - * Compares the Entity with a URI. - * - * \since 4.5 - */ - bool operator==( const QUrl& other ) const; - - /** - * Compares two Entity instances. This is faster than simply - * comparing the URIs. - */ - bool operator!=( const Entity& other ) const; - - /** - * Compares the Entity with a URI. - * - * \since 4.5 - */ - bool operator!=( const QUrl& other ) const; - - protected: - /** - * Create an invalid Entity instance. - */ - Entity(); - - QExplicitlySharedDataPointer d; - }; - - inline uint qHash( const Entity& c ) - { - return qHash( c.uri() ); - } - } -} - -#ifndef DISABLE_NEPOMUK_LEGACY - -namespace Nepomuk { - - class Ontology; - - /** - * \deprecated in favor of Nepomuk::Types::Entity - */ - class KDE_DEPRECATED NEPOMUK_EXPORT Entity - { - public: - Entity( const Entity& ); - ~Entity(); - - Entity& operator=( const Entity& ); - - /** - * The ontology in which the resource is defined. - */ - const Ontology* definingOntology() const; - - /** - * The name of the resource. The name equals the fragment of the - * URI. - */ - QString name() const; - - /** - * The URI of the resource - */ - QUrl uri() const; - - QString label( const QString& language = QString() ) const; - QString comment( const QString& language = QString() ) const; - - protected: - Entity(); - - private: - class Private; - QSharedDataPointer d; - - friend class OntologyManager; - }; -} - -#endif // DISABLE_NEPOMUK_LEGACY - -#endif // _NEPOMUK_ENTITY_H_ diff --git a/nepomuk/types/entity_p.h b/nepomuk/types/entity_p.h deleted file mode 100644 index a663f4e9..00000000 --- a/nepomuk/types/entity_p.h +++ /dev/null @@ -1,92 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_ENTITY_PRIVATE_H_ -#define _NEPOMUK_ENTITY_PRIVATE_H_ - -#include "entity.h" - -#include -#include -#include -#include -#include -#include - -namespace Nepomuk { - namespace Types { - class EntityPrivate : public QSharedData - { - public: - EntityPrivate( const QUrl& uri = QUrl() ); - virtual ~EntityPrivate() {} - - QMutex mutex; - - QUrl uri; - QString label; - QString comment; - QString l10nLabel; - QString l10nComment; - - QIcon icon; - - bool userVisible; - - // -1 - unknown - // 0 - no - // 1 - yes - int available; - int ancestorsAvailable; - - void init(); - void initAncestors(); - - virtual bool addProperty( const QUrl& property, const Soprano::Node& value ) = 0; - virtual bool addAncestorProperty( const QUrl& ancestorResource, const QUrl& property ) = 0; - - virtual void reset( bool recursive ); - - protected: - virtual bool load(); - virtual bool loadAncestors(); - }; - } -} - - -#ifndef DISABLE_NEPOMUK_LEGACY -class Nepomuk::Entity::Private : public QSharedData -{ -public: - Private() - : ontology( 0 ) { - } - - const Ontology* ontology; - - QUrl uri; - QString label; - QString comment; - QHash l10nLabels; - QHash l10nComments; -}; -#endif - -#endif diff --git a/nepomuk/types/entitymanager.cpp b/nepomuk/types/entitymanager.cpp deleted file mode 100644 index 5226f1ce..00000000 --- a/nepomuk/types/entitymanager.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "entitymanager.h" -#include "class_p.h" -#include "property_p.h" -#include "ontology_p.h" - -#include "resourcemanager.h" - -#include - -Q_GLOBAL_STATIC( Nepomuk::Types::EntityManager, entityManager ) - -Nepomuk::Types::EntityManager::EntityManager() -{ -} - - -QExplicitlySharedDataPointer Nepomuk::Types::EntityManager::getClass( const QUrl& uri ) -{ - QMutexLocker lock( &m_mutex ); - - QHash >::const_iterator it = m_classMap.constFind( uri ); - if ( it != m_classMap.constEnd() ) { - return it.value(); - } - else { - QExplicitlySharedDataPointer scp( new ClassPrivate( uri ) ); - m_classMap.insert( uri, scp ); - return scp; - } -} - - -QExplicitlySharedDataPointer Nepomuk::Types::EntityManager::getProperty( const QUrl& uri ) -{ - QMutexLocker lock( &m_mutex ); - - QHash >::const_iterator it = m_propertyMap.constFind( uri ); - if ( it != m_propertyMap.constEnd() ) { - return it.value(); - } - else { - QExplicitlySharedDataPointer cp( new PropertyPrivate( uri ) ); - m_propertyMap.insert( uri, cp ); - return cp; - } -} - - -QExplicitlySharedDataPointer Nepomuk::Types::EntityManager::getOntology( const QUrl& uri ) -{ - QMutexLocker lock( &m_mutex ); - - QHash >::const_iterator it = m_ontologyMap.constFind( uri ); - if ( it != m_ontologyMap.constEnd() ) { - return it.value(); - } - else { - QExplicitlySharedDataPointer cp( new OntologyPrivate( uri ) ); - m_ontologyMap.insert( uri, cp ); - return cp; - } -} - - -Nepomuk::Types::EntityManager* Nepomuk::Types::EntityManager::self() -{ - return entityManager(); -} diff --git a/nepomuk/types/entitymanager.h b/nepomuk/types/entitymanager.h deleted file mode 100644 index 712a0b2d..00000000 --- a/nepomuk/types/entitymanager.h +++ /dev/null @@ -1,64 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_ENTITY_MANAGER_H_ -#define _NEPOMUK_ENTITY_MANAGER_H_ - -#include -#include -#include -#include - - -namespace Soprano { - class Statement; -} - -namespace Nepomuk { - namespace Types { - class EntityPrivate; - class ClassPrivate; - class PropertyPrivate; - class OntologyPrivate; - - /** - * Cache for all loaded entities. - */ - class EntityManager - { - public: - EntityManager(); - - QExplicitlySharedDataPointer getClass( const QUrl& uri ); - QExplicitlySharedDataPointer getProperty( const QUrl& uri ); - QExplicitlySharedDataPointer getOntology( const QUrl& uri ); - - static EntityManager* self(); - - private: - QHash > m_classMap; - QHash > m_propertyMap; - QHash > m_ontologyMap; - - QMutex m_mutex; - }; - } -} - -#endif diff --git a/nepomuk/types/fileontologyloader.cpp b/nepomuk/types/fileontologyloader.cpp deleted file mode 100644 index b34594a5..00000000 --- a/nepomuk/types/fileontologyloader.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "fileontologyloader.h" - -#include - -#include -#include - - -class Nepomuk::FileOntologyLoader::Private -{ -public: - Private() - : serialization( Soprano::SerializationUnknown ) { - } - - QString filename; - Soprano::RdfSerialization serialization; -}; - - -Nepomuk::FileOntologyLoader::FileOntologyLoader() - : OntologyLoader(), - d( new Private() ) -{ -} - - -Nepomuk::FileOntologyLoader::FileOntologyLoader( const QString& filename, Soprano::RdfSerialization serialization ) - : OntologyLoader(), - d( new Private() ) -{ - setFileName( filename ); - setSerialization( serialization ); -} - - -Nepomuk::FileOntologyLoader::~FileOntologyLoader() -{ - delete d; -} - - -void Nepomuk::FileOntologyLoader::setFileName( const QString& filename ) -{ - d->filename = filename; -} - - -void Nepomuk::FileOntologyLoader::setSerialization( Soprano::RdfSerialization s ) -{ - d->serialization = s; -} - - -QString Nepomuk::FileOntologyLoader::fileName() const -{ - return d->filename; -} - - -QList Nepomuk::FileOntologyLoader::loadOntology( const QUrl& url ) -{ - QString filename; - - if ( d->filename.isEmpty() ) { - // FIXME: use KIO or is QT sufficient? Actually how about NetAccess and a temp file? - qDebug() << "(FileOntologyLoader) remote support not implemented yet."; - return QList(); - } - else { - filename = d->filename; - } - - QList sl; - - QFile f( filename ); - if ( f.open( QIODevice::ReadOnly ) ) { - // TODO: how can we check if the requested onto is really defined in this file? - const Soprano::Parser* rdfParser = Soprano::PluginManager::instance()->discoverParserForSerialization( d->serialization ); - if ( rdfParser ) { - sl = rdfParser->parseFile( d->filename, url, d->serialization ).allStatements(); - } - } - else { - qDebug() << "(FileOntologyLoader) failed to open " << filename; - } - - return sl; -} diff --git a/nepomuk/types/fileontologyloader.h b/nepomuk/types/fileontologyloader.h deleted file mode 100644 index b0e8adcf..00000000 --- a/nepomuk/types/fileontologyloader.h +++ /dev/null @@ -1,89 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_FILE_ONTOLOGY_LOADER_H_ -#define _NEPOMUK_FILE_ONTOLOGY_LOADER_H_ - -#include "ontologyloader.h" -#include "nepomuk_export.h" - -#include -#include - - -namespace Nepomuk { - /** - * \deprecated Ontologies should now be handled using the classes - * in the Nepomuk::Types namespace. - */ - class KDE_DEPRECATED NEPOMUK_EXPORT FileOntologyLoader : public OntologyLoader - { - public: - /** - * Default constructor. - * Creates a FileOntologyLoader that will try to load the - * ontology directly from its URL, i.e. the internet. - */ - FileOntologyLoader(); - - /** - * Creates a FileOntologyLoader that will load the - * ontology from the specified filename. - */ - explicit FileOntologyLoader( const QString& filename, - Soprano::RdfSerialization serialization = Soprano::SerializationUnknown ); - - /** - * Destructor - */ - ~FileOntologyLoader(); - - /** - * Set the filename to be used for reading the ontologies. - * If no filename has been set FileOntologyLoader will try - * load the ontology file from the internet, i.e. directly - * use the ontology URL - NOT IMPLEMENTED YET. - */ - void setFileName( const QString& filename ); - - /** - * The filename that has been set. - * \sa setFileName - * \return The filename set (can be empty) - */ - QString fileName() const; - - /** - * Set the serialization that is used in the file. - * Defaults to Soprano::SerializationUnknown - */ - void setSerialization( Soprano::RdfSerialization ); - - /** - * reimplemented from OntologyLoader - */ - QList loadOntology( const QUrl& url ); - - private: - class Private; - Private* const d; - }; -} - -#endif diff --git a/nepomuk/types/global.cpp b/nepomuk/types/global.cpp deleted file mode 100644 index 0c89402d..00000000 --- a/nepomuk/types/global.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "global.h" - -#include -#include - - -QUrl Nepomuk::extractNamespace( const QUrl& url ) -{ - QByteArray s = url.toEncoded(); - int pos = s.lastIndexOf( '#' ); - if ( pos == -1 ) { - pos = s.lastIndexOf( '/' ); - } - if ( pos == -1 ) { - kError() << " Failed to extract namespace from " << url << endl; - return QUrl(); - } - return QUrl::fromEncoded( s.left( pos+1 ) ); -} diff --git a/nepomuk/types/global.h b/nepomuk/types/global.h deleted file mode 100644 index 89aaf1a6..00000000 --- a/nepomuk/types/global.h +++ /dev/null @@ -1,32 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_GLOBAL_H_ -#define _NEPOMUK_GLOBAL_H_ - -#include "nepomuk_export.h" - -#include -#include - -namespace Nepomuk { - KDE_DEPRECATED NEPOMUK_EXPORT QUrl extractNamespace( const QUrl& url ); -} - -#endif diff --git a/nepomuk/types/literal.cpp b/nepomuk/types/literal.cpp deleted file mode 100644 index 523be9d2..00000000 --- a/nepomuk/types/literal.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "literal.h" -#include "literal_p.h" - -#include -#include - -#include - -#include - - -namespace { -typedef QHash XmlSchemaMap; - -K_GLOBAL_STATIC(XmlSchemaMap, s_xmlSchemaTypes) - -void initXmlSchemaTypes() { - if( s_xmlSchemaTypes->isEmpty() ) { - s_xmlSchemaTypes->insert( "int", QVariant::Int ); - s_xmlSchemaTypes->insert( "integer", QVariant::Int ); - s_xmlSchemaTypes->insert( "negativeInteger", QVariant::Int ); - s_xmlSchemaTypes->insert( "decimal", QVariant::Int ); - s_xmlSchemaTypes->insert( "short", QVariant::Int ); - s_xmlSchemaTypes->insert( "long", QVariant::LongLong ); - s_xmlSchemaTypes->insert( "unsignedInt", QVariant::UInt ); - s_xmlSchemaTypes->insert( "unsignedShort", QVariant::UInt ); - s_xmlSchemaTypes->insert( "unsignedLong", QVariant::ULongLong ); - s_xmlSchemaTypes->insert( "boolean", QVariant::Bool ); - s_xmlSchemaTypes->insert( "double", QVariant::Double ); - s_xmlSchemaTypes->insert( "float", QVariant::Double ); - s_xmlSchemaTypes->insert( "string", QVariant::String ); - s_xmlSchemaTypes->insert( "date", QVariant::Date ); - s_xmlSchemaTypes->insert( "time", QVariant::Time ); - s_xmlSchemaTypes->insert( "dateTime", QVariant::DateTime ); - // s_xmlSchemaTypes->insert( "", QVariant::Url ); - } -} - -const XmlSchemaMap& xmlSchemaTypes() -{ - if(s_xmlSchemaTypes->isEmpty()) - initXmlSchemaTypes(); - return *s_xmlSchemaTypes; -} -} - - -Nepomuk::Types::Literal::Literal() -{ - d = new Private(); -} - - -Nepomuk::Types::Literal::Literal( const Literal& other ) -{ - d = other.d; -} - - -Nepomuk::Types::Literal::Literal( const QUrl& dataType ) -{ - d = new Private(); - d->dataTypeUri = dataType; - - // now determine the QVariant type - initXmlSchemaTypes(); - - // check if it is a known type, otherwise leave it as QVariant::Invalid - if ( dataType == Soprano::Vocabulary::RDFS::Literal() ) { - d->dataType = QVariant::String; - } - else { - QHash::const_iterator it = xmlSchemaTypes().constFind( dataType.fragment() ); - if ( it != xmlSchemaTypes().constEnd() ) { - d->dataType = it.value(); - } - } -} - - -Nepomuk::Types::Literal::~Literal() -{ -} - - -Nepomuk::Types::Literal& Nepomuk::Types::Literal::operator=( const Literal& other ) -{ - d = other.d; - return *this; -} - - -QUrl Nepomuk::Types::Literal::dataTypeUri() const -{ - return d->dataTypeUri; -} - - -QVariant::Type Nepomuk::Types::Literal::dataType() const -{ - return d->dataType; -} - - -bool Nepomuk::Types::Literal::isValid() const -{ - return d->dataTypeUri.isValid(); -} - - -#ifndef DISABLE_NEPOMUK_LEGACY - -Nepomuk::Literal::Literal() -{ - d = new Private(); -} - - -Nepomuk::Literal::Literal( const Literal& other ) -{ - d = other.d; -} - - -Nepomuk::Literal::Literal( const QUrl& dataType ) -{ - d = new Private(); - d->dataTypeUri = dataType; - - // now determine the QVariant type - initXmlSchemaTypes(); - - // check if it is a known type, otherwise leave it as QVariant::Invalid - QHash::const_iterator it = xmlSchemaTypes().constFind( dataType.fragment() ); - if ( it != xmlSchemaTypes().constEnd() ) { - d->dataType = it.value(); - } -} - - -Nepomuk::Literal::~Literal() -{ -} - - -Nepomuk::Literal& Nepomuk::Literal::operator=( const Literal& other ) -{ - d = other.d; - return *this; -} - - -const QUrl& Nepomuk::Literal::dataTypeUri() const -{ - return d->dataTypeUri; -} - - -QVariant::Type Nepomuk::Literal::dataType() const -{ - return d->dataType; -} - -#endif // DISABLE_NEPOMUK_LEGACY - diff --git a/nepomuk/types/literal.h b/nepomuk/types/literal.h deleted file mode 100644 index fe652130..00000000 --- a/nepomuk/types/literal.h +++ /dev/null @@ -1,125 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_LITERAL_H_ -#define _NEPOMUK_LITERAL_H_ - -#include -#include -#include - -#include "nepomuk_export.h" - -namespace Nepomuk { - namespace Types { - /** - * \class Literal literal.h Nepomuk/Types/Literal - * - * \brief Defines a literal type based on XML Schema. - * - * Each valid Literal represents the literal type - * as XML Schema URI and as QVariant type. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT Literal - { - public: - /** - * Default constructor. - * Creates an empty Literal - */ - Literal(); - Literal( const Literal& ); - Literal( const QUrl& dataTypeUri ); - ~Literal(); - - Literal& operator=( const Literal& ); - - /** - * The XML Schema type URI. - */ - QUrl dataTypeUri() const; - - /** - * The type converted to a QVariant::Type. - * \return The QVariant::Type that corresponds to the XML Schema type or - * QVariant::Invalid if it could not be matched. - */ - QVariant::Type dataType() const; - - /** - * Is this a valid Literal, i.e. has it a valid URI. - */ - bool isValid() const; - - private: - class Private; - QExplicitlySharedDataPointer d; - }; - } -} - - -#ifndef DISABLE_NEPOMUK_LEGACY - -namespace Nepomuk { - /** - * \brief Defines a literal type based on XML Schema. - * - * Each valid Literal represents the literal type - * as XML Schema URI and as QVariant type. - * - * \deprecated in favor of Nepomuk::Types::Literal - */ - class KDE_DEPRECATED NEPOMUK_EXPORT Literal - { - public: - /** - * Default constructor. - * Creates an empty Literal - */ - Literal(); - Literal( const Literal& ); - Literal( const QUrl& dataTypeUri ); - ~Literal(); - - Literal& operator=( const Literal& ); - - /** - * The XML Schema type URI. - */ - const QUrl& dataTypeUri() const; - - /** - * The type converted to a QVariant::Type. - * \return The QVariant::Type that corresponds to the XML Schema type or - * QVariant::Invalid if it could not be matched. - */ - QVariant::Type dataType() const; - - private: - class Private; - QSharedDataPointer d; - }; -} - -#endif // DISABLE_NEPOMUK_LEGACY - -#endif diff --git a/nepomuk/types/literal_p.h b/nepomuk/types/literal_p.h deleted file mode 100644 index c066a0ea..00000000 --- a/nepomuk/types/literal_p.h +++ /dev/null @@ -1,53 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_LITERAL_PRIVATE_H_ -#define _NEPOMUK_LITERAL_PRIVATE_H_ - -#include "literal.h" - -#include -#include -#include - -class Nepomuk::Types::Literal::Private : public QSharedData -{ - public: - Private() - : dataType( QVariant::Invalid ) { - } - - QUrl dataTypeUri; - QVariant::Type dataType; -}; - -#ifndef DISABLE_NEPOMUK_LEGACY -class Nepomuk::Literal::Private : public QSharedData -{ - public: - Private() - : dataType( QVariant::Invalid ) { - } - - QUrl dataTypeUri; - QVariant::Type dataType; -}; -#endif - -#endif diff --git a/nepomuk/types/nepomukontologyloader.cpp b/nepomuk/types/nepomukontologyloader.cpp deleted file mode 100644 index f6b7b501..00000000 --- a/nepomuk/types/nepomukontologyloader.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "nepomukontologyloader.h" -#include "global.h" -#include "resourcemanager.h" - -#include -#include -#include -#include - -#include - - -class Nepomuk::NepomukOntologyLoader::Private -{ -public: -}; - - -Nepomuk::NepomukOntologyLoader::NepomukOntologyLoader() - : OntologyLoader(), - d( 0 ) -{ -} - - -Nepomuk::NepomukOntologyLoader::~NepomukOntologyLoader() -{ -} - - -QList Nepomuk::NepomukOntologyLoader::loadOntology( const QUrl& uri ) -{ - QList sl; - - // get the complete named graph describing the ontology - Soprano::QueryResultIterator it - = ResourceManager::instance()->mainModel()->executeQuery( QString::fromLatin1( "construct {?s ?p ?o} " - "where { GRAPH %1 { ?s ?p ?o } . }" ) - .arg( Soprano::Node::resourceToN3(uri) ), - Soprano::Query::QueryLanguageSparql ); - while ( it.next() ) { - sl.append( it.currentStatement() ); - } - - return sl; -} diff --git a/nepomuk/types/nepomukontologyloader.h b/nepomuk/types/nepomukontologyloader.h deleted file mode 100644 index d9640424..00000000 --- a/nepomuk/types/nepomukontologyloader.h +++ /dev/null @@ -1,45 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_NEPOMUK_ONTOLOGY_LOADER_H_ -#define _NEPOMUK_NEPOMUK_ONTOLOGY_LOADER_H_ - -#include "ontologyloader.h" -#include "nepomuk_export.h" - -namespace Nepomuk { - /** - * \deprecated Ontologies should now be handled using the classes - * in the Nepomuk::Types namespace. - */ - class KDE_DEPRECATED NEPOMUK_EXPORT NepomukOntologyLoader : public OntologyLoader - { - public: - NepomukOntologyLoader(); - ~NepomukOntologyLoader(); - - QList loadOntology( const QUrl& url ); - - private: - class Private; - Private* const d; - }; -} - -#endif diff --git a/nepomuk/types/ontology.cpp b/nepomuk/types/ontology.cpp deleted file mode 100644 index 3459d680..00000000 --- a/nepomuk/types/ontology.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "ontology.h" -#include "ontology_p.h" -#include "class.h" -#include "property.h" -#include "entitymanager.h" -#include "resourcemanager.h" - -#include -#include -#include -#include -#include -#include - -#undef D -#define D static_cast( d.data() ) - -Nepomuk::Types::OntologyPrivate::OntologyPrivate( const QUrl& uri ) - : EntityPrivate( uri ), - entitiesAvailable( uri.isValid() ? -1 : 0 ) -{ -} - - -void Nepomuk::Types::OntologyPrivate::initEntities() -{ - if ( entitiesAvailable < 0 ) { - entitiesAvailable = loadEntities() ? 1 : 0; - } -} - - -bool Nepomuk::Types::OntologyPrivate::loadEntities() -{ - // load classes - // We use a FILTER(STR(?ns)...) to support both Soprano 2.3 (with plain literals) and earlier (with only typed ones) - Soprano::QueryResultIterator it - = ResourceManager::instance()->mainModel()->executeQuery( QString("select ?c where { " - "graph ?g { ?c a <%1> . } . " - "?g <%2> ?ns . " - "FILTER(STR(?ns) = \"%3\") . }" ) - .arg( Soprano::Vocabulary::RDFS::Class().toString() ) - .arg( Soprano::Vocabulary::NAO::hasDefaultNamespace().toString() ) - .arg( QString::fromLatin1( uri.toEncoded() ) ), - Soprano::Query::QueryLanguageSparql ); - while ( it.next() ) { - classes.append( Class( it.binding( "c" ).uri() ) ); - } - - - // load properties - it = ResourceManager::instance()->mainModel()->executeQuery( QString("select ?p where { " - "graph ?g { ?p a <%1> . } . " - "?g <%2> ?ns . " - "FILTER(STR(?ns) = \"%3\") . }" ) - .arg( Soprano::Vocabulary::RDF::Property().toString() ) - .arg( Soprano::Vocabulary::NAO::hasDefaultNamespace().toString() ) - .arg( QString::fromLatin1( uri.toEncoded() ) ), - Soprano::Query::QueryLanguageSparql ); - while ( it.next() ) { - properties.append( Property( it.binding( "p" ).uri() ) ); - } - - return !it.lastError(); -} - - -bool Nepomuk::Types::OntologyPrivate::addProperty( const QUrl&, const Soprano::Node& ) -{ - return false; -} - - -bool Nepomuk::Types::OntologyPrivate::addAncestorProperty( const QUrl&, const QUrl& ) -{ - return false; -} - - -void Nepomuk::Types::OntologyPrivate::reset( bool recursive ) -{ - QMutexLocker lock( &mutex ); - - if ( entitiesAvailable != -1 ) { - if ( recursive ) { - foreach( Class c, classes ) { - c.reset( true ); - } - foreach( Property p, properties ) { - p.reset( true ); - } - } - classes.clear(); - properties.clear(); - - entitiesAvailable = -1; - } - - EntityPrivate::reset( recursive ); -} - - - -Nepomuk::Types::Ontology::Ontology() -{ - d = new OntologyPrivate(); -} - - -Nepomuk::Types::Ontology::Ontology( const QUrl& uri ) -{ - d = EntityManager::self()->getOntology( uri ); -} - - -Nepomuk::Types::Ontology::Ontology( const Ontology& other ) - : Entity( other ) -{ -} - - -Nepomuk::Types::Ontology::~Ontology() -{ -} - - -Nepomuk::Types::Ontology& Nepomuk::Types::Ontology::operator=( const Ontology& other ) -{ - d = other.d; - return *this; -} - - -QList Nepomuk::Types::Ontology::allClasses() -{ - D->initEntities(); - return D->classes; -} - - -Nepomuk::Types::Class Nepomuk::Types::Ontology::findClassByName( const QString& name ) -{ - D->initEntities(); - for ( QList::const_iterator it = D->classes.constBegin(); - it != D->classes.constEnd(); ++it ) { - const Class& c = *it; - if ( c.name() == name ) { - return c; - } - } - - return Class(); -} - - -Nepomuk::Types::Class Nepomuk::Types::Ontology::findClassByLabel( const QString& label, const QString& language ) -{ - D->initEntities(); - for ( QList::iterator it = D->classes.begin(); - it != D->classes.end(); ++it ) { - Class& c = *it; - if ( c.label( language ) == label ) { - return c; - } - } - - return Class(); -} - - -QList Nepomuk::Types::Ontology::allProperties() -{ - D->initEntities(); - return D->properties; -} - - -Nepomuk::Types::Property Nepomuk::Types::Ontology::findPropertyByName( const QString& name ) -{ - D->initEntities(); - for ( QList::const_iterator it = D->properties.constBegin(); - it != D->properties.constEnd(); ++it ) { - const Property& p = *it; - if ( p.name() == name ) { - return p; - } - } - - return Property(); -} - - -Nepomuk::Types::Property Nepomuk::Types::Ontology::findPropertyByLabel( const QString& label, const QString& language ) -{ - D->initEntities(); - for ( QList::iterator it = D->properties.begin(); - it != D->properties.end(); ++it ) { - Property& p = *it; - if ( p.label( language ) == label ) { - return p; - } - } - - return Property(); -} - - -#ifndef DISABLE_NEPOMUK_LEGACY -// Start of code for deprecated Ontology -// ------------------------------------- -#include "global.h" -#include "ontologymanager.h" - - -Nepomuk::Ontology::Ontology() -{ - d = new Private; -} - - -Nepomuk::Ontology::Ontology( const Ontology& other ) -{ - d = other.d; -} - - -Nepomuk::Ontology::~Ontology() -{ -} - - -Nepomuk::Ontology& Nepomuk::Ontology::operator=( const Ontology& other) -{ - d = other.d; - return *this; -} - - -QUrl Nepomuk::Ontology::uri() const -{ - return d->uri; -} - - -QList Nepomuk::Ontology::allClasses() const -{ - return d->classes.values(); -} - - -const Nepomuk::Class* Nepomuk::Ontology::findClassByName( const QString& name ) const -{ - for ( QHash::const_iterator it = d->classes.constBegin(); - it != d->classes.constEnd(); ++it ) { - const Class* c = it.value(); - if ( c->name() == name ) { - return c; - } - } - - return 0; -} - - -const Nepomuk::Class* Nepomuk::Ontology::findClassByLabel( const QString& label, const QString& language ) const -{ - for ( QHash::const_iterator it = d->classes.constBegin(); - it != d->classes.constEnd(); ++it ) { - const Class* c = it.value(); - if ( c->label( language ) == label ) { - return c; - } - } - - return 0; -} - - -const Nepomuk::Class* Nepomuk::Ontology::findClassByUri( const QUrl& uri ) const -{ - QHash::const_iterator it = d->classes.find( uri ); - if ( it != d->classes.constEnd() ) { - return it.value(); - } - else { - return 0; - } -} - - -QList Nepomuk::Ontology::allProperties() const -{ - return d->properties.values(); -} - - -const Nepomuk::Property* Nepomuk::Ontology::findPropertyByName( const QString& name ) const -{ - for ( QHash::const_iterator it = d->properties.constBegin(); - it != d->properties.constEnd(); ++it ) { - const Property* p = it.value(); - if ( p->name() == name ) { - return p; - } - } - - return 0; -} - - -const Nepomuk::Property* Nepomuk::Ontology::findPropertyByLabel( const QString& label, const QString& language ) const -{ - for ( QHash::const_iterator it = d->properties.constBegin(); - it != d->properties.constEnd(); ++it ) { - const Property* p = it.value(); - if ( p->label( language ) == label ) { - return p; - } - } - - return 0; -} - - -const Nepomuk::Property* Nepomuk::Ontology::findPropertyByUri( const QUrl& uri ) const -{ - QHash::const_iterator it = d->properties.find( uri ); - if ( it != d->properties.constEnd() ) { - return it.value(); - } - else { - return 0; - } -} - - -const Nepomuk::Ontology* Nepomuk::Ontology::load( const QUrl& uri ) -{ - // load the ontology in the cache - return OntologyManager::instance()->getOntology( uri ); -} - -#endif // DISABLE_NEPOMUK_LEGACY - diff --git a/nepomuk/types/ontology.h b/nepomuk/types/ontology.h deleted file mode 100644 index 08c92196..00000000 --- a/nepomuk/types/ontology.h +++ /dev/null @@ -1,238 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_ONTOLOGY_H_ -#define _NEPOMUK_ONTOLOGY_H_ - -#include -#include -#include -#include - -#include "entity.h" -#include "nepomuk_export.h" - - -namespace Nepomuk { - namespace Types { - - class Class; - class Property; - - /** - * \class Ontology ontology.h Nepomuk/Types/Ontology - * - * \brief Represents one ontology. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT Ontology : public Entity - { - public: - /** - * Default constructor. Creates an empty Ontology. - */ - Ontology(); - - /** - * Create the ontology referred to by \p uri. - * The result is either a valid ontology which could be loaded from the - * Nepomuk store or a simple class which only contains the uri. - * - * Be aware that the data is only loaded once read. - * - * Subsequent calls result in a simple hash lookup of cached data. - */ - Ontology( const QUrl& uri ); - - /** - * Default copy constructor - */ - Ontology( const Ontology& ); - - /** - * Destructor - */ - ~Ontology(); - - Ontology& operator=( const Ontology& ); - - /** - * All classes defined in this ontology, i.e. its namespace. - */ - QList allClasses(); - - /** - * Search for a class in the ontology by its name. - * \param name The name of the class. - * \return the Class object identified by name or an invalid one if the class could not be found. - */ - Class findClassByName( const QString& name ); - - /** - * Search for a class in the ontology by its label. - * \param label The label of the class (i.e. rdfs:label) - * \param language The language in which the label was specified. If empty the default rdfs:label - * is returned. - * \return the Class object identified by label or an invalid one if the class could not be found. - */ - Class findClassByLabel( const QString& label, const QString& language = QString() ); - - /** - * A list of all properties defined in this ontology. This does not include properties that use - * classes of this ontology but are defined in a different one. - */ - QList allProperties(); - - /** - * Search for a property in the ontology by its name. - * \param name The name of the property. - * \return the Property object identified by name or an invalid one if the property could not be found. - */ - Property findPropertyByName( const QString& name ); - - /** - * Search for a property in the ontology by its label. - * \param label The label of the property (i.e. rdfs:label) - * \param language The language in which the label was specified. If empty the default rdfs:label - * is returned. - * \return the Property object identified by label or an invalid one if the property could not be found. - */ - Property findPropertyByLabel( const QString& label, const QString& language = QString() ); - }; - } -} - - -#ifndef DISABLE_NEPOMUK_LEGACY - -namespace Nepomuk { - - class Class; - class Property; - - /** - * Ontology represents one ontology specified using NRL. - * - * \deprecated in favor of Nepomuk::Types::Ontology - */ - class KDE_DEPRECATED NEPOMUK_EXPORT Ontology - { - public: - /** - * Default constructor. Creates an empty Ontology. - */ - Ontology(); - - /** - * Default copy constructor - */ - Ontology( const Ontology& ); - - /** - * Destructor - */ - ~Ontology(); - - Ontology& operator=( const Ontology& ); - - /** - * The URI of the ontology, i.e. its namespace - */ - QUrl uri() const; - - /** - * All classes defined in this ontology, i.e. its namespace. - */ - QList allClasses() const; - - /** - * Search for a class in the ontology by its name. - * \param name The name of the class. - * \return the Class object identified by name or 0 if the class could not be found. - */ - const Class* findClassByName( const QString& name ) const; - - /** - * Search for a class in the ontology by its label. - * \param label The label of the class (i.e. rdfs:label) - * \param language The language in which the label was specified. If empty the default rdfs:label - * is returned. - * \return the Class object identified by label or 0 if the class could not be found. - */ - const Class* findClassByLabel( const QString& label, const QString& language = QString() ) const; - - /** - * Search for a class in the ontology by its name. - * \param uri the URI of the class - * \return the Class object identified by uri or 0 if the class could not be found. - */ - const Class* findClassByUri( const QUrl& uri ) const; - - /** - * A list of all properties defined in this ontology. This does not include properties that use - * classes of this ontology but are defined in a different one. - */ - QList allProperties() const; - - /** - * Search for a property in the ontology by its name. - * \param name The name of the property. - * \return the Property object identified by name or 0 if the property could not be found. - */ - const Property* findPropertyByName( const QString& name ) const; - - /** - * Search for a property in the ontology by its label. - * \param label The label of the property (i.e. rdfs:label) - * \param language The language in which the label was specified. If empty the default rdfs:label - * is returned. - * \return the Property object identified by label or 0 if the property could not be found. - */ - const Property* findPropertyByLabel( const QString& label, const QString& language = QString() ) const; - - /** - * Search for a property in the ontology by its name. - * \param uri the URI of the property - * \return the Property object identified by uri or 0 if the property could not be found. - */ - const Property* findPropertyByUri( const QUrl& uri ) const; - - /** - * Loads an ontology. - * - * Dependancies are resolved automatically if possible. - * - * \return An Ontology object representing the ontology identified - * by uri or an invalid Ontology object if the resource identified - * by uri is either not an ontology or does not exist. - */ - static const Ontology* load( const QUrl& uri ); - - private: - class Private; - QSharedDataPointer d; - - friend class OntologyManager; - }; -} - -#endif // DISABLE_NEPOMUK_LEGACY - -#endif diff --git a/nepomuk/types/ontology_p.h b/nepomuk/types/ontology_p.h deleted file mode 100644 index 784da7ad..00000000 --- a/nepomuk/types/ontology_p.h +++ /dev/null @@ -1,77 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_ONTOLOGY_PRIVATE_H_ -#define _NEPOMUK_ONTOLOGY_PRIVATE_H_ - -#include "entity_p.h" -#include "class.h" -#include "property.h" - -#include -#include -#include - -namespace Nepomuk { - namespace Types { - class Class; - class Property; - - class OntologyPrivate : public EntityPrivate - { - public: - OntologyPrivate( const QUrl& uri = QUrl() ); - - QList classes; - QList properties; - - // -1 - unknown - // 0 - no - // 1 - yes - int entitiesAvailable; - - bool addProperty( const QUrl& property, const Soprano::Node& value ); - bool addAncestorProperty( const QUrl& ancestorResource, const QUrl& property ); - - void initEntities(); - bool loadEntities(); - - void reset( bool recursive ); - }; - } -} - -#ifndef DISABLE_NEPOMUK_LEGACY -#include "ontology.h" -namespace Nepomuk { - - class Class; - class Property; - - class Ontology::Private : public QSharedData - { - public: - QUrl uri; - QHash classes; - QHash properties; - }; -} -#endif - -#endif diff --git a/nepomuk/types/ontologyloader.cpp b/nepomuk/types/ontologyloader.cpp deleted file mode 100644 index 89f4d5ca..00000000 --- a/nepomuk/types/ontologyloader.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "ontologyloader.h" - -class Nepomuk::OntologyLoader::Private -{ -}; - -Nepomuk::OntologyLoader::OntologyLoader() - :d( new Private() ) -{ -} - - -Nepomuk::OntologyLoader::~OntologyLoader() -{ - delete d; -} diff --git a/nepomuk/types/ontologyloader.h b/nepomuk/types/ontologyloader.h deleted file mode 100644 index 3c1233e9..00000000 --- a/nepomuk/types/ontologyloader.h +++ /dev/null @@ -1,60 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_ONTOLOGY_LOADER_H_ -#define _NEPOMUK_ONTOLOGY_LOADER_H_ - -#include - -#include "nepomuk_export.h" - -namespace Soprano { - class Statement; -} - -namespace Nepomuk { - - /** - * An OntologyLoader provides the statements that make up an ontology - * for the OntologyManager to create the ontology classes and properties. - * - * Typical implementations read RDF statements from RDF files or from the - * Nepomuk-KDE RDF store. - * - * \deprecated Ontologies should now be handled using the classes - * in the Nepomuk::Types namespace. - */ - class KDE_DEPRECATED NEPOMUK_EXPORT OntologyLoader - { - public: - virtual ~OntologyLoader(); - - // FIXME: use StatementIterator - virtual QList loadOntology( const QUrl& url ) = 0; - - protected: - OntologyLoader(); - - private: - class Private; - Private* const d; - }; -} - -#endif diff --git a/nepomuk/types/ontologymanager.cpp b/nepomuk/types/ontologymanager.cpp deleted file mode 100644 index 10d1031f..00000000 --- a/nepomuk/types/ontologymanager.cpp +++ /dev/null @@ -1,343 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "ontologymanager.h" -#include "nepomukontologyloader.h" -#include "desktopontologyloader.h" -#include "ontology.h" -#include "ontology_p.h" -#include "class_p.h" -#include "property_p.h" -#include "entity_p.h" -#include "global.h" - -#include -#include -#include - -#include - - -using namespace Soprano; - -class Nepomuk::OntologyManager::Private -{ -public: - Private( OntologyManager* manager ) - : userOntologyLoader( 0 ), - desktopOntologyLoader( 0 ), - nepomukOntologyLoader( 0 ), - m_manager( manager ) { - } - - OntologyLoader* userOntologyLoader; - DesktopOntologyLoader* desktopOntologyLoader; - NepomukOntologyLoader* nepomukOntologyLoader; - - // cache - QHash ontoCache; - QHash classCache; - QHash propertyCache; - - /** - * Find a class in the cache. - * - * \param recurse if true the method will try loading dependancies (i.e. - * other ontologies to fulfill the requirement - */ - Class* findClass( const QUrl& uri, bool recurse = false ) { - QHash::iterator it = classCache.find( uri ); - if ( it != classCache.end() ) { - return &it.value(); - } - else { - if ( recurse ) { - // try loading the ontology containing the class - QUrl parentNs = extractNamespace( uri ); - if ( m_manager->getOntology( parentNs ) ) { - return findClass( uri ); - } - } - return 0; - } - } - - /** - * Find a property in the cache. - * - * \param recurse if true the method will try loading dependancies (i.e. - * other ontologies to fulfill the requirement - */ - Property* findProperty( const QUrl& uri, bool recurse = false ) { - QHash::iterator it = propertyCache.find( uri ); - if ( it != propertyCache.end() ) { - return &it.value(); - } - else { - if ( recurse ) { - // try loading the ontology containing the property - QUrl parentNs = extractNamespace( uri ); - if ( m_manager->getOntology( parentNs ) ) { - return findProperty( uri ); - } - } - return 0; - } - } - -private: - OntologyManager* m_manager; -}; - - -Nepomuk::OntologyManager* Nepomuk::OntologyManager::instance() -{ - static OntologyManager* s_instance = 0; - if ( !s_instance ) { - s_instance = new OntologyManager(); - } - - return s_instance; -} - - -Nepomuk::OntologyManager::OntologyManager() - : d( new Private( this ) ) -{ -} - - -Nepomuk::OntologyManager::~OntologyManager() -{ - delete d->userOntologyLoader; - delete d->desktopOntologyLoader; - delete d->nepomukOntologyLoader; - delete d; -} - - -void Nepomuk::OntologyManager::setOntologyLoader( OntologyLoader* loader ) -{ - if ( d->userOntologyLoader != loader ) { - delete d->userOntologyLoader; - } - d->userOntologyLoader = loader; -} - - -const Nepomuk::Ontology* Nepomuk::OntologyManager::getOntology( const QUrl& uri ) -{ - // if the ontology is already in the cache return it - // - QHash::const_iterator it = d->ontoCache.constFind( uri ); - if ( it != d->ontoCache.constEnd() ) { - return &it.value(); - } - - // if not in the cache, try loading it - // - else { - QList sl; - if ( !d->userOntologyLoader ) { - if ( !d->desktopOntologyLoader ) { - d->desktopOntologyLoader = new DesktopOntologyLoader(); - } - if ( !d->nepomukOntologyLoader ) { - d->nepomukOntologyLoader = new NepomukOntologyLoader(); - } - - // we prefer the NepomukOntologyLoader since it does not parse - // anything - sl = d->nepomukOntologyLoader->loadOntology( uri ); - if ( sl.isEmpty() ) { - sl = d->desktopOntologyLoader->loadOntology( uri ); - } - } - else { - sl = d->userOntologyLoader->loadOntology( uri ); - } - - if ( !sl.isEmpty() ) { - qDebug() << "(Nepomuk::OntologyManager) Found ontology " << uri << endl; - return constructOntology( uri, sl ); - } - else { - // loading failed, i.e. ontology not stored. - // - qDebug() << "(Nepomuk::OntologyManager) Could not find ontology " << uri << endl; - return 0; - } - } -} - - -Nepomuk::Ontology* Nepomuk::OntologyManager::constructOntology( const QUrl& ontoUri, const QList& sl ) -{ - Ontology& ont = d->ontoCache[ ontoUri ]; - ont.d->uri = ontoUri; - - // FIXME: Is it possible to define classes and properties with different namespaces in one file? - // Should we check the namespaces of the resources and if necessary create multiple Ontology - // instances? - - // step 1: collect all classes and properties - for ( QList::const_iterator it = sl.constBegin(); it != sl.constEnd(); ++it ) { - const Statement& s = *it; - QUrl subjectUri( s.subject().uri() ); - if( s.predicate().uri().toString().endsWith( "#type" ) ) { - if ( s.object().uri().toString().endsWith( "#Class" ) ) { - d->classCache.insert( subjectUri, Class() ); - Class* c = &d->classCache[ subjectUri ]; - Entity* entity = static_cast( c ); - entity->d->uri = subjectUri; - entity->d->ontology = &ont; - ont.d->classes.insert( subjectUri, c ); - } - else if ( s.object().uri().toString().endsWith( "#Property" ) ) { - d->propertyCache.insert( subjectUri, Property() ); - Property* p = &d->propertyCache[ subjectUri ]; - Entity* entity = static_cast( p ); - entity->d->uri = subjectUri; - entity->d->ontology = &ont; - ont.d->properties.insert( subjectUri, p ); - } - else { - qDebug() << "(OntologyManager) unknown type in ontology: " << s.object().uri(); - } - } - } - - // step 2: construct the classes and properties - for ( QList::const_iterator it = sl.constBegin(); it != sl.constEnd(); ++it ) { - const Statement& s = *it; - - // build the objects in the cache. If the ontology references another ontology try loading that one - // BIG PROBLEM: reverse dependancies of ontologies. - // If one ontology depends on another one which in turn depends on the first one. It should work - // since the first step already went through and thus, the class and property bodies have been created. - - const QUrl& subjectUri = s.subject().uri(); - Class* currentClass = d->findClass( subjectUri ); - Property* currentProperty = ( currentClass ? ( Property* )0 : d->findProperty( subjectUri ) ); - Entity* currentEntity = currentClass; - if ( !currentEntity ) { - currentEntity = currentProperty; - } - - if ( !currentClass && !currentProperty ) { - qDebug() << "(OntologyManager) invalid ontology statement: " << s; - d->ontoCache.remove( ontoUri ); - return 0; - } - - if( s.predicate().uri().toString().endsWith( "#subClassOf" ) ) { - Class* parent = d->findClass( s.object().uri(), true ); - if ( !parent ) { - qDebug() << "(OntologyManager) unable to load dependancy for: " << s; - } - else { - currentClass->d->parents.append( parent ); - parent->d->children.append( currentClass ); - } - } - - if( s.predicate().uri().toString().endsWith( "#subPropertyOf" ) ) { - Property* parent = d->findProperty( s.object().uri(), true ); - if ( !parent ) { - qDebug() << "(OntologyManager) unable to load dependancy for: " << s; - } - else { - currentProperty->d->parents.append( parent ); - parent->d->children.append( currentProperty ); - } - } - - else if( s.predicate().toString().endsWith( "#domain" ) ) { - Class* domain = d->findClass( s.object().uri(), true ); - if ( !domain ) { - qDebug() << "(OntologyManager) unable to load dependancy for: " << s; - } - else { - currentProperty->d->domain = domain; - domain->d->domainOf.insert( subjectUri, currentProperty ); - } - } - - else if( s.predicate().toString().endsWith( "#range" ) ) { - if ( s.object().toString().startsWith( Soprano::Vocabulary::XMLSchema::xsdNamespace().toString() ) ) { - currentProperty->d->literalRange = Literal( s.object().literal().toString() ); - } - else { - Class* range = d->findClass( s.object().uri(), true ); - if ( range ) { - currentProperty->d->range = range; - range->d->rangeOf.insert( subjectUri, currentProperty ); - } - else { - qDebug() << "(OntologyManager) unable to load dependancy for: " << s; - } - } - } - - else if( s.predicate().toString().endsWith( "#minCardinality" ) ) { - currentProperty->d->minCardinality = s.object().literal().toInt(); - } - - else if( s.predicate().toString().endsWith( "#maxCardinality" ) ) { - currentProperty->d->maxCardinality = s.object().literal().toInt(); - } - - else if ( s.predicate().toString().endsWith( "#cardinality" ) ) { - currentProperty->d->cardinality = s.object().literal().toInt(); - } - - else if ( s.predicate().toString().endsWith( "#inverseProperty" ) ) { - Property* inverse = d->findProperty( s.object().toString(), true ); - if ( !inverse ) { - qDebug() << "(OntologyManager) failed to load inverse property: " << s; - d->ontoCache.remove( ontoUri ); - return 0; - } - currentProperty->d->inverse = inverse; - inverse->d->inverse = currentProperty; - } - - // load l10n'ed comments - else if( s.predicate() == Soprano::Vocabulary::RDFS::comment() ) { - if ( s.object().language().isEmpty() ) { - currentEntity->d->comment = s.object().toString(); - } - else { - currentEntity->d->l10nComments[s.object().language()] = s.object().toString(); - } - } - - // load l10n'ed labels - else if( s.predicate() == Soprano::Vocabulary::RDFS::label() ) { - if ( s.object().language().isEmpty() ) { - currentEntity->d->label = s.object().toString(); - } - else { - currentEntity->d->l10nLabels[s.object().language()] = s.object().toString(); - } - } - } - - return &ont; -} diff --git a/nepomuk/types/ontologymanager.h b/nepomuk/types/ontologymanager.h deleted file mode 100644 index 955a3871..00000000 --- a/nepomuk/types/ontologymanager.h +++ /dev/null @@ -1,99 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_ONTOLOGY_MANAGER_H_ -#define _NEPOMUK_ONTOLOGY_MANAGER_H_ - -#include - -#include "nepomuk_export.h" - -namespace Soprano { - class Statement; -} - -namespace Nepomuk { - - class OntologyLoader; - class Ontology; - - /** - * The OntologyManager is the central ontology cache handler. - * It is modeled as a singleton and its instance can be accessed - * through OntologyManager::instance. - * - * \deprecated Ontologies should be handled via the classes in - * Nepomuk::Types. - */ - class KDE_DEPRECATED NEPOMUK_EXPORT OntologyManager - { - public: - ~OntologyManager(); - - static OntologyManager* instance(); - - /** - * Set an OntologyLoader to be used to retrieve - * the RDF statements that make up an ontology. - * - * By default Nepomuk uses a combination of the - * NepomukOntologyLoader and DesktopOntologyLoader - * where the NepomukOntologyLoader is the preferred - * one, i.e. only if it is not able to load the - * ontology DesktopOntologyLoader is used as a fallback. - * - * If an OntologyLoader is set no fallback loader will - * be used. Thus, to force one of the default loaders - * (for example the DesktopOntologyLoader) just do: - * - * \code - * OntologyManager::instance()->setOntologyLoader( new DesktopOntologyLoader() ); - * \endcode - * - * OntologyManager will take over ownership of loader. - * - * Overwriting the loader will delete any loader previously - * set via setOntologyLoader. - */ - void setOntologyLoader( OntologyLoader* loader ); - - /** - * Attempt to load the ontology referenced by uri. - * If the manager already has the ontology in the cache - * it is simply returned. Otherwise the manager tries - * to load the ontology from one of the configured - * OntologyLoader instances. - * - * \return The requested ontology or 0 in case it could - * not be found, i.e. none of the OntologyLoader instances - * could provide the RDF statements making up the ontology. - */ - const Ontology* getOntology( const QUrl& uri ); - - private: - OntologyManager(); - - Ontology* constructOntology( const QUrl& uri, const QList& sl ); - - class Private; - Private* const d; - }; -} - -#endif diff --git a/nepomuk/types/property.cpp b/nepomuk/types/property.cpp deleted file mode 100644 index 06daf3c3..00000000 --- a/nepomuk/types/property.cpp +++ /dev/null @@ -1,565 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "property.h" -#include "property_p.h" -#include "class.h" -#include "ontology.h" -#include "literal.h" -#include "entitymanager.h" - -#include -#include -#include - -#undef D -#define D static_cast( d.data() ) - -Nepomuk::Types::PropertyPrivate::PropertyPrivate( const QUrl& uri ) - : EntityPrivate( uri ), - minCardinality( -1 ), - maxCardinality( -1 ), - cardinality( -1 ) -{ -} - - -bool Nepomuk::Types::PropertyPrivate::addProperty( const QUrl& property, const Soprano::Node& value ) -{ - // we avoid subclassing loops (as created for crappy inferencing) by checking for our own uri - if( value.isResource() && - value.uri() != uri && - property == Soprano::Vocabulary::RDFS::subPropertyOf() ) { - parents.append( value.uri() ); - return true; - } - - else if( property == Soprano::Vocabulary::RDFS::domain() ) { - domain = value.uri(); - return true; - } - - else if( property == Soprano::Vocabulary::RDFS::range() ) { - if ( value.toString().startsWith( Soprano::Vocabulary::XMLSchema::xsdNamespace().toString() ) ) { - literalRange = Literal( value.uri() ); - } - else if ( value.uri() == Soprano::Vocabulary::RDFS::Literal()) { - literalRange = Literal( value.uri() ); - } - else { - range = value.uri(); - } - return true; - } - - else if( property == Soprano::Vocabulary::NRL::minCardinality() ) { - minCardinality = value.literal().toInt(); - return true; - } - - else if( property == Soprano::Vocabulary::NRL::maxCardinality() ) { - maxCardinality = value.literal().toInt(); - return true; - } - - else if ( property == Soprano::Vocabulary::NRL::cardinality() ) { - cardinality = value.literal().toInt(); - return true; - } - - else if ( property == Soprano::Vocabulary::NRL::inverseProperty() ) { - inverse = value.uri(); - return true; - } - - return false; -} - - -bool Nepomuk::Types::PropertyPrivate::addAncestorProperty( const QUrl& ancestorResource, const QUrl& property ) -{ - // we avoid subclassing loops (as created for crappy inferencing) by checking for our own uri - if( property == Soprano::Vocabulary::RDFS::subPropertyOf() && - ancestorResource != uri ) { - children.append( ancestorResource ); - return true; - } - else if ( property == Soprano::Vocabulary::NRL::inverseProperty() ) { - inverse = ancestorResource; - return true; - } - - return false; -} - - -void Nepomuk::Types::PropertyPrivate::reset( bool recursive ) -{ - QMutexLocker lock( &mutex ); - - if ( available != -1 ) { - if ( recursive ) { - range.reset( true ); - domain.reset( true ); - inverse.reset( true ); - foreach( Property p, parents ) { - p.reset( true ); - } - } - - parents.clear(); - available = -1; - } - - if ( ancestorsAvailable != -1 ) { - if ( recursive ) { - foreach( Property p, children ) { - p.reset( true ); - } - } - - children.clear(); - ancestorsAvailable = -1; - } - - EntityPrivate::reset( recursive ); -} - - - -Nepomuk::Types::Property::Property() - : Entity() -{ - d = 0; -} - - -Nepomuk::Types::Property::Property( const QUrl& uri ) - : Entity() -{ - d = EntityManager::self()->getProperty( uri ); -} - - -Nepomuk::Types::Property::Property( const Property& other ) - : Entity( other ) -{ -} - - -Nepomuk::Types::Property::~Property() -{ -} - - -Nepomuk::Types::Property& Nepomuk::Types::Property::operator=( const Property& other ) -{ - d = other.d; - return *this; -} - - -QList Nepomuk::Types::Property::parentProperties() -{ - if ( d ) { - D->init(); - return D->parents; - } - else { - return QList(); - } -} - - -QList Nepomuk::Types::Property::parentProperties() const -{ - return const_cast(this)->parentProperties(); -} - - -QList Nepomuk::Types::Property::subProperties() -{ - if ( d ) { - D->initAncestors(); - return D->children; - } - else { - return QList(); - } -} - - -QList Nepomuk::Types::Property::subProperties() const -{ - return const_cast(this)->subProperties(); -} - - -Nepomuk::Types::Property Nepomuk::Types::Property::inverseProperty() -{ - if ( d ) { - D->init(); - D->initAncestors(); - return D->inverse; - } - else { - return Property(); - } -} - - -Nepomuk::Types::Property Nepomuk::Types::Property::inverseProperty() const -{ - return const_cast(this)->inverseProperty(); -} - - -Nepomuk::Types::Class Nepomuk::Types::Property::range() -{ - if ( d ) { - D->init(); - - if( D->range.isValid() ) { - return D->range; - } - else if( !literalRangeType().isValid() ) { - // try getting a domain from one of the parent properties - for( int i = 0; i < D->parents.count(); ++i ) { - Class pr = D->parents[i].range(); - if( pr.isValid() ) { - return pr; - } - } - - // if we have no literal range type, we fall back to rdfs:Resource - return Class( Soprano::Vocabulary::RDFS::Resource() ); - } - else { - // other than domain() we do not use a general fallback since the range - // might be a literalRangeType() - return Class(); - } - } - else { - return Class(); - } -} - - -Nepomuk::Types::Class Nepomuk::Types::Property::range() const -{ - return const_cast(this)->range(); -} - - -Nepomuk::Types::Literal Nepomuk::Types::Property::literalRangeType() -{ - if ( d ) { - D->init(); - - if( D->literalRange.isValid() ) { - return D->literalRange; - } - else { - // try getting a domain from one of the parent properties - // We cannot check the resource range here since that would - // result in an endless loop - for( int i = 0; i < D->parents.count(); ++i ) { - Literal pr = D->parents[i].literalRangeType(); - if( pr.isValid() ) { - return pr; - } - } - - // fallback is an invalid range which will then result in - // range() returning a valid one - return Literal(); - } - } - else { - return Literal(); - } -} - - -Nepomuk::Types::Literal Nepomuk::Types::Property::literalRangeType() const -{ - return const_cast(this)->literalRangeType(); -} - - -Nepomuk::Types::Class Nepomuk::Types::Property::domain() -{ - if ( d ) { - D->init(); - - if( D->domain.isValid() ) { - return D->domain; - } - else { - // try getting a domain from one of the parent properties - for( int i = 0; i < D->parents.count(); ++i ) { - Class pd = D->parents[i].domain(); - if( pd.isValid() ) { - return pd; - } - } - - // fallback: rdfs:Resource - return Class( Soprano::Vocabulary::RDFS::Resource() ); - } - } - else { - return Class(); - } -} - - -Nepomuk::Types::Class Nepomuk::Types::Property::domain() const -{ - return const_cast(this)->domain(); -} - - -int Nepomuk::Types::Property::cardinality() -{ - if ( d ) { - D->init(); - return D->cardinality; - } - else { - return -1; - } -} - - -int Nepomuk::Types::Property::cardinality() const -{ - return const_cast(this)->cardinality(); -} - - -int Nepomuk::Types::Property::minCardinality() -{ - if ( d ) { - D->init(); - if ( D->minCardinality > 0 ) { - return D->minCardinality; - } - else { - return D->cardinality; - } - } - else { - return -1; - } -} - - -int Nepomuk::Types::Property::minCardinality() const -{ - return const_cast(this)->minCardinality(); -} - - -int Nepomuk::Types::Property::maxCardinality() -{ - if ( d ) { - D->init(); - if ( D->maxCardinality > 0 ) { - return D->maxCardinality; - } - else { - return D->cardinality; - } - } - else { - return -1; - } -} - - -int Nepomuk::Types::Property::maxCardinality() const -{ - return const_cast(this)->maxCardinality(); -} - - -bool Nepomuk::Types::Property::isParentOf( const Property& other ) -{ - if ( d ) { - D->initAncestors(); - - if ( D->children.contains( other ) ) { - return true; - } - else { - for ( QList::iterator it = D->children.begin(); - it != D->children.end(); ++it ) { - if ( ( *it ).isParentOf( other ) ) { - return true; - } - } - } - } - - return false; -} - - -bool Nepomuk::Types::Property::isParentOf( const Property& other ) const -{ - return const_cast(this)->isParentOf( other ); -} - - -bool Nepomuk::Types::Property::isSubPropertyOf( const Property& other ) -{ - if ( d ) { - D->init(); - - if ( D->parents.contains( other ) ) { - return true; - } - else { - for ( QList::iterator it = D->parents.begin(); - it != D->parents.end(); ++it ) { - if ( ( *it ).isSubPropertyOf( other ) ) { - return true; - } - } - } - } - - return false; -} - - -bool Nepomuk::Types::Property::isSubPropertyOf( const Property& other ) const -{ - return const_cast(this)->isSubPropertyOf( other ); -} - - - -#ifndef DISABLE_NEPOMUK_LEGACY - -// Start of code for deprecated Property -// ------------------------------------- -#include "global.h" -#include "ontologymanager.h" - -Nepomuk::Property::Property() - : Entity() -{ - d = new Private(); -} - - -Nepomuk::Property::Property( const Property& other ) - : Entity( other ) -{ - d = other.d; -} - - -Nepomuk::Property::~Property() -{ -} - - -Nepomuk::Property& Nepomuk::Property::operator=( const Property& other ) -{ - d = other.d; - return *this; -} - - -QList Nepomuk::Property::parentProperties() const -{ - return d->parents; -} - - -QList Nepomuk::Property::parentOf() const -{ - return d->children; -} - - -const Nepomuk::Property* Nepomuk::Property::inverseProperty() const -{ - return d->inverse; -} - - -const Nepomuk::Class* Nepomuk::Property::range() const -{ - return d->range; -} - - -Nepomuk::Literal Nepomuk::Property::literalRangeType() const -{ - return d->literalRange; -} - - -const Nepomuk::Class* Nepomuk::Property::domain() const -{ - return d->domain; -} - - -int Nepomuk::Property::cardinality() const -{ - return d->cardinality; -} - - -int Nepomuk::Property::minCardinality() const -{ - return d->minCardinality; -} - - -int Nepomuk::Property::maxCardinality() const -{ - return d->maxCardinality; -} - - -const Nepomuk::Property* Nepomuk::Property::load( const QUrl& uri ) -{ - QUrl ns = extractNamespace( uri ); - - // load the ontology in the cache - const Ontology* ont = OntologyManager::instance()->getOntology( ns ); - - // return the requested class or an invalid one if the ontology - // was not found - if ( ont ) { - return ont->findPropertyByUri( uri ); - } - else { - return 0; - } -} - -#endif // DISABLE_NEPOMUK_LEGACY diff --git a/nepomuk/types/property.h b/nepomuk/types/property.h deleted file mode 100644 index 907177fc..00000000 --- a/nepomuk/types/property.h +++ /dev/null @@ -1,428 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_PROPERTY_H_ -#define _NEPOMUK_PROPERTY_H_ - -#include -#include -#include -#include -#include - -#include "entity.h" -#include "nepomuk_export.h" - -namespace Nepomuk { - namespace Types { - - class Class; - class Literal; - - /** - * \class Property property.h Nepomuk/Types/Property - * - * \brief A property is a resource of type rdf:Property which relates a domain - * with a range. The latter one can be a Literal or a Class. - * - * Property instances are explicitly shared. Two instances created - * with the same uri reference the same data. - * - * While Resource objects can be changed Property instances are considered - * to be static and never changed during their lifetime. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT Property : public Entity - { - public: - /** - * Default constructor. Creates an empty Property. - */ - Property(); - - /** - * Create the property referred to by \p uri. - * The result is either a valid property which could be loaded from the - * Nepomuk store or a simple property which only contains the uri. - * - * Be aware that the data is only loaded once read. - * - * Subsequent calls result in a simple hash lookup of cached data. - */ - Property( const QUrl& uri ); - - /** - * Default copy constructor - */ - Property( const Property& ); - - /** - * Destructor - */ - ~Property(); - - /** - * Copy operator. - */ - Property& operator=( const Property& ); - - /** - * Each property can have multiple parent properties. - * \return A list of all parent properties of this property. - * If the list is emppty it means that the property has no direct - * parents, i.e. it is derived from rdf:Resource. - */ - QList parentProperties(); - - /** - * Each property can have multiple parent properties. - * \return A list of all parent properties of this property. - * If the list is emppty it means that the property has no direct - * parents, i.e. it is derived from rdf:Resource. - * - * Const version - * - * \since 4.4 - */ - QList parentProperties() const; - - /** - * \return A list of all properties that have this property as a parent. - * Be aware that this list can never be final since other ontologies - * that have not been loaded yet may contain properties that are derived - * from this property. - */ - QList subProperties(); - - /** - * \return A list of all properties that have this property as a parent. - * Be aware that this list can never be final since other ontologies - * that have not been loaded yet may contain properties that are derived - * from this property. - * - * Const version - * - * \since 4.4 - */ - QList subProperties() const; - - /** - * The inverse property (nrl:inverseProperty). - * \return A Property instance representing the inverse property of this one - * or 0 if none was specified in the ontology. - */ - Property inverseProperty(); - - /** - * The inverse property (nrl:inverseProperty). - * \return A Property instance representing the inverse property of this one - * or 0 if none was specified in the ontology. - * - * Const version - * - * \since 4.4 - */ - Property inverseProperty() const; - - /** - * The range of the property. - * \return The range of the property or an invalid Class in case - * the range of this poperty is a literal. - * \sa literalRange - */ - Class range(); - - /** - * The range of the property. - * \return The range of the property or an invalid Class in case - * the range of this poperty is a literal. - * \sa literalRange - * - * Const version - * - * \since 4.4 - */ - Class range() const; - - /** - * If the rage of this property is a literal (i.e. range returns an invalid Class) - * this method provides the literal type. - * - * \returns the literal type of this property or an empty, invalid Literal - * if the range is a Class. - * - * \sa range - */ - Literal literalRangeType(); - - /** - * If the rage of this property is a literal (i.e. range returns an invalid Class) - * this method provides the literal type. - * - * \returns the literal type of this property or an empty, invalid Literal - * if the range is a Class. - * - * \sa range - * - * Const version - * - * \since 4.4 - */ - Literal literalRangeType() const; - - /** - * The domain of the property. - */ - Class domain(); - - /** - * The domain of the property. - * - * Const version - * - * \since 4.4 - */ - Class domain() const; - - /** - * The cardinality of this property as specified by nrl:cardinality. - * - * \return the cardinality of the property or -1 if none was set. - */ - int cardinality(); - - /** - * The cardinality of this property as specified by nrl:cardinality. - * - * \return the cardinality of the property or -1 if none was set. - * - * Const version - * - * \since 4.4 - */ - int cardinality() const; - - /** - * The minimum cardinality of this property as specified by nrl:minCardinality. - * - * \return the minimum cardinality of the property or -1 if none was set. - */ - int minCardinality(); - - /** - * The minimum cardinality of this property as specified by nrl:minCardinality. - * - * \return the minimum cardinality of the property or -1 if none was set. - * - * Const version - * - * \since 4.4 - */ - int minCardinality() const; - - /** - * The maximum cardinality of this property as specified by nrl:maxCardinality. - * - * \return the maximum cardinality of the property or -1 if none was set. - */ - int maxCardinality(); - - /** - * The maximum cardinality of this property as specified by nrl:maxCardinality. - * - * \return the maximum cardinality of the property or -1 if none was set. - * - * Const version - * - * \since 4.4 - */ - int maxCardinality() const; - - /** - * Check if a property inherits this property. This is a recursive method which - * does not only check direct child propertyes. - * - * \return true if other is derived from this property, false otherwise. - */ - bool isParentOf( const Property& other ); - - /** - * Check if a property inherits this property. This is a recursive method which - * does not only check direct child propertyes. - * - * \return true if other is derived from this property, false otherwise. - * - * Const version - * - * \since 4.4 - */ - bool isParentOf( const Property& other ) const; - - /** - * Check if this property is derived from another property. This is a recursive method which - * does not only check direct child propertyes. - * - * \return true if this property is derived from other, false otherwise. - */ - bool isSubPropertyOf( const Property& other ); - - /** - * Check if this property is derived from another property. This is a recursive method which - * does not only check direct child propertyes. - * - * \return true if this property is derived from other, false otherwise. - * - * Const version - * - * \since 4.4 - */ - bool isSubPropertyOf( const Property& other ) const; - }; - } -} - - -#ifndef DISABLE_NEPOMUK_LEGACY - -namespace Nepomuk { - - class Ontology; - class Class; - class Literal; - - /** - * A property is a resource of type rdf:Property which relates a domain - * with a range. The latter one can be a literal in addition to a Class. - * - * \deprecated in favor of Nepomuk::Types::Property - */ - class KDE_DEPRECATED NEPOMUK_EXPORT Property : public Entity - { - public: - /** - * Default constructor. Creates an empty Property. - */ - Property(); - - /** - * Default copy constructor - */ - Property( const Property& ); - - /** - * Destructor - */ - ~Property(); - - Property& operator=( const Property& ); - - /** - * Each property can have multiple parent properties. - * \return A list of all parent properties of this property. - * If the list is emppty it means that the property has no direct - * parents, i.e. it is derived from rdf:Resource. - */ - QList parentProperties() const; - - /** - * \return A list of all properties that have this property as a parent. - * Be aware that this list can never be final since other ontologies - * that have not been loaded yet may contain properties that are derived - * from this property. - */ - QList parentOf() const; - - /** - * The inverse property (nrl:inverseProperty). - * \return A Property instance representing the inverse property of this one - * or 0 if none was specified in the ontology. - */ - const Property* inverseProperty() const; - - /** - * The range of the property. - * \return The range of the property or an invalid Class in case - * the range of this poperty is a literal. - * \sa literalRange - */ - const Class* range() const; - - /** - * If the rage of this property is a literal (i.e. range returns 0) - * this method provides the literal type. - * - * \returns the literal type of this property or an empty, invalid Literal - * if the range is a Class. - * - * \sa range - */ - Literal literalRangeType() const; - - /** - * The domain of the property. - */ - const Class* domain() const; - - /** - * The cardinality of this property as specified by nrl:cardinality. - * - * \return the cardinality of the property or -1 if none was set. - */ - int cardinality() const; - - /** - * The minimum cardinality of this property as specified by nrl:minCardinality. - * - * \return the minimum cardinality of the property or -1 if none was set. - */ - int minCardinality() const; - - /** - * The maximum cardinality of this property as specified by nrl:maxCardinality. - * - * \return the maximum cardinality of the property or -1 if none was set. - */ - int maxCardinality() const; - - // QString unit() const; - - /** - * Loads a property actually including the whole ontology - * it is declared in. - * - * Dependancies are resolved automatically if possible. - * - * \return A property object representing the property identified - * by uri or an invalid Property object if the resource identified - * by uri is either not a property or does not exist. - */ - static const Property* load( const QUrl& uri ); - - private: - class Private; - QSharedDataPointer d; - - friend class OntologyManager; - }; -} - -#endif // DISABLE_NEPOMUK_LEGACY - -#endif // _NEPOMUK_PROPERTY_H_ diff --git a/nepomuk/types/property_p.h b/nepomuk/types/property_p.h deleted file mode 100644 index 4689ebd5..00000000 --- a/nepomuk/types/property_p.h +++ /dev/null @@ -1,95 +0,0 @@ -/* This file is part of the Nepomuk-KDE libraries - Copyright (c) 2007 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef _NEPOMUK_PROPERTY_PRIVATE_H_ -#define _NEPOMUK_PROPERTY_PRIVATE_H_ - -#include "entity_p.h" -#include "property.h" -#include "literal.h" -#include "class.h" - -#include -#include - -namespace Nepomuk { - namespace Types { - class PropertyPrivate : public EntityPrivate - { - public: - PropertyPrivate( const QUrl& uri = QUrl() ); - - Class range; - Class domain; - - Literal literalRange; - - Property inverse; - - QList parents; - QList children; - - int minCardinality; - int maxCardinality; - int cardinality; - - bool addProperty( const QUrl& property, const Soprano::Node& value ); - bool addAncestorProperty( const QUrl& ancestorResource, const QUrl& property ); - - void reset( bool recursive ); - }; - } -} - - -#ifndef DISABLE_NEPOMUK_LEGACY -namespace Nepomuk { - - class Class; - - class Property::Private : public QSharedData - { - public: - Private() - : range( 0 ), - domain( 0 ), - inverse( 0 ), - minCardinality( -1 ), - maxCardinality( -1 ), - cardinality( -1 ) { - } - - const Class* range; - const Class* domain; - - Literal literalRange; - - const Property* inverse; - - QList parents; - QList children; - - int minCardinality; - int maxCardinality; - int cardinality; - }; -} -#endif - -#endif diff --git a/nepomuk/ui/kblocklayout.cpp b/nepomuk/ui/kblocklayout.cpp deleted file mode 100644 index 09d39d18..00000000 --- a/nepomuk/ui/kblocklayout.cpp +++ /dev/null @@ -1,272 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -/* - KBlockLayout is based on the FlowLayout example from QT4. - Copyright (C) 2004-2006 Trolltech ASA. All rights reserved. - Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). - All rights reserved. - Contact: Nokia Corporation (qt-info@nokia.com) -*/ - -#include "kblocklayout.h" - -#include -#include -#include - -class KBlockLayout::Private -{ -public: - Private() - : alignment(Qt::AlignLeft|Qt::AlignTop) { - } - - int smartSpacing(QStyle::PixelMetric pm) const - { - QObject *parent = q->parent(); - if (!parent) { - return -1; - } else if (parent->isWidgetType()) { - QWidget *pw = static_cast(parent); - return pw->style()->pixelMetric(pm, 0, pw); - } else { - return static_cast(parent)->spacing(); - } - } - - QList itemList; - - int m_hSpace; - int m_vSpace; - - Qt::Alignment alignment; - - KBlockLayout* q; -}; - - -KBlockLayout::KBlockLayout( QWidget* parent, int margin, int hSpacing, int vSpacing ) - : QLayout(parent), - d( new Private() ) -{ - d->q = this; - setMargin(margin); - setSpacing(hSpacing, vSpacing); -} - -KBlockLayout::KBlockLayout( int margin, int hSpacing, int vSpacing ) - : d( new Private() ) -{ - d->q = this; - setMargin(margin); - setSpacing(hSpacing, vSpacing); -} - -KBlockLayout::~KBlockLayout() -{ - QLayoutItem* item; - while ((item = takeAt(0))) - delete item; - delete d; -} - -void KBlockLayout::setAlignment( Qt::Alignment a ) -{ - d->alignment = a; -} - -Qt::Alignment KBlockLayout::alignment() const -{ - return d->alignment; -} - -int KBlockLayout::horizontalSpacing() const -{ - if (d->m_hSpace >= 0) { - return d->m_hSpace; - } else { - return d->smartSpacing(QStyle::PM_LayoutHorizontalSpacing); - } -} - -int KBlockLayout::verticalSpacing() const -{ - if (d->m_vSpace >= 0) { - return d->m_vSpace; - } else { - return d->smartSpacing(QStyle::PM_LayoutVerticalSpacing); - } -} - -void KBlockLayout::setSpacing( int h, int v ) -{ - d->m_hSpace = h; - d->m_vSpace = v; - QLayout::setSpacing( h ); -} - -void KBlockLayout::addItem( QLayoutItem* item ) -{ - d->itemList.append(item); -} - -int KBlockLayout::count() const -{ - return d->itemList.size(); -} - -QLayoutItem *KBlockLayout::itemAt( int index ) const -{ - return d->itemList.value(index); -} - -QLayoutItem *KBlockLayout::takeAt( int index ) -{ - if (index >= 0 && index < d->itemList.size()) - return d->itemList.takeAt(index); - else - return 0; -} - -Qt::Orientations KBlockLayout::expandingDirections() const -{ - return 0; -} - -bool KBlockLayout::hasHeightForWidth() const -{ - return true; -} - -int KBlockLayout::heightForWidth( int width ) const -{ - int height = doLayout(QRect(0, 0, width, 0), true); - return height; -} - -void KBlockLayout::setGeometry( const QRect& rect ) -{ - QLayout::setGeometry(rect); - doLayout(rect, false); -} - -QSize KBlockLayout::sizeHint() const -{ - // TODO: try to get the items into a square - QSize size; - QLayoutItem *item; - foreach (item, d->itemList) { - const QSize itemSize = item->minimumSize(); - size.rwidth() += itemSize.width(); - if (itemSize.height() > size.height()) { - size.setHeight(itemSize.height()); - } - } - - size.rwidth() += horizontalSpacing() * d->itemList.count(); - size += QSize(2*margin(), 2*margin()); - return size; -} - -QSize KBlockLayout::minimumSize() const -{ - QSize size; - QLayoutItem *item; - foreach (item, d->itemList) { - size = size.expandedTo(item->minimumSize()); - } - - size += QSize(2*margin(), 2*margin()); - return size; -} - -struct Row { - Row( const QList& i, int h, int w ) - : items(i), height(h), width(w) { - } - - QList items; - int height; - int width; -}; - -int KBlockLayout::doLayout( const QRect& rect, bool testOnly ) const -{ - int x = rect.x(); - int y = rect.y(); - int lineHeight = 0; - - // 1. calculate lines - QList rows; - QList rowItems; - for( int i = 0; i < d->itemList.count(); ++i ) { - QLayoutItem* item = d->itemList[i]; - int nextX = x + item->sizeHint().width() + horizontalSpacing(); - if (nextX - horizontalSpacing() > rect.right() && lineHeight > 0) { - rows.append( Row( rowItems, lineHeight, x - horizontalSpacing() ) ); - rowItems.clear(); - - x = rect.x(); - y = y + lineHeight + verticalSpacing(); - nextX = x + item->sizeHint().width() + horizontalSpacing(); - lineHeight = 0; - } - - rowItems.append( item ); - - x = nextX; - lineHeight = qMax(lineHeight, item->sizeHint().height()); - } - // append the last row - rows.append( Row( rowItems, lineHeight, x-horizontalSpacing() ) ); - - int finalHeight = y + lineHeight - rect.y(); - if( testOnly ) - return finalHeight; - - // 2. place the items - y = rect.y(); - foreach( const Row &row, rows ) { - x = rect.x(); - if( alignment() & Qt::AlignRight ) - x += (rect.width() - row.width); - else if( alignment() & Qt::AlignHCenter ) - x += (rect.width() - row.width)/2; - - foreach( QLayoutItem* item, row.items ) { - int yy = y; - if( alignment() & Qt::AlignBottom ) - yy += (row.height - item->sizeHint().height()); - else if( alignment() & Qt::AlignVCenter ) - yy += (row.height - item->sizeHint().height())/2; - item->setGeometry(QRect(QPoint(x, yy), item->sizeHint())); - - x += item->sizeHint().width() + horizontalSpacing(); - - if( alignment() & Qt::AlignJustify ) - x += (rect.width() - row.width)/qMax(row.items.count()-1,1); - } - - y = y + row.height + verticalSpacing(); - } - - return finalHeight; -} diff --git a/nepomuk/ui/kblocklayout.h b/nepomuk/ui/kblocklayout.h deleted file mode 100644 index 5281d8a7..00000000 --- a/nepomuk/ui/kblocklayout.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -/* - KBlockLayout is based on the FlowLayout example from QT4. - Copyright (C) 2004-2006 Trolltech ASA. All rights reserved. -*/ - -#ifndef KBLOCKLAYOUT_H -#define KBLOCKLAYOUT_H - -#include -#include - -/** - * The KBlockLayout arranges widget in rows and columns like a text - * editor does. - */ -class KBlockLayout : public QLayout -{ - public: - explicit KBlockLayout( QWidget *parent, int margin = 0, int hSpacing = -1, int vSpacing = -1 ); - KBlockLayout( int margin = 0, int hSpacing = -1, int vSpacing = -1 ); - ~KBlockLayout(); - - /** - * Set the alignment to use. It can be a combination of a horizontal and - * a vertical alignment flag. The vertical flag is used to arrange widgets - * that do not fill the complete height of a row. - * - * The default alignment is Qt::AlignLeft|Qt::AlignTop - */ - void setAlignment( Qt::Alignment ); - Qt::Alignment alignment() const; - - int horizontalSpacing() const; - int verticalSpacing() const; - - void setSpacing( int h, int v ); - - void addItem( QLayoutItem* item ); - Qt::Orientations expandingDirections() const; - bool hasHeightForWidth() const; - int heightForWidth(int) const; - int count() const; - QLayoutItem* itemAt( int index ) const; - QSize minimumSize() const; - void setGeometry( const QRect& rect ); - QSize sizeHint() const; - QLayoutItem* takeAt( int index ); - - private: - int doLayout( const QRect& rect, bool testOnly ) const; - - class Private; - Private* const d; -}; - -#endif diff --git a/nepomuk/ui/kedittagsdialog.cpp b/nepomuk/ui/kedittagsdialog.cpp deleted file mode 100644 index e7c9addd..00000000 --- a/nepomuk/ui/kedittagsdialog.cpp +++ /dev/null @@ -1,280 +0,0 @@ -/***************************************************************************** - * Copyright (C) 2009 by Peter Penz * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License version 2 as published by the Free Software Foundation. * - * * - * This library 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 * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public License * - * along with this library; see the file COPYING.LIB. If not, write to * - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * - * Boston, MA 02110-1301, USA. * - *****************************************************************************/ - -#include "kedittagsdialog_p.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -KEditTagsDialog::KEditTagsDialog(const QList& tags, - QWidget* parent, - Qt::WindowFlags flags) : - KDialog(parent, flags), - m_tags(tags), - m_tagsList(0), - m_newTagItem(0), - m_autoCheckedItem(0), - m_deleteCandidate(0), - m_newTagEdit(0), - m_deleteButtonTimer(0) -{ - - const QString caption = (tags.count() > 0) ? - i18nc("@title:window", "Change Tags") : - i18nc("@title:window", "Add Tags"); - setCaption(caption); - setButtons(KDialog::Ok | KDialog::Cancel); - setDefaultButton(KDialog::Ok); - - QWidget* mainWidget = new QWidget(this); - QVBoxLayout* topLayout = new QVBoxLayout(mainWidget); - - QLabel* label = new QLabel(i18nc("@label:textbox", - "Configure which tags should " - "be applied."), this); - - m_tagsList = new QListWidget(mainWidget); - m_tagsList->setMouseTracking(true); - m_tagsList->setSortingEnabled(true); - m_tagsList->setSelectionMode(QAbstractItemView::NoSelection); - m_tagsList->installEventFilter(this); - connect(m_tagsList, SIGNAL(itemEntered(QListWidgetItem*)), - this, SLOT(slotItemEntered(QListWidgetItem*))); - - QLabel* newTagLabel = new QLabel(i18nc("@label", "Create new tag:")); - m_newTagEdit = new KLineEdit(this); - m_newTagEdit->setClearButtonShown(true); - connect(m_newTagEdit, SIGNAL(textEdited(QString)), - this, SLOT(slotTextEdited(QString))); - - QHBoxLayout* newTagLayout = new QHBoxLayout(); - newTagLayout->addWidget(newTagLabel); - newTagLayout->addWidget(m_newTagEdit, 1); - - topLayout->addWidget(label); - topLayout->addWidget(m_tagsList); - topLayout->addLayout(newTagLayout); - - setMainWidget(mainWidget); - - loadTags(); - - // create the delete button, which is shown when - // hovering the items - m_deleteButton = new QPushButton(m_tagsList->viewport()); - m_deleteButton->setIcon(KIcon("edit-delete")); - m_deleteButton->setToolTip(i18nc("@info", "Delete tag")); - m_deleteButton->hide(); - connect(m_deleteButton, SIGNAL(clicked()), this, SLOT(deleteTag())); - - m_deleteButtonTimer = new QTimer(this); - m_deleteButtonTimer->setSingleShot(true); - m_deleteButtonTimer->setInterval(500); - connect(m_deleteButtonTimer, SIGNAL(timeout()), this, SLOT(showDeleteButton())); -} - -KEditTagsDialog::~KEditTagsDialog() -{ -} - -QList KEditTagsDialog::tags() const -{ - return m_tags; -} - -bool KEditTagsDialog::eventFilter(QObject* watched, QEvent* event) -{ - if ((watched == m_tagsList) && (event->type() == QEvent::Leave)) { - m_deleteButtonTimer->stop(); - m_deleteButton->hide(); - } - return KDialog::eventFilter(watched, event); -} - -void KEditTagsDialog::slotButtonClicked(int button) -{ - if (button == KDialog::Ok) { - // update m_tags with the checked values, so - // that the caller of the KEditTagsDialog can - // receive the tags by KEditTagsDialog::tags() - m_tags.clear(); - - const int count = m_tagsList->count(); - for (int i = 0; i < count; ++i) { - QListWidgetItem* item = m_tagsList->item(i); - if (item->checkState() == Qt::Checked) { - const QUrl uri = item->data(Qt::UserRole).toUrl(); - if( uri.isEmpty() ) { - Nepomuk::Tag tag( item->text() ); - tag.setLabel( item->text() ); - m_tags.append( tag ); - } - else { - m_tags.append( Nepomuk::Tag(uri) ); - } - } - } - - accept(); - } else { - KDialog::slotButtonClicked(button); - } -} - -void KEditTagsDialog::slotTextEdited(const QString& text) -{ - // Remove unnecessary spaces from a new tag is - // mandatory, as the user cannot see the difference - // between a tag "Test" and "Test ". - const QString tagText = text.simplified(); - if (tagText.isEmpty()) { - removeNewTagItem(); - return; - } - - // Check whether the new tag already exists. If this - // is the case, remove the new tag item. - const int count = m_tagsList->count(); - for (int i = 0; i < count; ++i) { - QListWidgetItem* item = m_tagsList->item(i); - const bool remove = (item->text() == tagText) && - ((m_newTagItem == 0) || (m_newTagItem != item)); - if (remove) { - m_tagsList->scrollToItem(item); - if (item->checkState() == Qt::Unchecked) { - item->setCheckState(Qt::Checked); - // Remember the checked item, so that it can be unchecked - // again if the user changes the tag-text. - m_autoCheckedItem = item; - } - removeNewTagItem(); - return; - } - } - - // There is no tag in the list with the the passed text. - if (m_newTagItem == 0) { - m_newTagItem = new QListWidgetItem(tagText, m_tagsList); - } else { - m_newTagItem->setText(tagText); - } - - if (m_autoCheckedItem != 0) { - m_autoCheckedItem->setCheckState(Qt::Unchecked); - m_autoCheckedItem = 0; - } - - m_newTagItem->setData(Qt::UserRole, QUrl()); - m_newTagItem->setCheckState(Qt::Checked); - m_tagsList->scrollToItem(m_newTagItem); -} - -void KEditTagsDialog::slotItemEntered(QListWidgetItem* item) -{ - // align the delete-button to stay on the right border - // of the item - const QRect rect = m_tagsList->visualItemRect(item); - const int size = rect.height(); - const int x = rect.right() - size; - const int y = rect.top(); - m_deleteButton->setGeometry(x, y, size, size); - - m_deleteCandidate = item; - m_deleteButtonTimer->start(); -} - -void KEditTagsDialog::showDeleteButton() -{ - m_deleteButton->show(); -} - -void KEditTagsDialog::deleteTag() -{ - Q_ASSERT(m_deleteCandidate != 0); - const QString text = i18nc("@info", - "Should the tag %1 really be deleted for all files?", - m_deleteCandidate->text()); - const QString caption = i18nc("@title", "Delete tag"); - const KGuiItem deleteItem(i18nc("@action:button", "Delete"), KIcon("edit-delete")); - const KGuiItem cancelItem(i18nc("@action:button", "Cancel"), KIcon("dialog-cancel")); - if (KMessageBox::warningYesNo(this, text, caption, deleteItem, cancelItem) == KMessageBox::Yes) { - int row = m_tagsList->row( m_deleteCandidate ); - - const QUrl uri = m_deleteCandidate->data(Qt::UserRole).toUrl(); - Nepomuk::Tag tag(uri); - tag.remove(); - - delete m_deleteCandidate; - m_deleteCandidate = 0; - - // Give the delete Candidate an appropriate value. - // This is required cause when the mouse button doesn't move at all then m_deleteCandidate - // stays 0 and clicking on the delete button executes deleteTag() which then asserts. - if( row == m_tagsList->count() ) - row = m_tagsList->count() - 1; - - // The deleteCandidate is now the next item in the row - m_deleteCandidate = m_tagsList->item( row ); - } -} - -static bool tagLabelLessThan( const Nepomuk::Tag& t1, const Nepomuk::Tag& t2 ) -{ - return t1.genericLabel() < t2.genericLabel(); -} - -void KEditTagsDialog::loadTags() -{ - // load all available tags and mark those tags as checked - // that have been passed to the KEditTagsDialog - QList tags = Nepomuk::Tag::allTags(); - qSort( tags.begin(), tags.end(), tagLabelLessThan ); - - foreach (const Nepomuk::Tag& tag, tags) { - const QString label = tag.genericLabel(); - - QListWidgetItem* item = new QListWidgetItem(label, m_tagsList); - item->setData(Qt::UserRole, tag.resourceUri()); - - const bool check = m_tags.contains( tag ); - item->setCheckState(check ? Qt::Checked : Qt::Unchecked); - } -} - -void KEditTagsDialog::removeNewTagItem() -{ - if (m_newTagItem != 0) { - const int row = m_tagsList->row(m_newTagItem); - m_tagsList->takeItem(row); - delete m_newTagItem; - m_newTagItem = 0; - } -} - -#include "kedittagsdialog_p.moc" diff --git a/nepomuk/ui/kedittagsdialog_p.h b/nepomuk/ui/kedittagsdialog_p.h deleted file mode 100644 index 542cbda1..00000000 --- a/nepomuk/ui/kedittagsdialog_p.h +++ /dev/null @@ -1,79 +0,0 @@ -/***************************************************************************** - * Copyright (C) 2009 by Peter Penz * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License version 2 as published by the Free Software Foundation. * - * * - * This library 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 * - * Library General Public License for more details. * - * * - * You should have received a copy of the GNU Library General Public License * - * along with this library; see the file COPYING.LIB. If not, write to * - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * - * Boston, MA 02110-1301, USA. * - *****************************************************************************/ - -#ifndef KEDIT_TAGS_DIALOG_H -#define KEDIT_TAGS_DIALOG_H - -#include -#include - -class KLineEdit; -class QListWidget; -class QListWidgetItem; -class QPushButton; -class QTimer; - -/** - * @brief Dialog to edit a list of Nepomuk tags. - * - * It is possible for the user to add existing tags, - * create new tags or to remove tags. - * - * @see KMetaDataConfigurationDialog - */ -class KEditTagsDialog : public KDialog -{ - Q_OBJECT - -public: - KEditTagsDialog(const QList& tags, - QWidget* parent = 0, - Qt::WindowFlags flags = 0); - - virtual ~KEditTagsDialog(); - - QList tags() const; - - virtual bool eventFilter(QObject* watched, QEvent* event); - -protected slots: - virtual void slotButtonClicked(int button); - -private slots: - void slotTextEdited(const QString& text); - void slotItemEntered(QListWidgetItem* item); - void showDeleteButton(); - void deleteTag(); - -private: - void loadTags(); - void removeNewTagItem(); - -private: - QList m_tags; - QListWidget* m_tagsList; - QListWidgetItem* m_newTagItem; - QListWidgetItem* m_autoCheckedItem; - QListWidgetItem* m_deleteCandidate; - KLineEdit* m_newTagEdit; - - QPushButton* m_deleteButton; - QTimer* m_deleteButtonTimer; -}; - -#endif diff --git a/nepomuk/ui/kmetadatatagcloud.cpp b/nepomuk/ui/kmetadatatagcloud.cpp deleted file mode 100644 index 414b297a..00000000 --- a/nepomuk/ui/kmetadatatagcloud.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "kmetadatatagcloud.h" -#include "resourcemanager.h" - -#include "tag.h" - -#include - -#include - - -class Nepomuk::TagCloud::Private -{ -public: - Private() - : autoUpdate(false) { - } - QTimer* updateTimer; - bool autoUpdate; -}; - - -Nepomuk::TagCloud::TagCloud( QWidget* parent ) - : KTagCloudWidget( parent ), - d( new Private() ) -{ - updateTags(); - setAutoUpdate( true ); -} - - -Nepomuk::TagCloud::~TagCloud() -{ - delete d; -} - - -bool Nepomuk::TagCloud::autoUpdate() const -{ - return d->autoUpdate; -} - - -void Nepomuk::TagCloud::updateTags() -{ - // clear the tag cloud - clear(); - - // retrieve the list of all tags - QList tags = Tag::allTags(); - - // count the number of usages of the tags and add them to the cloud - for( QList::iterator it = tags.begin(); - it != tags.end(); ++it ) { - Tag& tag = *it; - if ( tag.label().isEmpty() ) { - tag.setLabel( tag.genericLabel() ); - } - addTag( tag.label(), tag.tagOf().count() ); - } -} - - -void Nepomuk::TagCloud::setAutoUpdate( bool enable ) -{ - if ( enable != d->autoUpdate ) { - if( !enable ) { - disconnect( ResourceManager::instance()->mainModel(), SIGNAL(statementsAdded()), - this, SLOT(updateTags()) ); - disconnect( ResourceManager::instance()->mainModel(), SIGNAL(statementsRemoved()), - this, SLOT(updateTags()) ); - } - else { - connect( ResourceManager::instance()->mainModel(), SIGNAL(statementsAdded()), - this, SLOT(updateTags()) ); - connect( ResourceManager::instance()->mainModel(), SIGNAL(statementsRemoved()), - this, SLOT(updateTags()) ); - } - - d->autoUpdate = enable; - } -} - - -void Nepomuk::TagCloud::slotTagClicked( const QString& tag ) -{ - emit tagClicked( Tag(tag) ); -} - -#include "kmetadatatagcloud.moc" diff --git a/nepomuk/ui/kmetadatatagcloud.h b/nepomuk/ui/kmetadatatagcloud.h deleted file mode 100644 index 6621d521..00000000 --- a/nepomuk/ui/kmetadatatagcloud.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KMETADATATAGCLOUD_H -#define KMETADATATAGCLOUD_H - -#include - -#include "ktagcloudwidget.h" - -namespace Nepomuk { - class Tag; - - /** - * Tag cloud widget that displays all tags stored in the - * local Nepomuk store. - */ - class NEPOMUK_EXPORT TagCloud : public KTagCloudWidget - { - Q_OBJECT - - public: - /** - * Create a new TagCloud widget. - * The widget will be populated immediately. - */ - TagCloud( QWidget* parent = 0 ); - ~TagCloud(); - - /** - * \return true if auto updating is enabled (the default). - * - * \sa setAutoUpdate - */ - bool autoUpdate() const; - - public Q_SLOTS: - /** - * Update the tag cloud, ie. reload all tags from the store - * and recalculate their importance. - * - * There is no need to call this unless auto updating is - * disabled. - * - * \sa setAutoUpdate - */ - void updateTags(); - - /** - * If auto updating is enabled the tag cloud is updated - * regularly to keep in sync with the local Nepomuk store. - * - * \sa updateTags - */ - void setAutoUpdate( bool enable ); - - Q_SIGNALS: - /** - * This signal is emitted whenever a tag is clicked. - * - * \sa KTagCloudWidget::tagClicked - */ - void tagClicked( Tag ); - - private Q_SLOTS: - void slotTagClicked( const QString& tag ); - - private: - class Private; - Private* const d; - }; -} - -#endif // KMETADATATAGCLOUD_H diff --git a/nepomuk/ui/kmetadatatagwidget.h b/nepomuk/ui/kmetadatatagwidget.h deleted file mode 100644 index d96f8a68..00000000 --- a/nepomuk/ui/kmetadatatagwidget.h +++ /dev/null @@ -1,2 +0,0 @@ -// backwards compatibility -#include "tagwidget.h" diff --git a/nepomuk/ui/ktagcloudwidget.cpp b/nepomuk/ui/ktagcloudwidget.cpp deleted file mode 100644 index 23b70e6a..00000000 --- a/nepomuk/ui/ktagcloudwidget.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "ktagcloudwidget.h" -#include "kblocklayout.h" - -#include - -#include - - -class KTagCloudWidget::Private -{ -public: - Private() - : minFontSize(8), - maxFontSize(22) { - } - - QMap tagMap; - QMap labelMap; - QMap weightMap; - - KBlockLayout* mainLay; - - int minFontSize; - int maxFontSize; - - void buildWeightMap() { - weightMap.clear(); - - int max = 0; - int min = 0; - - // determine max - for( QMap::const_iterator it = tagMap.constBegin(); - it != tagMap.constEnd(); ++it ) { - max = qMax( max, it.value() ); - min = qMin( min, it.value() ); - } - - // normalize weights - for( QMap::const_iterator it = tagMap.constBegin(); - it != tagMap.constEnd(); ++it ) { - weightMap[it.key()] = (double)(it.value() - min) / (double)qMax(max - min, 1); - } - } - - KUrlLabel* createLabel( QWidget* parent, const QString& tag ) { - KUrlLabel* label = new KUrlLabel( tag, tag, parent ); - QFont font( label->font() ); - font.setPointSize( minFontSize + (int)((double)(maxFontSize-minFontSize)*weightMap[tag]) ); - if( weightMap[tag] > 0.8 ) - font.setBold( true ); - label->setFont( font ); - label->setUnderline(false); - return label; - } -}; - - -KTagCloudWidget::KTagCloudWidget( QWidget* parent ) - : QWidget( parent ), - d( new Private() ) -{ - d->mainLay = new KBlockLayout( this ); - d->mainLay->setAlignment( Qt::AlignJustify|Qt::AlignVCenter ); -} - - -KTagCloudWidget::~KTagCloudWidget() -{ - delete d; -} - - -void KTagCloudWidget::setMaxFontSize( int pointSize ) -{ - d->maxFontSize = pointSize; - buildTagCloud(); -} - - -void KTagCloudWidget::setMinFontSize( int pointSize ) -{ - d->minFontSize = pointSize; - buildTagCloud(); -} - - -int KTagCloudWidget::tagWeight( const QString& tag ) const -{ - return d->tagMap[tag]; -} - - -void KTagCloudWidget::addTag( const QString& tag, int weight ) -{ - d->tagMap[tag] = weight; - buildTagCloud(); -} - - -void KTagCloudWidget::addTags( const QMap& tags ) -{ - for( QMap::const_iterator it = tags.constBegin(); - it != tags.constEnd(); ++it ) - d->tagMap[it.key()] = it.value(); - buildTagCloud(); -} - - -void KTagCloudWidget::clear() -{ - d->tagMap.clear(); - buildTagCloud(); -} - - -void KTagCloudWidget::resizeEvent( QResizeEvent* e ) -{ - QWidget::resizeEvent( e ); -} - - -void KTagCloudWidget::buildTagCloud() -{ - // Brute force: delete all existing labels - for( QMap::iterator it = d->labelMap.begin(); - it != d->labelMap.end(); ++it ) - delete it.value(); - - d->labelMap.clear(); - - d->buildWeightMap(); - - // now rebuild the cloud - QStringList tags; - for( QMap::const_iterator it = d->tagMap.constBegin(); - it != d->tagMap.constEnd(); ++it ) { - tags.append( it.key() ); - d->labelMap[it.key()] = d->createLabel( this, it.key() ); - connect( d->labelMap[it.key()], SIGNAL(leftClickedUrl(QString)), - this, SIGNAL(tagClicked(QString)) ); - } - - // for now we display the tags sorted alphabetically - qSort( tags.begin(), tags.end() ); - - int x = 0; - foreach( const QString &tag, tags ) { - KUrlLabel* label = d->labelMap[tag]; - if( x + label->width() > width() ) { - // new line - x = 0; - } - d->mainLay->addWidget( label ); - x += label->width(); - } -} - -#include "ktagcloudwidget.moc" diff --git a/nepomuk/ui/ktagcloudwidget.h b/nepomuk/ui/ktagcloudwidget.h deleted file mode 100644 index d8b1f6d6..00000000 --- a/nepomuk/ui/ktagcloudwidget.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef KTAGCLOUDWIDGET_H -#define KTAGCLOUDWIDGET_H - -#include -#include - -#include - -class NEPOMUK_EXPORT KTagCloudWidget : public QWidget -{ - Q_OBJECT - - public: - KTagCloudWidget( QWidget* parent = 0 ); - ~KTagCloudWidget(); - - /** - * Retrieve the weight for a certain tag - */ - int tagWeight( const QString& tag ) const; - - public Q_SLOTS: - /** - * Add \a tag to the cloud using the weight factor \a weight. - * Existing tags with the same name will be overwritten. - */ - void addTag( const QString& tag, int weight ); - - /** - * Add a set of tags with weight factors - */ - void addTags( const QMap& tags ); - - /** - * Remove all tags from the cloud. - */ - void clear(); - - /** - * Set the maximum font size to be used for the most popular tags. - * Default is 22. - */ - void setMaxFontSize( int pointSize ); - - /** - * Set the minimum font size to be used for the most unpopular tags. - * Default is 8. - */ - void setMinFontSize( int pointSize ); - - Q_SIGNALS: - void tagClicked( const QString& tag ); - - protected: - void resizeEvent( QResizeEvent* e ); - - private: - void buildTagCloud(); - - class Private; - Private* const d; -}; - -#endif diff --git a/nepomuk/ui/ktagdisplaywidget.cpp b/nepomuk/ui/ktagdisplaywidget.cpp deleted file mode 100644 index f1159032..00000000 --- a/nepomuk/ui/ktagdisplaywidget.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "ktagdisplaywidget.h" - -#include - -#include - - -class KTagDisplayWidget::Private -{ -public: - Private( KTagDisplayWidget* _parent ) - : parent( _parent ) { - layout = new QHBoxLayout( parent ); - layout->setMargin( 0 ); - } - - void buildDisplay() { - // delete all the children - foreach( QWidget* w, wl ) - delete w; - wl.clear(); - - // remove the stretch we added in the last call - if ( QLayoutItem* item = layout->takeAt( 0 ) ) - delete item; - - // create new labels - for( QStringList::const_iterator it = tags.constBegin(); - it != tags.constEnd(); ++it ) { - if ( it != tags.constBegin() ) { - QLabel* label = new QLabel( "-", parent ); - wl.append( label ); - layout->addWidget( label ); // FIXME: display some nicer symbol like a big dot - } - KUrlLabel* label = new KUrlLabel( *it, *it, parent ); - wl.append( label ); - label->setUnderline( false ); - layout->addWidget( label ); - - connect( label, SIGNAL(leftClickedUrl(QString)), - parent, SIGNAL(tagClicked(QString)) ); - } - - layout->addStretch( 1 ); - } - - QStringList tags; - QList wl; - QHBoxLayout* layout; - -private: - KTagDisplayWidget* parent; -}; - - -KTagDisplayWidget::KTagDisplayWidget( QWidget* parent ) - : QWidget( parent ), - d( new Private( this ) ) -{ -} - - -KTagDisplayWidget::~KTagDisplayWidget() -{ - delete d; -} - - -void KTagDisplayWidget::setTags( const QStringList& tags ) -{ - d->tags = tags; - d->buildDisplay(); -} - - -void KTagDisplayWidget::addTag( const QString& tag ) -{ - if ( !d->tags.contains( tag ) ) - d->tags.append( tag ); - d->buildDisplay(); -} - - -void KTagDisplayWidget::addTags( const QStringList& tags ) -{ - foreach( const QString &tag, tags ) - if ( !d->tags.contains( tag ) ) - d->tags.append( tag ); - d->buildDisplay(); -} - - -void KTagDisplayWidget::clear() -{ - d->tags.clear(); - d->buildDisplay(); -} - -#include "ktagdisplaywidget.moc" diff --git a/nepomuk/ui/ktagdisplaywidget.h b/nepomuk/ui/ktagdisplaywidget.h deleted file mode 100644 index f3924496..00000000 --- a/nepomuk/ui/ktagdisplaywidget.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2007 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _KTAG_DISPLAY_WIDGET_H_ -#define _KTAG_DISPLAY_WIDGET_H_ - -#include - -#include - -/** - * The KTagDisplayWidget shows a list of tags and allows clicking each of them. - */ -class NEPOMUK_EXPORT KTagDisplayWidget : public QWidget -{ - Q_OBJECT - - public: - KTagDisplayWidget( QWidget* parent = 0 ); - ~KTagDisplayWidget(); - - public Q_SLOTS: - /** - * Set \a tags to be displayed. - */ - void setTags( const QStringList& tags ); - - /** - * Add \a tag to be displayed. - * Existing tags with the same name will be overwritten. - */ - void addTag( const QString& tag ); - - /** - * Add a set of tags to be displayed. - * Existing tags with the same name will be overwritten. - */ - void addTags( const QStringList& tags ); - - /** - * Remove all tags. - */ - void clear(); - - Q_SIGNALS: - void tagClicked( const QString& tag ); - - private: - class Private; - Private* const d; -}; - -#endif diff --git a/nepomuk/ui/nepomukmassupdatejob.cpp b/nepomuk/ui/nepomukmassupdatejob.cpp deleted file mode 100644 index 50756e6e..00000000 --- a/nepomuk/ui/nepomukmassupdatejob.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright 2008-2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "nepomukmassupdatejob.h" - -#include "klocale.h" -#include "kdebug.h" - -#include "tag.h" -#include "tools.h" - - -Nepomuk::MassUpdateJob::MassUpdateJob( QObject* parent ) - : KJob( parent ), - m_index( -1 ) -{ - kDebug(); - setCapabilities( Killable|Suspendable ); - connect( &m_processTimer, SIGNAL(timeout()), - this, SLOT(slotNext()) ); -} - - -Nepomuk::MassUpdateJob::~MassUpdateJob() -{ - kDebug(); -} - - -void Nepomuk::MassUpdateJob::setFiles( const KUrl::List& urls ) -{ - m_resources.clear(); - foreach( const KUrl &url, urls ) { - m_resources.append( Resource( url ) ); - } - setTotalAmount( KJob::Files, m_resources.count() ); -} - - -void Nepomuk::MassUpdateJob::setResources( const QList& rl ) -{ - m_resources = rl; - setTotalAmount( KJob::Files, m_resources.count() ); -} - - -void Nepomuk::MassUpdateJob::setProperties( const QList >& props ) -{ - m_properties = props; -} - - -void Nepomuk::MassUpdateJob::start() -{ - if ( m_index < 0 ) { - kDebug(); - emit description( this, - i18n("Changing annotations") ); - m_index = 0; - m_processTimer.start(); - } - else { - kDebug() << "Job has already been started"; - } -} - - -bool Nepomuk::MassUpdateJob::doKill() -{ - if ( m_index > 0 ) { - m_processTimer.stop(); - m_index = -1; - return true; - } - else { - return false; - } -} - - -bool Nepomuk::MassUpdateJob::doSuspend() -{ - m_processTimer.stop(); - return true; -} - - -bool Nepomuk::MassUpdateJob::doResume() -{ - if ( m_index > 0 ) { - m_processTimer.start(); - return true; - } - else { - return false; - } -} - - -void Nepomuk::MassUpdateJob::slotNext() -{ - if ( !isSuspended() ) { - if ( m_index < m_resources.count() ) { - Nepomuk::Resource& res = m_resources[m_index]; - for ( int i = 0; i < m_properties.count(); ++i ) { - res.setProperty( m_properties[i].first, m_properties[i].second ); - } - ++m_index; - setProcessedAmount( KJob::Files, m_index ); - } - else if ( m_index >= m_resources.count() ) { - kDebug() << "done"; - m_index = -1; - m_processTimer.stop(); - emitResult(); - } - } -} - - -Nepomuk::MassUpdateJob* Nepomuk::MassUpdateJob::tagResources( const QList& rl, const QList& tags ) -{ - Nepomuk::MassUpdateJob* job = new Nepomuk::MassUpdateJob(); - job->setResources( rl ); - job->setProperties( QList >() << qMakePair( QUrl( Nepomuk::Resource::tagUri() ), Nepomuk::Variant( convertResourceList( tags ) ) ) ); - return job; -} - - -Nepomuk::MassUpdateJob* Nepomuk::MassUpdateJob::rateResources( const QList& rl, int rating ) -{ - Nepomuk::MassUpdateJob* job = new Nepomuk::MassUpdateJob(); - job->setResources( rl ); - job->setProperties( QList >() << qMakePair( QUrl( Nepomuk::Resource::ratingUri() ), Nepomuk::Variant( rating ) ) ); - return job; -} - -Nepomuk::MassUpdateJob* Nepomuk::MassUpdateJob::commentResources( const QList& rl, const QString& comment ) -{ - Nepomuk::MassUpdateJob* job = new Nepomuk::MassUpdateJob(); - job->setResources( rl ); - job->setProperties( QList >() << qMakePair( QUrl( Nepomuk::Resource::descriptionUri() ), Nepomuk::Variant( comment ) ) ); - return job; -} - -#include "nepomukmassupdatejob.moc" diff --git a/nepomuk/ui/nepomukmassupdatejob.h b/nepomuk/ui/nepomukmassupdatejob.h deleted file mode 100644 index 67310aaf..00000000 --- a/nepomuk/ui/nepomukmassupdatejob.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright 2008-2009 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_MASS_UPDATE_JOB_H_ -#define _NEPOMUK_MASS_UPDATE_JOB_H_ - -#include "kjob.h" -#include "kurl.h" - -#include -#include -#include - -#include "resource.h" -#include "variant.h" - - -namespace Nepomuk { - /** - * \class MassUpdateJob nepomukmassupdatejob.h Nepomuk/MassUpdateJob - * - * \brief A KJob to set Nepomuk properties on a set of resources at once. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT MassUpdateJob : public KJob - { - Q_OBJECT - - public: - /** - * Default constructor. Normally there is no need to use this. - * Use tagResources(), rateResources(), or commentResources() - * instead. - */ - MassUpdateJob( QObject* parent = 0 ); - - /** - * Destructor - */ - ~MassUpdateJob(); - - /** - * Set a list of files to change - * This has the same effect as using setResources - * with a list of manually created resources. - */ - void setFiles( const KUrl::List& urls ); - - /** - * Set a list of resources to change. - */ - void setResources( const QList& ); - - /** - * Set the properties to change in the mass update. - */ - void setProperties( const QList >& props ); - - /** - * Actually start the job. - */ - void start(); - - static MassUpdateJob* tagResources( const QList&, const QList& tags ); - static MassUpdateJob* rateResources( const QList&, int rating ); - static MassUpdateJob* commentResources( const QList&, const QString& comment); - - protected: - bool doKill(); - bool doSuspend(); - bool doResume(); - - private Q_SLOTS: - void slotNext(); - - private: - QList m_resources; - QList > m_properties; - int m_index; - QTimer m_processTimer; - }; -} - -#endif diff --git a/nepomuk/ui/tagcheckbox.cpp b/nepomuk/ui/tagcheckbox.cpp deleted file mode 100644 index 6ff6411c..00000000 --- a/nepomuk/ui/tagcheckbox.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "tagcheckbox.h" -#include "tagwidget.h" -#include "tagwidget_p.h" - -#include -#include -#include - -#include -#include -#include -#include -#include - - -class Nepomuk::TagCheckBox::CheckBoxWithPublicInitStyleOption : public QCheckBox -{ -public: - CheckBoxWithPublicInitStyleOption( const QString& text, QWidget* parent ) - : QCheckBox( text, parent ) { - } - - void initStyleOption( QStyleOptionButton* so ) { - QCheckBox::initStyleOption( so ); - } -}; - - -Nepomuk::TagCheckBox::TagCheckBox( const Tag& tag, TagWidgetPrivate* tagWidget, QWidget* parent ) - : QWidget( parent ), - m_label(0), - m_checkBox(0), - m_tag(tag), - m_urlHover(false), - m_tagWidget(tagWidget) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setMargin(0); - if( tagWidget->m_flags & TagWidget::MiniMode ) { - m_label = new QLabel( tag.genericLabel(), this ); - m_label->setMouseTracking(true); - m_child = m_label; - } - else { - m_checkBox = new CheckBoxWithPublicInitStyleOption( tag.genericLabel(), this ); - m_child = m_checkBox; - connect(m_checkBox, SIGNAL(stateChanged(int)), this, SLOT(slotStateChanged(int))); - } - m_child->installEventFilter( this ); - m_child->setMouseTracking(true); - layout->addWidget( m_child ); -} - - -Nepomuk::TagCheckBox::~TagCheckBox() -{ -} - - -bool Nepomuk::TagCheckBox::isChecked() const -{ - if( m_checkBox ) - return m_checkBox->isChecked(); - else - return true; -} - - -void Nepomuk::TagCheckBox::setChecked( bool checked ) -{ - if( m_checkBox ) - m_checkBox->setChecked( checked ); -} - - -void Nepomuk::TagCheckBox::leaveEvent( QEvent* event ) -{ - QWidget::leaveEvent( event ); - enableUrlHover( false ); -} - - -bool Nepomuk::TagCheckBox::eventFilter( QObject* watched, QEvent* event ) -{ - if( watched == m_child ) { - switch( event->type() ) { - case QEvent::MouseMove: { - QMouseEvent* me = static_cast(event); - if( !(m_tagWidget->m_flags & TagWidget::DisableTagClicking) ) - enableUrlHover( tagRect().contains(me->pos()) ); - } - - case QEvent::MouseButtonRelease: { - QMouseEvent* me = static_cast(event); - if( !(m_tagWidget->m_flags & TagWidget::DisableTagClicking) && - me->button() == Qt::LeftButton && - tagRect().contains(me->pos()) ) { - emit tagClicked( m_tag ); - return true; - } - } - - default: - // do nothing - break; - } - } - - return QWidget::eventFilter( watched, event ); -} - - -void Nepomuk::TagCheckBox::slotStateChanged( int state ) -{ - emit tagStateChanged( m_tag, state ); -} - - -QRect Nepomuk::TagCheckBox::tagRect() const -{ - if( m_checkBox ) { - QStyleOptionButton opt; - m_checkBox->initStyleOption(&opt); - return style()->subElementRect(QStyle::SE_CheckBoxContents, - &opt, - m_checkBox); - } - else { - return QRect(QPoint(0, 0), m_label->size()); - } -} - - -void Nepomuk::TagCheckBox::enableUrlHover( bool enable ) -{ - if( m_urlHover != enable ) { - m_urlHover = enable; - QFont f = font(); - if(enable) - f.setUnderline(true); - m_child->setFont(f); - m_child->setCursor( enable ? Qt::PointingHandCursor : Qt::ArrowCursor ); - } -} - -#include "tagcheckbox.moc" diff --git a/nepomuk/ui/tagcheckbox.h b/nepomuk/ui/tagcheckbox.h deleted file mode 100644 index 3678281c..00000000 --- a/nepomuk/ui/tagcheckbox.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_TAG_CHECKBOX_H_ -#define _NEPOMUK_TAG_CHECKBOX_H_ - -#include - -#include "tag.h" -#include "tagwidget_p.h" - -class QMouseEvent; -class QLabel; - -namespace Nepomuk { -class TagCheckBox : public QWidget -{ - Q_OBJECT - -public: - TagCheckBox( const Tag& tag, TagWidgetPrivate* tagWidget, QWidget* parent = 0 ); - ~TagCheckBox(); - - Tag tag() const { return m_tag; } - - bool isChecked() const; - -public Q_SLOTS: - void setChecked( bool checked ); - -Q_SIGNALS: - void tagClicked( const Nepomuk::Tag& tag ); - void tagStateChanged( const Nepomuk::Tag& tag, int state ); - -protected: - void leaveEvent( QEvent* event ); - bool eventFilter( QObject* watched, QEvent* event ); - -private Q_SLOTS: - void slotStateChanged( int state ); - -private: - QRect tagRect() const; - void enableUrlHover( bool enabled ); - - // two modes: checkbox and simple label - QLabel* m_label; - class CheckBoxWithPublicInitStyleOption; - CheckBoxWithPublicInitStyleOption* m_checkBox; - QWidget* m_child; - - Tag m_tag; - bool m_urlHover; - TagWidgetPrivate* m_tagWidget; -}; -} - -#endif diff --git a/nepomuk/ui/tagwidget.cpp b/nepomuk/ui/tagwidget.cpp deleted file mode 100644 index b65b6457..00000000 --- a/nepomuk/ui/tagwidget.cpp +++ /dev/null @@ -1,409 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2010 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "tagwidget.h" -#include "tagwidget_p.h" -#include "kblocklayout.h" -#include "nepomukmassupdatejob.h" -#include "kedittagsdialog_p.h" -#include "tagcheckbox.h" - -#include "tools.h" -#include "tag.h" -#include "resourcemanager.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - - -void Nepomuk::TagWidgetPrivate::init( TagWidget* parent ) -{ - q = parent; - m_maxTags = 10; - m_flags = TagWidget::StandardMode; - m_blockSelectionChangedSignal = false; - m_showAllLinkLabel = 0; - m_editTagsDialog = 0; - - QGridLayout* mainLayout = new QGridLayout( q ); - mainLayout->setMargin(0); - m_flowLayout = new KBlockLayout( 0, KDialog::spacingHint()*3 ); - m_showAllButton = new QPushButton( i18nc("@label", "Show all tags..."), q ); - q->connect( m_showAllButton, SIGNAL(clicked()), SLOT(slotShowAll()) ); - mainLayout->addLayout( m_flowLayout, 0, 0, 1, 2 ); - mainLayout->addWidget( m_showAllButton, 1, 1, 1, 1 ); - mainLayout->setColumnStretch( 0, 1 ); - - rebuild(); -} - - -void Nepomuk::TagWidgetPrivate::rebuild() -{ - if( m_flags & TagWidget::MiniMode ) { - buildTagHash( q->selectedTags() ); - } - else { - QList tags = q->selectedTags(); - buildTagHash( loadTags( m_maxTags ) ); - selectTags( tags ); - } -} - - -void Nepomuk::TagWidgetPrivate::buildTagHash( const QList& tags ) -{ - qDeleteAll(m_checkBoxHash); - m_checkBoxHash.clear(); - - foreach( const Nepomuk::Tag& tag, tags ) { - getTagCheckBox( tag ); - } - - delete m_showAllLinkLabel; - m_showAllLinkLabel = 0; - - if( m_flags & TagWidget::MiniMode ) { - m_showAllButton->hide(); - if ( (m_flags&TagWidget::ReadOnly) && !tags.isEmpty() ) { - return; - } - - m_showAllLinkLabel = new QLabel( q ); - m_flowLayout->addWidget( m_showAllLinkLabel ); - if( m_flags&TagWidget::ReadOnly ) { - m_showAllLinkLabel->setText("-"); - } - else { - QFont f(q->font()); - f.setUnderline(true); - m_showAllLinkLabel->setFont(f); - m_showAllLinkLabel->setText( QLatin1String("") + - ( m_checkBoxHash.isEmpty() ? i18nc("@label", "Add Tags...") : i18nc("@label", "Change...") ) + - QLatin1String("") ); - q->connect( m_showAllLinkLabel, SIGNAL(linkActivated(QString)), SLOT(slotShowAll()) ); - } - } - else { - m_showAllButton->setShown( !(m_flags&TagWidget::ReadOnly) ); - } -} - - -QList Nepomuk::TagWidgetPrivate::loadTags( int max ) -{ - // get the "max" first tags with the most resources - QString query = QString::fromLatin1("select ?r count(distinct ?f) as ?c where { " - "?r a %1 . " - "?f %2 ?r . " - "} ORDER BY DESC(?c) LIMIT %3") - .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::Tag()), - Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag())) - .arg( max ); - QList tags; - Soprano::QueryResultIterator it = ResourceManager::instance()->mainModel()->executeQuery( query, Soprano::Query::QueryLanguageSparql ); - while( it.next() ) { - // workaround for bug in Virtuoso where resources are returned as strings if a count() is in the select clause - tags << Tag( KUrl(it["r"].toString()) ); - } - return tags; -} - - -QList Nepomuk::TagWidgetPrivate::intersectResourceTags() -{ - if ( m_resources.count() == 1 ) { - return m_resources.first().tags(); - } - else if ( !m_resources.isEmpty() ) { - // determine the tags used for all resources - QSet tags = QSet::fromList( m_resources.first().tags() ); - QList::const_iterator it = m_resources.constBegin(); - for ( ++it; it != m_resources.constEnd(); ++it ) { - tags.intersect( QSet::fromList( (*it).tags() ) ); - } - return tags.values(); - } - else { - return QList(); - } -} - - -Nepomuk::TagCheckBox* Nepomuk::TagWidgetPrivate::getTagCheckBox( const Tag& tag ) -{ - QMap::iterator it = m_checkBoxHash.find(tag); - if( it == m_checkBoxHash.end() ) { - kDebug() << "Creating checkbox for" << tag.genericLabel(); - TagCheckBox* checkBox = new TagCheckBox( tag, this, q ); - q->connect( checkBox, SIGNAL(tagClicked(Nepomuk::Tag)), SIGNAL(tagClicked(Nepomuk::Tag)) ); - q->connect( checkBox, SIGNAL(tagStateChanged(Nepomuk::Tag,int)), SLOT(slotTagStateChanged(Nepomuk::Tag,int)) ); - m_checkBoxHash.insert( tag, checkBox ); - m_flowLayout->addWidget( checkBox ); - return checkBox; - } - else { - return it.value(); - } -} - -namespace Nepomuk { -/// operator necessary for QMap::erase -bool operator<(const Tag& t1, const Tag& t2) { - return t1.resourceUri() < t2.resourceUri(); -} -} - -void Nepomuk::TagWidgetPrivate::selectTags( const QList& tags ) -{ - m_blockSelectionChangedSignal = true; - - if( m_flags & TagWidget::MiniMode ) { - buildTagHash( tags ); - } - else { - foreach( TagCheckBox* checkBox, m_checkBoxHash ) { - checkBox->setChecked( false ); - } - - foreach( const Tag& tag, tags ) { - getTagCheckBox(tag)->setChecked( true ); - } - - // remove the previously added check boxes which are not amongst - // the top 10 or remove as many check boxes as possible to get down to - // m_maxTags - if( !m_checkBoxHash.isEmpty() ) { - int r = qMax( m_checkBoxHash.count() - m_maxTags, 0 ); - QMap::iterator it = m_checkBoxHash.end(); - --it; - while( r > 0 ) { - - // stop the loop when we reach the beginning of the hash - bool end = ( it == m_checkBoxHash.begin() ); - - // remove unused checkboxes - if( !it.value()->isChecked() ) { - delete it.value(); - it = m_checkBoxHash.erase(it); - --r; - } - - if( end ) { - break; - } - else { - --it; - } - } - } - } - - m_blockSelectionChangedSignal = false; -} - - -void Nepomuk::TagWidgetPrivate::updateResources() -{ - if ( !m_resources.isEmpty() ) { - Nepomuk::MassUpdateJob* job = Nepomuk::MassUpdateJob::tagResources( m_resources, q->selectedTags() ); - q->connect( job, SIGNAL(result(KJob*)), - SLOT(slotTagUpdateDone()) ); - q->setEnabled( false ); // no updates during execution - job->start(); - } -} - - -Nepomuk::TagWidget::TagWidget( const Resource& resource, QWidget* parent ) - : QWidget( parent ), - d( new TagWidgetPrivate() ) -{ - d->init( this ); - setTaggedResource( resource ); -} - - -Nepomuk::TagWidget::TagWidget( QWidget* parent ) - : QWidget( parent ), - d( new TagWidgetPrivate() ) -{ - d->init( this ); -} - - -Nepomuk::TagWidget::~TagWidget() -{ - delete d; -} - - -QList Nepomuk::TagWidget::taggedResources() const -{ - return d->m_resources; -} - - -#ifndef KDE_NO_DEPRECATED -QList Nepomuk::TagWidget::assignedTags() const -{ - return selectedTags(); -} -#endif - - -QList Nepomuk::TagWidget::selectedTags() const -{ - QList tags; - QMapIterator it( d->m_checkBoxHash ); - while( it.hasNext() ) { - it.next(); - if( it.value()->isChecked() ) - tags << it.key(); - } - return tags; -} - - -int Nepomuk::TagWidget::maxTagsShown() const -{ - return d->m_maxTags; -} - - -Qt::Alignment Nepomuk::TagWidget::alignment() const -{ - return d->m_flowLayout->alignment(); -} - - -Nepomuk::TagWidget::ModeFlags Nepomuk::TagWidget::modeFlags() const -{ - return d->m_flags; -} - - -void Nepomuk::TagWidget::setTaggedResource( const Resource& resource ) -{ - QList l; - l.append( resource ); - setTaggedResources( l ); -} - - -void Nepomuk::TagWidget::setTaggedResources( const QList& resources ) -{ - // reset selection to a sensible default - d->buildTagHash( d->loadTags( d->m_maxTags ) ); - - d->m_resources = resources; - if ( !resources.isEmpty() ) { - d->selectTags( d->intersectResourceTags() ); - } - else { - d->selectTags( QList() ); - } -} - - -#ifndef KDE_NO_DEPRECATED -void Nepomuk::TagWidget::setAssignedTags( const QList& tags ) -{ - setSelectedTags( tags ); -} -#endif - - -void Nepomuk::TagWidget::setSelectedTags( const QList& tags ) -{ - d->selectTags( tags ); - d->updateResources(); -} - - -void Nepomuk::TagWidget::setMaxTagsShown( int max ) -{ - d->m_maxTags = max; - setTaggedResources( d->m_resources ); -} - - -void Nepomuk::TagWidget::setAlignment( Qt::Alignment alignment ) -{ - d->m_flowLayout->setAlignment( alignment ); -} - - -void Nepomuk::TagWidget::setModeFlags( ModeFlags flags ) -{ - d->m_flags = flags; - d->rebuild(); -} - - -void Nepomuk::TagWidget::slotTagUpdateDone() -{ - setEnabled( true ); -} - - -void Nepomuk::TagWidget::slotShowAll() -{ - d->m_editTagsDialog = new KEditTagsDialog( selectedTags(), this ); - d->m_editTagsDialog->setWindowModality( Qt::ApplicationModal ); - connect( d->m_editTagsDialog, SIGNAL(finished(int)), this, SLOT(slotKEditTagDialogFinished(int)) ); - d->m_editTagsDialog->open(); -} - -void Nepomuk::TagWidget::slotKEditTagDialogFinished(int result) -{ - if( result == QDialog::Accepted ) { - setSelectedTags( d->m_editTagsDialog->tags() ); - emit selectionChanged( selectedTags() ); - } - - d->m_editTagsDialog->deleteLater(); - d->m_editTagsDialog = 0; -} - - -void Nepomuk::TagWidget::slotTagStateChanged( const Nepomuk::Tag&, int ) -{ - if( !d->m_blockSelectionChangedSignal ) { - d->updateResources(); - emit selectionChanged( selectedTags() ); - } -} - -#include "tagwidget.moc" diff --git a/nepomuk/ui/tagwidget.h b/nepomuk/ui/tagwidget.h deleted file mode 100644 index a84b0636..00000000 --- a/nepomuk/ui/tagwidget.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2010 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_TAG_WIDGET_H_ -#define _NEPOMUK_TAG_WIDGET_H_ - -#include "nepomuk_export.h" - -#include - -namespace Nepomuk { - class Resource; - class Tag; - class TagWidgetPrivate; - - /** - * \class TagWidget tagwidget.h Nepomuk/TagWidget - * - * \brief Allows to change a selection of tags. - * - * TagWidget provides a simple GUI interface to assign tags. - * It has two basic modes: - * \li If resources are set via setTaggedResource() or setTaggedResources() - * the changes in the tag selection are automatically assigned to the - * selected resources. - * \li If no resources have been set the widget simply emits the selectionChanged() - * signal. - * - * \author Sebastian Trueg - */ - class NEPOMUK_EXPORT TagWidget : public QWidget - { - Q_OBJECT - - public: - /** - * Creates a new TagWidget for resource. The assigned tags are loaded - * instantly. - */ - explicit TagWidget( const Resource& resource, QWidget* parent = 0 ); - - /** - * Constructor - */ - TagWidget( QWidget* parent = 0 ); - - /** - * Destructor - */ - ~TagWidget(); - - /** - * \return The resources that are supposed to be tagged or an empty - * list if none have been set. - */ - QList taggedResources() const; - - /** - * \deprecated use selectedTags() instead - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED QList assignedTags() const; -#endif - - /** - * The list of selected tags. - * - * \return The list of all tags that are currently selected. In case - * resources to be tagged have been selected this list matches the - * tags assigned to the resources. - * - * \sa setTaggedResource, taggedResource, Resource::getTags - * - * \since 4.5 - */ - QList selectedTags() const; - - /** - * By default the TagWidget shows the most often used tags in the - * main window and allows access to all tags via an additional button. - * This is the maximum number of tags that should be shown unless they - * are selected. - * - * \sa setMaxTagsShown() - * - * \since 4.5 - */ - int maxTagsShown() const; - - /** - * The alignment of the tags in the widget. - * - * \since 4.5 - */ - Qt::Alignment alignment() const; - - /** - * Flags to configure the widget. - * - * \since 4.5 - */ - enum ModeFlag { - /** - * The mini mode which tries to - * display the tags on the least - * space possible. - */ - MiniMode = 0x1, - - /** - * The standard mode which is used by default - * provides a set of check boxes for the most - * frequently used tags. - */ - StandardMode = 0x2, - - /** - * Read only mode which prevents the changing - * of tags by the user. - */ - ReadOnly = 0x4, - - /** - * Disable the clicking of the tags. This will - * also disable the emitting of the tagClicked() - * signal. - */ - DisableTagClicking = 0x8 - }; - Q_DECLARE_FLAGS( ModeFlags, ModeFlag ) - - /** - * Flags the widget is configured with. - * - * \sa setModeFlags() - * - * \since 4.5 - */ - ModeFlags modeFlags() const; - - Q_SIGNALS: - /** - * This signal is emitted whenever a tag is clicked. - */ - void tagClicked( Nepomuk::Tag ); - - /** - * Emitted whenever the selection of tags changes. - * - * \since 4.5 - */ - void selectionChanged( const QList& tags ); - - public Q_SLOTS: - /** - * Set the Resource to be tagged. The assigned tags will be loaded - * instantly. - */ - void setTaggedResource( const Resource& resource ); - - /** - * Set the resources to be tagged. If the list of resources is - * empty TagWidget will only emit the selectionChanged() signal. - */ - void setTaggedResources( const QList& resources ); - - /** - * \deprecated use setSelectedTags() instead - */ -#ifndef KDE_NO_DEPRECATED - KDE_DEPRECATED void setAssignedTags( const QList& tags ); -#endif - - /** - * Set the list of selected tags. In case resources have been - * set via setTaggedResource() or setTaggedResources() their - * list of tags is changed automatically. - * - * \since 4.5 - */ - void setSelectedTags( const QList& tags ); - - /** - * By default the TagWidget shows the most often used tags in the - * main window and allows access to all tags via an additional button. - * - * The number of tags that are shown by default can be changed. - * - * \param max The maximum number of tags that should be shown in the - * main window. Set to 0 for no limit. Be aware that more tags might be - * shown since selected tags are always shown. - * - * \since 4.5 - */ - void setMaxTagsShown( int max ); - - /** - * Set the alignment to use. Only horizontal alignment flags make a - * difference. - * - * \since 4.5 - */ - void setAlignment( Qt::Alignment alignment ); - - /** - * Set flags to change the behaviour and look of the tag widget. - * - * \since 4.5 - */ - void setModeFlags( ModeFlags flags ); - - private Q_SLOTS: - void slotShowAll(); - void slotTagUpdateDone(); - void slotTagStateChanged( const Nepomuk::Tag&, int ); - void slotKEditTagDialogFinished( int result ); - - private: - TagWidgetPrivate* const d; - }; -} - -Q_DECLARE_OPERATORS_FOR_FLAGS( Nepomuk::TagWidget::ModeFlags ) - -#endif diff --git a/nepomuk/ui/tagwidget_p.h b/nepomuk/ui/tagwidget_p.h deleted file mode 100644 index 18ccb266..00000000 --- a/nepomuk/ui/tagwidget_p.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of the Nepomuk KDE project. - * Copyright (C) 2006-2010 Sebastian Trueg - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library 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 - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef _NEPOMUK_TAG_WIDGET_P_H_ -#define _NEPOMUK_TAG_WIDGET_P_H_ - -#include "tagwidget.h" -#include "tag.h" - -#include -#include - -class QPushButton; -class QLabel; -class KBlockLayout; -class KEditTagsDialog; - -namespace Nepomuk { - -class TagCheckBox; - -class TagWidgetPrivate -{ -public: - void init( TagWidget* parent ); - void rebuild(); - void buildTagHash( const QList& tags ); - QList loadTags( int max ); - QList intersectResourceTags(); - - /// lookup (and if necessary create) checkbox for tag - TagCheckBox* getTagCheckBox( const Tag& tag ); - - /// check the corresponding checkboxes and even - /// add missing checkboxes - void selectTags( const QList& tags ); - - /// start a massupdate job to set the selected tags on the resources - void updateResources(); - - QList m_resources; - int m_maxTags; - TagWidget::ModeFlags m_flags; - bool m_blockSelectionChangedSignal; - - QMap m_checkBoxHash; - QPushButton* m_showAllButton; - QLabel* m_showAllLinkLabel; - KBlockLayout* m_flowLayout; - TagWidget* q; - - KEditTagsDialog* m_editTagsDialog; -}; -} - -#endif diff --git a/nepomuk/utils/CMakeLists.txt b/nepomuk/utils/CMakeLists.txt deleted file mode 100644 index 8b02990c..00000000 --- a/nepomuk/utils/CMakeLists.txt +++ /dev/null @@ -1,64 +0,0 @@ -project(nepomuk_utils) - -add_definitions (${QT_DEFINITIONS} ${KDE4_DEFINITIONS}) -add_definitions(-DDISABLE_NEPOMUK_LEGACY=1) - -include_directories( - ${CMAKE_CURRENT_BINARY_DIR}/.. -) - -set(nepomukutils_SRCS - typefacet.cpp - utils.cpp - - facetdelegate.cpp - facetwidget.cpp - facetmodel.cpp - facetfiltermodel.cpp - facet.cpp - simplefacet.cpp - dynamicresourcefacet.cpp - datefacet.cpp - proxyfacet.cpp - - daterange.cpp - daterangeselectionwidget.cpp - - resourcemodel.cpp - simpleresourcemodel.cpp - searchlineedit.cpp - searchwidget.cpp -) - -kde4_add_ui_files(nepomukutils_SRCS daterangeselectionwidget.ui) - -kde4_add_library(nepomukutils ${LIBRARY_TYPE} ${nepomukutils_SRCS}) - -target_link_libraries(nepomukutils - ${SOPRANO_LIBRARIES} - ${QT_QTCORE_LIBRARY} - nepomuk - nepomukquery - kdecore -) - -set_target_properties(nepomukutils PROPERTIES - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) - -install(TARGETS nepomukutils EXPORT kdelibsLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS}) - -install(FILES - utils.h - facet.h - simplefacet.h - dynamicresourcefacet.h - proxyfacet.h - facetwidget.h - searchwidget.h - resourcemodel.h - simpleresourcemodel.h - nepomukutils_export.h - DESTINATION ${INCLUDE_INSTALL_DIR}/nepomuk COMPONENT Devel -) diff --git a/nepomuk/utils/datefacet.cpp b/nepomuk/utils/datefacet.cpp deleted file mode 100644 index 386aa00a..00000000 --- a/nepomuk/utils/datefacet.cpp +++ /dev/null @@ -1,420 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "datefacet.h" -#include "daterange.h" -#include "daterangeselectionwidget.h" - -#include "comparisonterm.h" -#include "orterm.h" -#include "andterm.h" -#include "literalterm.h" -#include "standardqueries.h" -#include "query.h" - -#include "nie.h" -#include "nuao.h" - -#include -#include -#include -#include - -#include "kglobal.h" -#include "klocale.h" -#include "kcalendarsystem.h" -#include "kguiitem.h" -#include "kdialog.h" -#include "kdebug.h" - - -class Nepomuk::Utils::DateFacet::Private -{ -public: - Private() - : m_currentRange( NoDateRange ) { - } - - /// only used for code simplification - QList m_rangeCandidates; - - DateRangeCandidates m_enabledRanges; - QList m_ranges; - - DateRangeCandidate m_currentRange; - DateRange m_customRange; - - void rebuild(); - - bool setCurrentRange( const DateRange& range ); - - QString titleForDateRangeCandidate( DateRangeCandidate range ) const; - DateRange dateRangeCandidateToDateRange( DateRangeCandidate range ) const; - - DateFacet* q; -}; - - -void Nepomuk::Utils::DateFacet::Private::rebuild() -{ - m_ranges.clear(); - Q_FOREACH( DateRangeCandidate r, m_rangeCandidates ) { - if ( m_enabledRanges&r ) { - m_ranges << r; - } - } - if ( !m_ranges.contains( m_currentRange ) ) { - q->clearSelection(); - } - q->setLayoutChanged(); -} - - -bool Nepomuk::Utils::DateFacet::Private::setCurrentRange( const DateRange& range ) -{ - kDebug() << range; - Q_FOREACH( DateRangeCandidate dr, m_ranges ) { - if ( dateRangeCandidateToDateRange( dr ) == range ) { - kDebug() << range << "is" << dr; - m_currentRange = dr; - q->setSelectionChanged(); - return true; - } - } - // not one of the candicates -> use it as custom one - if ( m_ranges.contains( CustomDateRange ) ) { - m_currentRange = CustomDateRange; - m_customRange = range; - q->setSelectionChanged(); - return true; - } - else { - return false; - } -} - - -QString Nepomuk::Utils::DateFacet::Private::titleForDateRangeCandidate( DateRangeCandidate range ) const -{ - switch( range ) { - case Anytime: - return i18nc( "referring to a filter on the modification and usage date of files/resources", "Anytime" ); - case Today: - return i18nc( "referring to a filter on the modification and usage date of files/resources", "Today" ); - case Yesterday: - return i18nc( "referring to a filter on the modification and usage date of files/resources", "Yesterday" ); - case ThisWeek: - return i18nc( "referring to a filter on the modification and usage date of files/resources", "This Week" ); - case LastWeek: - return i18nc( "referring to a filter on the modification and usage date of files/resources", "Last Week" ); - case ThisMonth: - return i18nc( "referring to a filter on the modification and usage date of files/resources", "This Month" ); - case LastMonth: - return i18nc( "referring to a filter on the modification and usage date of files/resources", "Last Month" ); - case ThisYear: - return i18nc( "referring to a filter on the modification and usage date of files/resources", "This Year" ); - case LastYear: - return i18nc( "referring to a filter on the modification and usage date of files/resources", "Last Year" ); - case CustomDateRange: - return i18nc( "referring to a filter on the modification and usage date of files/resources that will open a dialog to choose a date range", "Custom..." ); - default: - return QString(); - } - - // shut up gcc - return QString(); -} - - -DateRange Nepomuk::Utils::DateFacet::Private::dateRangeCandidateToDateRange( DateRangeCandidate range ) const -{ - const QDate today = QDate::currentDate(); - - switch( range ) { - case Today: - return DateRange::today(); - - case Yesterday: - return DateRange(today.addDays(-1), today.addDays(-1)); - - case ThisWeek: { - return DateRange::thisWeek( DateRange::NoDateRangeFlags ); - } - - case LastWeek: { - return DateRange::weekOf(today.addDays( -KGlobal::locale()->calendar()->daysInWeek( today ) )); - } - - case ThisMonth: { - return DateRange::thisMonth( DateRange::NoDateRangeFlags ); - } - - case LastMonth: { - return DateRange::monthOf(today.addDays( -KGlobal::locale()->calendar()->daysInMonth( today ) )); - } - - case ThisYear: { - return DateRange::thisYear(); - } - - case LastYear: { - return DateRange::yearOf( QDate( today.year()-1, 1, 1 ) ); - } - - case CustomDateRange: - return m_customRange; - - default: - return DateRange(); - } - - // shut up gcc - return DateRange(); -} - - -Nepomuk::Utils::DateFacet::DateFacet( QObject* parent ) - : Facet( parent ), - d( new Private() ) -{ - d->q = this; - d->m_rangeCandidates << Anytime - << Today - << Yesterday - << ThisWeek - << LastWeek - << ThisMonth - << LastMonth - << ThisYear - << LastYear - << CustomDateRange; - setDateRangeCandidates( DefaultRanges ); -} - - -Nepomuk::Utils::DateFacet::~DateFacet() -{ - delete d; -} - - -Nepomuk::Query::Term Nepomuk::Utils::DateFacet::queryTerm() const -{ - return createDateRangeTerm( d->dateRangeCandidateToDateRange( d->m_currentRange ) ); -} - - -Nepomuk::Utils::DateFacet::SelectionMode Nepomuk::Utils::DateFacet::selectionMode() const -{ - return MatchOne; -} - - -int Nepomuk::Utils::DateFacet::count() const -{ - return d->m_ranges.count(); -} - - -KGuiItem Nepomuk::Utils::DateFacet::guiItem( int index ) const -{ - if ( index < d->m_ranges.count() ) - return KGuiItem( d->titleForDateRangeCandidate( d->m_ranges[index] ) ); - else - return KGuiItem(); -} - - -bool Nepomuk::Utils::DateFacet::isSelected( int index ) const -{ - return d->m_ranges.indexOf( d->m_currentRange ) == index; -} - - -void Nepomuk::Utils::DateFacet::setDateRangeCandidates( DateRangeCandidates ranges ) -{ - d->m_enabledRanges = ranges; - d->rebuild(); -} - - -Nepomuk::Utils::DateFacet::DateRangeCandidates Nepomuk::Utils::DateFacet::dateRangeCandidates() const -{ - return d->m_enabledRanges; -} - - -void Nepomuk::Utils::DateFacet::clearSelection() -{ - d->m_currentRange = d->m_ranges.isEmpty() ? NoDateRange : d->m_ranges.first(); - setQueryTermChanged(); - setSelectionChanged(); -} - - -void Nepomuk::Utils::DateFacet::setSelected( int index, bool selected ) -{ - if ( index == d->m_ranges.indexOf( CustomDateRange ) ) { - bool ok = false; - DateRange newRange = getCustomRange( &ok ); - if( ok ) { - d->setCurrentRange( newRange ); - } - } - - else if ( selected && - index < d->m_ranges.count() ) { - kDebug() << d->m_ranges[index] << d->dateRangeCandidateToDateRange(d->m_ranges[index]); - d->m_currentRange = d->m_ranges[index]; - setQueryTermChanged(); - setSelectionChanged(); - } - - else { - clearSelection(); - } -} - - -bool Nepomuk::Utils::DateFacet::selectFromTerm( const Nepomuk::Query::Term& term ) -{ - DateRange range = extractDateRange( term ); - return range.isValid() ? d->setCurrentRange( range ) : false; -} - - -Nepomuk::Query::Term Nepomuk::Utils::DateFacet::createDateRangeTerm( const DateRange& range ) const -{ - return Nepomuk::Query::dateRangeQuery( range.start(), range.end() ).term(); -} - - -namespace { - bool isDateComparisonTerm( const Nepomuk::Query::Term& term ) { - return( term.isComparisonTerm() && - term.toComparisonTerm().subTerm().isLiteralTerm() && - term.toComparisonTerm().subTerm().toLiteralTerm().value().isDateTime() && - ( term.toComparisonTerm().comparator() == Nepomuk::Query::ComparisonTerm::Greater || - term.toComparisonTerm().comparator() == Nepomuk::Query::ComparisonTerm::Smaller ) ); - } - - Nepomuk::Types::Property isDateTerm( const Nepomuk::Query::Term& term, QDate& start, QDate& end ) { - if( term.isAndTerm() ) { - if( term.toAndTerm().subTerms().count() != 2 || - !isDateComparisonTerm( term.toAndTerm().subTerms()[0] ) || - !isDateComparisonTerm( term.toAndTerm().subTerms()[1] ) || - term.toAndTerm().subTerms()[0].toComparisonTerm().property() != term.toAndTerm().subTerms()[1].toComparisonTerm().property() || - term.toAndTerm().subTerms()[0].toComparisonTerm().comparator() == term.toAndTerm().subTerms()[1].toComparisonTerm().comparator() ) { - return Nepomuk::Types::Property(); - } - // at this point we have two ComparisonTerms with QDate subterms and similar properties and different comparators - if( term.toAndTerm().subTerms()[0].toComparisonTerm().comparator() == Nepomuk::Query::ComparisonTerm::Greater ) { - start = term.toAndTerm().subTerms()[0].toComparisonTerm().subTerm().toLiteralTerm().value().toDateTime().toLocalTime().date(); - end = term.toAndTerm().subTerms()[1].toComparisonTerm().subTerm().toLiteralTerm().value().toDateTime().toLocalTime().date(); - } - else { - start = term.toAndTerm().subTerms()[1].toComparisonTerm().subTerm().toLiteralTerm().value().toDateTime().toLocalTime().date(); - end = term.toAndTerm().subTerms()[0].toComparisonTerm().subTerm().toLiteralTerm().value().toDateTime().toLocalTime().date(); - } - return term.toAndTerm().subTerms()[0].toComparisonTerm().property(); - } - else if( isDateComparisonTerm( term ) ) { - if( term.toComparisonTerm().comparator() == Nepomuk::Query::ComparisonTerm::Greater ) { - start = term.toComparisonTerm().subTerm().toLiteralTerm().value().toDateTime().toLocalTime().date(); - } - else { - end = term.toComparisonTerm().subTerm().toLiteralTerm().value().toDateTime().toLocalTime().date(); - } - return term.toComparisonTerm().property(); - } - else { - return Nepomuk::Types::Property(); - } - } -} - -DateRange Nepomuk::Utils::DateFacet::extractDateRange( const Query::Term& term ) const -{ - // this is ugly since creating the query is done in standardqueries.cpp - // thus, if that impl is changed this code wont work anymore. :( - if( !term.isOrTerm() ) { - return DateRange(); - } - Nepomuk::Query::OrTerm orTerm = term.toOrTerm(); - if( orTerm.subTerms().count() != 3 ) { - return DateRange(); - } - QDate start, end; - bool mtime = false; - bool created = false; - bool nuao = false; - Q_FOREACH( const Nepomuk::Query::Term& t, orTerm.subTerms() ) { - Nepomuk::Types::Property p = isDateTerm( t, start, end ); - if( p == Nepomuk::Vocabulary::NIE::lastModified() ) { - mtime = true; - } - else if( p == Nepomuk::Vocabulary::NIE::contentCreated() ) { - created = true; - } - else { - // check if it is the nuao term - if( !t.isComparisonTerm() || - !t.toComparisonTerm().isInverted() || - t.toComparisonTerm().property() != Nepomuk::Vocabulary::NUAO::involves() ) { - return DateRange(); - } - Nepomuk::Types::Property p = isDateTerm(t.toComparisonTerm().subTerm(), start, end); - if( p == Nepomuk::Vocabulary::NUAO::start() ) - nuao = true; - else - return DateRange(); - } - } - if( mtime && created && nuao ) { - return DateRange(start, end); - } - else { - return DateRange(); - } -} - - -DateRange Nepomuk::Utils::DateFacet::getCustomRange( bool* ok ) const -{ - DateRangeSelectionWidget* drw = new DateRangeSelectionWidget(); - drw->setRange( d->dateRangeCandidateToDateRange(d->m_currentRange) ); - - // we use QMenu for the look only - QMenu menu; - QWidgetAction* wa = new QWidgetAction( &menu ); - wa->setDefaultWidget(drw); - menu.addAction(wa); - - connect( drw, SIGNAL(rangeChanged(DateRange)), &menu, SLOT(close())); - - menu.exec(QCursor::pos()); - - if( ok ) - *ok = true; - return drw->range(); -} - -#include "datefacet.moc" diff --git a/nepomuk/utils/datefacet.h b/nepomuk/utils/datefacet.h deleted file mode 100644 index 00c7aeb2..00000000 --- a/nepomuk/utils/datefacet.h +++ /dev/null @@ -1,228 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_DATE_FACET_H_ -#define _NEPOMUK_QUERY_DATE_FACET_H_ - -#include "facet.h" - -class DateRange; - -namespace Nepomuk { - namespace Utils { - /** - * \class DateFacet datefacet.h Nepomuk/Utils/DateFacet - * - * \ingroup nepomuk_facets - * - * \brief A Facet that provides a set of date ranges. - * - * Filtering search results on a date is a very typical problem. This could be - * handled by adding fixed Terms to a SimpleFacet. The big problem with that - * solution, however, is that these fixed terms would become inaccurate over time. - * Say, one wants to filter files that have been modified today. This is a very - * simple filter involving the nie:lastModified property and QDate::currentDate(). - * But as soon as the application runs while the current date is changing this - * fixed term becomes invalid since it is now referencing yesterday instead of today. - * - * The DateFacet works around this problem by using the enumeration DateRangeCandidate - * instead of fixed terms and creating the terms on the fly based on the enum value. - * - * By default it creates date terms via Nepomuk::Utils::dateRangeQuery() which - * includes the file modification time but also access times and content creation times - * (the latter includes the date a photo was taken). This can, however, be modified by - * reimplementing createDateRangeTerm() and its counterpart extractDateRange(). - * - * \author Sebastian Trueg - * - * \since 4.6 - */ - class DateFacet : public Facet - { - Q_OBJECT - - public: - /** - * Creates a new date facet which contains the DefaultRanges - * date range candidates as choices. - */ - DateFacet( QObject* parent = 0 ); - - /** - * Destructor - */ - virtual ~DateFacet(); - - /** - * Creates a query term for the currently selected date range. - * This method makes use of createDateRangeTerm(). - */ - Query::Term queryTerm() const; - - /** - * The selection mode in the date facet is fixed to MatchOne, ie. - * it is an exclusive facet where a single date range must be - * selected at all time. - */ - SelectionMode selectionMode() const; - - /** - * \return The number of date range candidates set via setDateRangeCandidates(). - */ - int count() const; - - KGuiItem guiItem( int index ) const; - bool isSelected( int index ) const; - - /** - * Using fixed QDate values would result in - * invalid queries as soon as an application runs - * over the span of two days. Thus, DateFacet uses - * DateRangeCandidates to specify the list of - * choices and generates the QDate instances on the - * fly. - */ - enum DateRangeCandidate { - /// no date range - NoDateRange = 0x0, - - /// no restriction on the date - Anytime = 0x1, - - /// a date range which uses QDate::today() for start and end - Today = 0x2, - - /// a date range which uses QDate::today().addDays(-1) for start and end - Yesterday = 0x4, - - /// a date range that includes all days from the current week up to today - ThisWeek = 0x8, - - /// a date range that includes all days from the last week, ie. that before the current one - LastWeek = 0x10, - - /// a date range that includes all days from the current month up to today - ThisMonth = 0x20, - - /// a date range that includes all days from the last month, ie. that before the current one - LastMonth = 0x40, - - /// a date range that includes all days from the current year up to today - ThisYear = 0x80, - - /// a date range that includes all days from the last year, ie. that before the current one - LastYear = 0x100, - - /// a custom range - this will enable a special item that if selection will open a dialog - /// allowing the user to choose a custom date range - CustomDateRange = 0x10000, - - /// the defaults this facet starts with - DefaultRanges = Anytime|Today|ThisWeek|ThisMonth|ThisYear|CustomDateRange - }; - Q_DECLARE_FLAGS( DateRangeCandidates, DateRangeCandidate ) - - /** - * Set the date ranges this facet should provide. By default all - * date ranges from DefaultRanges are enabled. - */ - void setDateRangeCandidates( DateRangeCandidates ranges ); - - /** - * \return The date ranges configured via setDateRangeCandidates() - * \sa DateRangeCandidate - */ - DateRangeCandidates dateRangeCandidates() const; - - public Q_SLOTS: - /** - * Resets the current range to the default value which is the first in the - * list of candidates. If Anytime is part of the configured candidates it will - * be selected. - */ - void clearSelection(); - - /** - * Change the currently selected date range. This method is typically triggered - * by user interaction. - */ - void setSelected( int index, bool selected = true ); - - /** - * Select the current date range based on \p term. This method relies on - * extractDateRange() to determine if \p term can be used or not. - * - * \return \p true if \p term could be handled and the current range - * has been changed accordingly, \p false otherwise. - */ - bool selectFromTerm( const Nepomuk::Query::Term& queryTerm ); - - protected: - /** - * Create the query Term that reflects the dates specified in \p range. - * The default implementation uses Nepomuk::Utils::dateRangeQuery(). - * - * Subclasses may reimplement this method to create custom date ranges. - * - * If this method is reimplemented extractDateRange() also needs to be - * implemented in order for selectFromTerm() to work properly. - */ - virtual Query::Term createDateRangeTerm( const DateRange& range ) const; - - /** - * This is the counterpart method to createDateRangeTerm(). It should only - * extract valid date ranges from terms that have been created by createDateRangeTerm() - * or have the same structure. - * - * A working implementation is required in order for selectFromTerm() to - * work properly. - * - * The default implementation can handle query terms created via - * Nepomuk::Utils::dateRangeQuery(). - */ - virtual DateRange extractDateRange( const Query::Term& queryTerm ) const; - - /** - * Retrieve a custom date range typically from the user. The default implementation - * opens a popup at the current cursor position allowing the user to choose the range - * via appropriate GUI elements. - * - * This method is called internally by DateFacet to handle the CustomRange date range - * candidate. - * - * Reimplementing this method allows to provide a customized way to get a range - * for the CustomRange date range candidate. - * - * \param ok The method should set this boolean according to the user feedback. This is - * necessary since returning an invalid DateRange is ambiguous. - * - * \return The date range chosen by the user. - */ - virtual DateRange getCustomRange( bool* ok = 0 ) const; - - private: - class Private; - Private* const d; - }; - } -} - -#endif diff --git a/nepomuk/utils/daterange.cpp b/nepomuk/utils/daterange.cpp deleted file mode 100644 index cbb3b28f..00000000 --- a/nepomuk/utils/daterange.cpp +++ /dev/null @@ -1,264 +0,0 @@ -/* - Copyright (c) 2009-2010 Sebastian Trueg - - 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 . - -*/ - -#include "daterange.h" - -#include "kglobal.h" -#include "klocale.h" -#include "kcalendarsystem.h" - -#include -#include - - -class DateRange::Private : public QSharedData -{ -public: - QDate m_start; - QDate m_end; -}; - - -DateRange::DateRange( const QDate& s, - const QDate& e ) - : d(new Private()) -{ - d->m_start = s; - d->m_end = e; -} - - -DateRange::DateRange( const DateRange& other ) -{ - d = other.d; -} - - -DateRange::~DateRange() -{ -} - - -DateRange& DateRange::operator=( const DateRange& other ) -{ - d = other.d; - return *this; -} - - -QDate DateRange::start() const -{ - return d->m_start; -} - - -QDate DateRange::end() const -{ - return d->m_end; -} - - -bool DateRange::isValid() const -{ - return KGlobal::locale()->calendar()->isValid(d->m_start) && KGlobal::locale()->calendar()->isValid(d->m_end) && d->m_start <= d->m_end; -} - - -void DateRange::setStart( const QDate& date ) -{ - d->m_start = date; -} - - -void DateRange::setEnd( const QDate& date ) -{ - d->m_end = date; -} - - -// static -DateRange DateRange::today() -{ - const QDate today = QDate::currentDate(); - return DateRange( today, today ); -} - - -namespace { - /** - * Put \p day into the week range 1...weekDays - */ - int dateModulo( int day, int weekDays ) { - day = day%weekDays; - if ( day == 0 ) - return weekDays; - else - return day; - } -} - -// static -DateRange DateRange::thisWeek( DateRangeFlags flags ) -{ - return weekOf( QDate::currentDate(), flags ); -} - - -// static -DateRange DateRange::weekOf( const QDate& date, DateRangeFlags flags ) -{ - const int daysInWeek = KGlobal::locale()->calendar()->daysInWeek( date ); - const int weekStartDay = KGlobal::locale()->weekStartDay(); - const int weekEndDay = dateModulo( weekStartDay+daysInWeek-1, daysInWeek ); - const int dayOfWeek = KGlobal::locale()->calendar()->dayOfWeek( date ); - - DateRange range; - - if ( weekStartDay > dayOfWeek ) - range.d->m_start = date.addDays( - (dayOfWeek + daysInWeek - weekStartDay) ); - else - range.d->m_start = date.addDays( - (dayOfWeek - weekStartDay) ); - - if ( weekEndDay < dayOfWeek ) - range.d->m_end = date.addDays( weekEndDay + daysInWeek - dayOfWeek ); - else - range.d->m_end = date.addDays( weekEndDay - dayOfWeek); - - if( flags & ExcludeFutureDays ) { - const QDate today = QDate::currentDate(); - if( range.start() <= today && range.end() >= today ) - range.setEnd( today ); - } - - return range; -} - - -// static -DateRange DateRange::thisMonth( DateRangeFlags flags ) -{ - return monthOf( QDate::currentDate(), flags ); -} - - -// static -DateRange DateRange::monthOf( const QDate& date, DateRangeFlags flags ) -{ - DateRange range( KGlobal::locale()->calendar()->firstDayOfMonth( date ), - KGlobal::locale()->calendar()->lastDayOfMonth( date ) ); - if( flags & ExcludeFutureDays ) { - const QDate today = QDate::currentDate(); - if( range.start() <= today && range.end() >= today ) - range.setEnd( today ); - } - return range; -} - - - -// static -DateRange DateRange::thisYear( DateRangeFlags flags ) -{ - return yearOf( QDate::currentDate(), flags ); -} - - -// static -DateRange DateRange::yearOf( const QDate& date, DateRangeFlags flags ) -{ - DateRange range( KGlobal::locale()->calendar()->firstDayOfYear( date ), - KGlobal::locale()->calendar()->lastDayOfYear( date ) ); - if( flags & ExcludeFutureDays ) { - const QDate today = QDate::currentDate(); - if( date.year() == today.year() ) - range.setEnd( today ); - } - return range; -} - - -// static -DateRange DateRange::lastNDays( int n ) -{ - DateRange range = today(); - range.setStart( range.start().addDays( -n ) ); - return range; -} - - -// static -DateRange DateRange::lastNWeeks( int n ) -{ - // This week is the first week - DateRange range = thisWeek( DateRange::NoDateRangeFlags ); - - // go into the previous week - range.setStart( range.start().addDays( -1 ) ); - - // from that on we go back n-1 weeks, for each of those we call daysInWeek - for( int i = 1; i < n; ++i ) { - QDate weekDay = range.start(); - weekDay.addDays( -KGlobal::locale()->calendar()->daysInWeek( weekDay ) ); - range.setStart( weekDay ); - } - - // go back to the start of the next week, thus, reverting the -1 we did above - range.setStart( range.start().addDays( 1 ) ); - - return range; -} - - -// static -DateRange DateRange::lastNMonths( int n ) -{ - // This month is the first month - DateRange range = thisMonth( DateRange::NoDateRangeFlags ); - - // move the start n-1 months back - range.setStart( KGlobal::locale()->calendar()->addMonths(range.start(), n-1 ) ); - - return range; -} - - -bool operator==( const DateRange& r1, const DateRange& r2 ) -{ - return r1.start() == r2.start() && r1.end() == r2.end(); -} - - -bool operator!=( const DateRange& r1, const DateRange& r2 ) -{ - return r1.start() != r2.start() || r1.end() != r2.end(); -} - - -uint qHash( const DateRange& range ) -{ - return qHash( range.start() ) ^ qHash( range.end() ); -} - -QDebug operator<<( QDebug dbg, const DateRange& range ) -{ - dbg.nospace() << "DateRange(" << range.start() << range.end() << ")"; - return dbg; -} diff --git a/nepomuk/utils/daterange.h b/nepomuk/utils/daterange.h deleted file mode 100644 index 0d793d51..00000000 --- a/nepomuk/utils/daterange.h +++ /dev/null @@ -1,214 +0,0 @@ -/* - Copyright (c) 2009-2010 Sebastian Trueg - - 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 _DATE_RANGE_H_ -#define _DATE_RANGE_H_ - -#include -#include - -class QDebug; - -/** - * \class DateRange daterange.h DateRange - * - * \brief A simple data structure storing a start and an end date. - * - * %DateRange is a very simple data structure storing a start and an end date. - * The really interesting parts are the static factory methods which take the - * current calendar system into account and, thus, create accurate values. - * - * \author Sebastian Trueg - */ -class DateRange -{ -public: - /** - * Create a new range - */ - DateRange( const QDate& s = QDate(), - const QDate& e = QDate() ); - - /** - * Copy constructor - */ - DateRange( const DateRange& other ); - - /** - * Destructor - */ - ~DateRange(); - - /** - * Make this range a copy of \p other - */ - DateRange& operator=( const DateRange& other ); - - /** - * Start date of the range. - */ - QDate start() const; - - /** - * End date of the range. - */ - QDate end() const; - - /** - * Checks if both start and end are valid dates - * and if end is after start. - */ - bool isValid() const; - - /** - * Set the start to \p date. - */ - void setStart( const QDate& date ); - - /** - * Set the end to \p date. - */ - void setEnd( const QDate& date ); - - /** - * \returns a DateRange with both start and end - * dates set to QDate::currentDate() - */ - static DateRange today(); - - /** - * The flags allow to change the result returned by several of the - * static factory methods provided by DateRange such as thisWeek() - * or thisMonth(). - */ - enum DateRangeFlag { - /** - * No flags. - */ - NoDateRangeFlags = 0x0, - - /** - * Exclude days that are in the future. thisWeek() for example - * will not include the days in the week that come after the current - * day. - */ - ExcludeFutureDays = 0x1 - }; - Q_DECLARE_FLAGS( DateRangeFlags, DateRangeFlag ) - - /** - * Takes KLocale::weekStartDay() into account. - * \sa DateRangeFlag - */ - static DateRange thisWeek( DateRangeFlags flags = NoDateRangeFlags ); - - /** - * Takes KLocale::weekStartDay() into account. - * \param flags ExcludeFutureDays does only makes sense for a date in the current week. For - * future weeks it is ignored. - * \sa DateRangeFlag - */ - static DateRange weekOf( const QDate& date, DateRangeFlags flags = NoDateRangeFlags ); - - /** - * \return A DateRange which includes all days of the current month. - * - * \sa DateRangeFlag - */ - static DateRange thisMonth( DateRangeFlags flags = NoDateRangeFlags ); - - /** - * \param flags ExcludeFutureDays does only makes sense for a date in the current month. For - * future months it is ignored. - * \return A DateRange which includes all days of the month in which - * \p date falls. - * \sa DateRangeFlag - */ - static DateRange monthOf( const QDate& date, DateRangeFlags flags = NoDateRangeFlags ); - - /** - * \return A DateRange which includes all days of the current year. - * \sa DateRangeFlag - */ - static DateRange thisYear( DateRangeFlags flags = NoDateRangeFlags ); - - /** - * \param flags ExcludeFutureDays does only makes sense for a date in the current year. For - * future years it is ignored. - * \return A DateRange which includes all days of the year in which - * \p date falls. - * \sa DateRangeFlags - */ - static DateRange yearOf( const QDate& date, DateRangeFlags flags = NoDateRangeFlags ); - - /** - * \return A DateRange which spans the last \p n days. - */ - static DateRange lastNDays( int n ); - - /** - * \return A DateRange which spans the last \p n weeks, - * including the already passed days in the current week. - */ - static DateRange lastNWeeks( int n ); - - /** - * \return A DateRange which spans the last \p n months, - * including the already passed days in the current month. - */ - static DateRange lastNMonths( int n ); - -private: - class Private; - QSharedDataPointer d; -}; - -/** - * Comparison operator - * - * \related DateRange - */ -bool operator==( const DateRange& r1, const DateRange& r2 ); - -/** - * Comparison operator - * - * \related DateRange - */ -bool operator!=( const DateRange& r1, const DateRange& r2 ); - -/** - * Allows using DateRange in hashed structures such as QHash or QMap. - * - * \related DateRange - */ -uint qHash( const DateRange& range ); - -/** - * Debug streaming operator - * - * \relates DateRange - */ -QDebug operator<<( QDebug dbg, const DateRange& range ); - -Q_DECLARE_OPERATORS_FOR_FLAGS( DateRange::DateRangeFlags ) - -#endif diff --git a/nepomuk/utils/daterangeselectionwidget.cpp b/nepomuk/utils/daterangeselectionwidget.cpp deleted file mode 100644 index fd397e88..00000000 --- a/nepomuk/utils/daterangeselectionwidget.cpp +++ /dev/null @@ -1,337 +0,0 @@ -/* - Copyright (c) 2009 Sebastian Trueg - - 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 . - -*/ - -#include "daterangeselectionwidget.h" -#include "ui_daterangeselectionwidget.h" -#include "daterange.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -class DateRangeSelectionWidget::Private : public Ui::DateRangeSelectionWidgetBase -{ -public: - void _k_anytimeClicked(); - void _k_beforeClicked(); - void _k_afterClicked(); - void _k_rangeClicked(); - void _k_rangeClicked( QAction* ); - void _k_rangeStartEdited( const QDate& date ); - void _k_rangeEndEdited( const QDate& date ); - void _k_calendarDateClicked( const QDate& date ); - - void checkButton( QAbstractButton* button ); - void setupPopupMenus(); - - void updateCalendar( const DateRange& range ); - void updateEditBoxes( const DateRange& range ); - - void setRange( const DateRange& range ); - - QAction* findRangeAction( const DateRange& range ); - - DateRange m_range; - - QAction* m_currentRangeAction; - QHash m_rangeActionMap; - - DateRangeSelectionWidget* q; -}; - - -void DateRangeSelectionWidget::Private::_k_anytimeClicked() -{ - checkButton( m_anytimeButton ); - setRange( DateRange() ); - - emit q->rangeChanged( m_range ); -} - - -void DateRangeSelectionWidget::Private::_k_beforeClicked() -{ - if ( m_range.end().isValid() ) - setRange( DateRange( QDate(), m_range.end() ) ); - else if ( m_range.start().isValid() ) - setRange( DateRange( QDate(), m_range.start() ) ); - else - setRange( DateRange( QDate(), QDate::currentDate() ) ); - - emit q->rangeChanged( m_range ); -} - - -void DateRangeSelectionWidget::Private::_k_afterClicked() -{ - if ( m_range.start().isValid() ) - setRange( DateRange( m_range.start(), QDate() ) ); - else if ( m_range.end().isValid() ) - setRange( DateRange( m_range.end(), QDate() ) ); - else - setRange( DateRange( QDate::currentDate(), QDate() ) ); - - emit q->rangeChanged( m_range ); -} - - -void DateRangeSelectionWidget::Private::_k_rangeClicked() -{ - _k_rangeClicked( m_currentRangeAction ); -} - - -void DateRangeSelectionWidget::Private::_k_rangeClicked( QAction* action ) -{ - m_currentRangeAction = action; - m_rangesButton->setText( action->text() ); - setRange( m_rangeActionMap[action] ); - - emit q->rangeChanged( m_range ); -} - - -void DateRangeSelectionWidget::Private::_k_rangeStartEdited( const QDate& date ) -{ - if ( date > m_range.end() ) - setRange( DateRange( date, date ) ); - else - setRange( DateRange( date, m_range.end() ) ); - - emit q->rangeChanged( m_range ); -} - - -void DateRangeSelectionWidget::Private::_k_rangeEndEdited( const QDate& date ) -{ - if ( date < m_range.start() ) - setRange( DateRange( date, date ) ); - else - setRange( DateRange( m_range.start(), date ) ); - - emit q->rangeChanged( m_range ); -} - - -void DateRangeSelectionWidget::Private::_k_calendarDateClicked( const QDate& date ) -{ - if ( QApplication::keyboardModifiers() & Qt::ShiftModifier ) { - if ( m_range.start().isValid() && - date < m_range.start() ) { - setRange( DateRange( date, m_range.end().isValid() ? m_range.end() : m_range.start() ) ); - emit q->rangeChanged( m_range ); - } - else if ( m_range.end().isValid() && - date < m_range.end() ) { - setRange( DateRange( date, m_range.end() ) ); - emit q->rangeChanged( m_range ); - } - else if ( m_range.end().isValid() && - date > m_range.end() ) { - setRange( DateRange( m_range.start().isValid() ? m_range.start() : m_range.end(), date ) ); - emit q->rangeChanged( m_range ); - } - else if ( m_range.start().isValid() && - date > m_range.start() ) { - setRange( DateRange( m_range.start(), date ) ); - emit q->rangeChanged( m_range ); - } - } - else if ( m_beforeButton->isChecked() ) { - setRange( DateRange( QDate(), date ) ); - emit q->rangeChanged( m_range ); - } - else if ( m_afterButton->isChecked() ) { - setRange( DateRange( date, QDate() ) ); - emit q->rangeChanged( m_range ); - } - else { - setRange( DateRange( date, date ) ); - emit q->rangeChanged( m_range ); - } -} - - -void DateRangeSelectionWidget::Private::checkButton( QAbstractButton* button ) -{ - foreach( QAbstractButton* b, m_buttonGroup->buttons() ) { - b->setChecked( b == button ); - } -} - - -void DateRangeSelectionWidget::Private::setupPopupMenus() -{ - QMenu* menu = new QMenu(m_rangesButton); - - QAction* a = new QAction( menu ); - a->setText( i18n( "Today" ) ); - m_rangeActionMap.insert( a, DateRange::today() ); - menu->addAction( a ); - - // today is the default - m_currentRangeAction = a; - - a = new QAction( menu ); - a->setText( i18n( "This Week" ) ); - m_rangeActionMap.insert( a, DateRange::thisWeek() ); - menu->addAction( a ); - - a = new QAction( menu ); - a->setText( i18n( "This Month" ) ); - m_rangeActionMap.insert( a, DateRange::thisMonth() ); - menu->addAction( a ); - - m_rangesButton->setMenu( menu ); -} - - -void DateRangeSelectionWidget::Private::updateCalendar( const DateRange& range ) -{ - m_calendar->setDateTextFormat( QDate(), QTextCharFormat() ); - if ( range.start().isValid() ) - m_calendar->setSelectedDate( range.start() ); - else if ( range.end().isValid() ) - m_calendar->setSelectedDate( range.end() ); - else - m_calendar->setSelectedDate( QDate::currentDate() ); - if ( range.isValid() ) { - QTextCharFormat selectedFormat; - selectedFormat.setBackground( q->palette().color( QPalette::Highlight ) ); - selectedFormat.setForeground( q->palette().color( QPalette::HighlightedText ) ); - for ( QDate date = range.start(); date <= range.end(); date = date.addDays( 1 ) ) { - m_calendar->setDateTextFormat( date, selectedFormat ); - } - } -} - - -void DateRangeSelectionWidget::Private::updateEditBoxes( const DateRange& range ) -{ - m_rangeStartEdit->blockSignals( true ); - m_rangeEndEdit->blockSignals( true ); - - m_rangeStartEdit->setDate( range.start() ); - m_rangeEndEdit->setDate( range.end() ); - m_rangeStartEdit->setEnabled( range.start().isValid() ); - m_rangeEndEdit->setEnabled( range.end().isValid() ); - - m_rangeStartEdit->blockSignals( false ); - m_rangeEndEdit->blockSignals( false ); -} - - -void DateRangeSelectionWidget::Private::setRange( const DateRange& range ) -{ - m_range = range; - - if ( range.isValid() ) { - if ( QAction* a = findRangeAction( range ) ) { - m_currentRangeAction = a; - m_rangesButton->setText( a->text() ); - checkButton( m_rangesButton ); - } - else { - checkButton( 0 ); - } - } - else if ( range.start().isValid() ) { - checkButton( m_afterButton ); - } - else if ( range.end().isValid() ) { - checkButton( m_beforeButton ); - } - else { - checkButton( m_anytimeButton ); - } - - updateCalendar( range ); - updateEditBoxes( range ); -} - - -QAction* DateRangeSelectionWidget::Private::findRangeAction( const DateRange& range ) -{ - // We have only 3 elements in here, thus, looping over them is ok - for ( QHash::const_iterator it = m_rangeActionMap.constBegin(); - it != m_rangeActionMap.constEnd(); ++it ) { - if ( it.value() == range ) - return it.key(); - } - return 0; -} - - -DateRangeSelectionWidget::DateRangeSelectionWidget( QWidget* parent ) - : QWidget( parent ), - d( new Private() ) -{ - d->q = this; - d->setupUi( this ); - d->setupPopupMenus(); - - d->m_calendar->setFirstDayOfWeek( Qt::DayOfWeek( KGlobal::locale()->weekStartDay() ) ); - connect( d->m_anytimeButton, SIGNAL(clicked()), - this, SLOT(_k_anytimeClicked()) ); - connect( d->m_beforeButton, SIGNAL(clicked()), - this, SLOT(_k_beforeClicked()) ); - connect( d->m_afterButton, SIGNAL(clicked()), - this, SLOT(_k_afterClicked()) ); - connect( d->m_rangesButton, SIGNAL(clicked()), - this, SLOT(_k_rangeClicked()) ); - connect( d->m_rangesButton, SIGNAL(triggered(QAction*)), - this, SLOT(_k_rangeClicked(QAction*)) ); - connect( d->m_rangeStartEdit, SIGNAL(dateChanged(QDate)), - this, SLOT(_k_rangeStartEdited(QDate)) ); - connect( d->m_rangeEndEdit, SIGNAL(dateChanged(QDate)), - this, SLOT(_k_rangeEndEdited(QDate)) ); - connect( d->m_calendar, SIGNAL(clicked(QDate)), - this, SLOT(_k_calendarDateClicked(QDate)) ); - - setRange( DateRange() ); -} - - -DateRangeSelectionWidget::~DateRangeSelectionWidget() -{ - delete d; -} - - -DateRange DateRangeSelectionWidget::range() const -{ - return d->m_range; -} - - -void DateRangeSelectionWidget::setRange( const DateRange& range ) -{ - d->setRange( range ); -} - -#include "daterangeselectionwidget.moc" diff --git a/nepomuk/utils/daterangeselectionwidget.h b/nepomuk/utils/daterangeselectionwidget.h deleted file mode 100644 index 16a6dfb8..00000000 --- a/nepomuk/utils/daterangeselectionwidget.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - Copyright (c) 2009-2010 Sebastian Trueg - - 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 _DATE_RANGE_SELECTION_WIDGET_H_ -#define _DATE_RANGE_SELECTION_WIDGET_H_ - -#include - -class DateRange; -class QAction; -class QDate; - -/** - * \class DataRangeSelectionWidget daterangeselectionwidget.h DateRangeSelectionWidget - * - * \brief A widget that allows to select a range of dates. - * - * \sa DateRange - * - * \author Sebastian Trueg - */ -class DateRangeSelectionWidget : public QWidget -{ - Q_OBJECT - -public: - /** - * Create a new DateRange selection widget with an - * invalid DateRange set which corresponds to "anytime". - */ - DateRangeSelectionWidget( QWidget* parent = 0 ); - - /** - * Destructor - */ - ~DateRangeSelectionWidget(); - - /** - * One of: - * \li a range between two valid dates - * \li only a valid end date: all dates before that date - * \li only a valid start date: all dates after that date - * \li invalid range: anytime - */ - DateRange range() const; - -public Q_SLOTS: - /** - * Set the date range. - */ - void setRange( const DateRange& range ); - -Q_SIGNALS: - /** - * Emitted when the date range changes. - */ - void rangeChanged( const DateRange& range ); - -private: - class Private; - Private* const d; - - Q_PRIVATE_SLOT( d, void _k_anytimeClicked() ) - Q_PRIVATE_SLOT( d, void _k_beforeClicked() ) - Q_PRIVATE_SLOT( d, void _k_afterClicked() ) - Q_PRIVATE_SLOT( d, void _k_rangeClicked() ) - Q_PRIVATE_SLOT( d, void _k_rangeClicked( QAction* ) ) - Q_PRIVATE_SLOT( d, void _k_rangeStartEdited( const QDate& date ) ) - Q_PRIVATE_SLOT( d, void _k_rangeEndEdited( const QDate& date ) ) - Q_PRIVATE_SLOT( d, void _k_calendarDateClicked( const QDate& date ) ) -}; - -#endif diff --git a/nepomuk/utils/daterangeselectionwidget.ui b/nepomuk/utils/daterangeselectionwidget.ui deleted file mode 100644 index 30a3b629..00000000 --- a/nepomuk/utils/daterangeselectionwidget.ui +++ /dev/null @@ -1,123 +0,0 @@ - - - Sebastian Trueg <trueg@kde.org> - DateRangeSelectionWidgetBase - - - - 0 - 0 - 364 - 240 - - - - - - - - - Qt::Horizontal - - - - 0 - 20 - - - - - - - - Anytime - - - true - - - true - - - m_buttonGroup - - - - - - - Before - - - true - - - true - - - m_buttonGroup - - - - - - - After - - - true - - - true - - - m_buttonGroup - - - - - - - Today - - - true - - - QToolButton::MenuButtonPopup - - - true - - - m_buttonGroup - - - - - - - - - - - - - - - - - - - - - - - - - - false - - - - diff --git a/nepomuk/utils/dynamicresourcefacet.cpp b/nepomuk/utils/dynamicresourcefacet.cpp deleted file mode 100644 index 47dcf4f4..00000000 --- a/nepomuk/utils/dynamicresourcefacet.cpp +++ /dev/null @@ -1,422 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "dynamicresourcefacet.h" -#include "dynamicresourcefacet_p.h" - -#include "andterm.h" -#include "orterm.h" -#include "resourceterm.h" -#include "resourcetypeterm.h" -#include "comparisonterm.h" -#include "result.h" -#include "query.h" -#include "queryserviceclient.h" - -#include "property.h" -#include "class.h" -#include "resource.h" -#include "resourcemanager.h" - -#include "searchwidget.h" - -#include "kguiitem.h" -#include "kdebug.h" - -#include - - -void Nepomuk::Utils::DynamicResourceFacet::Private::rebuild( bool clearSelection ) -{ - kDebug() << clearSelection; - m_haveMore = false; - m_resources.clear(); - if( clearSelection ) - m_selectedResources.clear(); - q->setLayoutChanged(); - - Query::Query query = q->resourceQuery( m_currentQuery ); - query.setLimit( m_maxRows+1 ); - startQuery( query ); -} - - -void Nepomuk::Utils::DynamicResourceFacet::Private::startQuery( const Query::Query& query ) -{ - kDebug() << query; - m_queryClient.query( query ); -} - - -void Nepomuk::Utils::DynamicResourceFacet::Private::addResource( const Nepomuk::Resource& res ) -{ - if ( !m_resources.contains( res ) ) { - m_resources.append( res ); - q->setLayoutChanged(); - } -} - - -void Nepomuk::Utils::DynamicResourceFacet::Private::_k_newEntries( const QList& entries ) -{ - kDebug(); - bool selectionChanged = false; - Q_FOREACH( const Query::Result& result, entries ) { - if( m_resources.count() == m_maxRows ) { - // add the more... button - m_haveMore = true; - } - else if( !m_resources.contains(result.resource()) ){ - m_resources.append( result.resource() ); - if( m_selectionMode == Facet::MatchOne && - m_selectedResources.isEmpty() ) { - m_selectedResources << m_resources.first(); - selectionChanged = true; - } - else if( m_selectedResources.contains(result.resource()) ) { - // in case we remember a selection from before - selectionChanged = true; - } - } - } - q->setLayoutChanged(); -} - - -void Nepomuk::Utils::DynamicResourceFacet::Private::_k_populateFinished() -{ - kDebug() << m_resources.count(); - m_queryClient.close(); - - // clean up selection in case rebuild was called without clearing it - // FIXME: shouldn't we rather add all the selected ones that are not in the list yet? - QSet::iterator it = m_selectedResources.begin(); - while( it != m_selectedResources.end() ) { - if( m_resources.contains( *it ) ) - ++it; - else - it = m_selectedResources.erase(it); - } -} - - -Nepomuk::Utils::DynamicResourceFacet::DynamicResourceFacet( QObject* parent ) - : Facet(parent), - d(new Private()) -{ - d->q = this; - connect( &d->m_queryClient, SIGNAL(newEntries(QList)), - this, SLOT(_k_newEntries(QList)) ); - connect( &d->m_queryClient, SIGNAL(finishedListing()), - this, SLOT(_k_populateFinished()) ); -} - - -Nepomuk::Utils::DynamicResourceFacet::~DynamicResourceFacet() -{ - delete d; -} - - -void Nepomuk::Utils::DynamicResourceFacet::setSelectionMode( SelectionMode mode ) -{ - d->m_selectionMode = mode; - clearSelection(); -} - - -Nepomuk::Utils::Facet::SelectionMode Nepomuk::Utils::DynamicResourceFacet::selectionMode() const -{ - return d->m_selectionMode; -} - - -Nepomuk::Query::Term Nepomuk::Utils::DynamicResourceFacet::queryTerm() const -{ - if( d->m_resources.isEmpty() || - d->m_selectedResources.isEmpty() ) { - return Query::Term(); - } - else { - switch( d->m_selectionMode ) { - case MatchAll: { - Query::AndTerm andTerm; - Q_FOREACH( const Resource& res, d->m_selectedResources ) { - andTerm.addSubTerm( termForResource( res ) ); - } - return andTerm.optimized(); - } - case MatchAny: { - Query::OrTerm orTerm; - Q_FOREACH( const Resource& res, d->m_selectedResources ) { - orTerm.addSubTerm( termForResource(res) ); - } - return orTerm.optimized(); - } - case MatchOne: - return termForResource( *d->m_selectedResources.begin() ); - } - } - - // make gcc shut up - return Query::Term(); -} - - -int Nepomuk::Utils::DynamicResourceFacet::count() const -{ - int c = d->m_resources.count(); - if ( d->m_haveMore ) - ++c; - return c; -} - - -bool Nepomuk::Utils::DynamicResourceFacet::isSelected( int index ) const -{ - if( index < d->m_resources.count() ) - return d->m_selectedResources.contains( d->m_resources[index] ); - else - return false; -} - - -void Nepomuk::Utils::DynamicResourceFacet::setRelation( const Types::Property& prop ) -{ - d->m_property = prop; - d->rebuild(); -} - - -void Nepomuk::Utils::DynamicResourceFacet::setResourceType( const Types::Class& type ) -{ - d->m_resourceType = type; - d->rebuild(); -} - - -void Nepomuk::Utils::DynamicResourceFacet::setMaxRows( int max ) -{ - d->m_maxRows = max; - d->rebuild(); -} - - -Nepomuk::Types::Property Nepomuk::Utils::DynamicResourceFacet::relation() const -{ - return d->m_property; -} - - -Nepomuk::Types::Class Nepomuk::Utils::DynamicResourceFacet::resourceType() const -{ - return d->resourceType(); -} - - -QList Nepomuk::Utils::DynamicResourceFacet::selectedResources() const -{ - return d->m_selectedResources.toList(); -} - - -int Nepomuk::Utils::DynamicResourceFacet::maxRows() const -{ - return d->m_maxRows; -} - - -KGuiItem Nepomuk::Utils::DynamicResourceFacet::guiItem( int index ) const -{ - KGuiItem item; - - if ( index < d->m_resources.count() ) { - item.setText( d->m_resources[index].genericLabel() ); - return item; - } - else if ( d->m_haveMore && index == count()-1 ) { - item.setText( i18nc( "@option:check An item in a list of resources that allows to query for more resources to put in the list", "More..." ) ); - } - - return item; -} - - -void Nepomuk::Utils::DynamicResourceFacet::setSelected( const Resource& res, bool selected ) -{ - kDebug() << res.resourceUri() << selected; - if( res.hasType( d->resourceType() ) ) { - if( selected ) { - d->addResource(res); - } - if ( d->m_resources.contains( res ) ) { - setSelected( d->m_resources.indexOf( res ), selected ); - } - } -} - - -void Nepomuk::Utils::DynamicResourceFacet::setSelected( int index, bool selected ) -{ - kDebug() << index << selected; - if ( d->m_haveMore && index == count()-1 && selected ) { - const QList rl = getMoreResources(); - Q_FOREACH( const Resource& res, rl ) { - // FIXME: try to honor d->m_maxRows - if ( !d->m_resources.contains( res ) ) { - d->m_resources.append( res ); - setLayoutChanged(); - } - - // select the new item - setSelected( d->m_resources.indexOf(res) ); - } - - // unselect the more item - setSelected( d->m_resources.count(), false ); - } - else if( index < d->m_resources.count() ) { - Resource res = d->m_resources[index]; - if ( selectionMode() == MatchOne ) { - if ( d->m_selectedResources.contains( res ) && !selected ) { - clearSelection(); - } - else if ( selected ) { - d->m_selectedResources.clear(); - d->m_selectedResources.insert( res ); - } - } - else if ( selected ) { - d->m_selectedResources.insert( res ); - } - else { - d->m_selectedResources.remove( res ); - } - } - setSelectionChanged(); - setQueryTermChanged(); -} - - -void Nepomuk::Utils::DynamicResourceFacet::clearSelection() -{ - kDebug(); - d->m_selectedResources.clear(); - if( selectionMode() == MatchOne && !d->m_resources.isEmpty() ) - d->m_selectedResources.insert(d->m_resources.first()); - setSelectionChanged(); - setQueryTermChanged(); -} - - -bool Nepomuk::Utils::DynamicResourceFacet::selectFromTerm( const Nepomuk::Query::Term& term ) -{ - kDebug() << term; - Resource res = resourceForTerm(term); - if( res.isValid() ) { - setSelected( res ); - return true; - } - else if( ( term.isAndTerm() && selectionMode() == MatchAll ) || - ( term.isOrTerm() && selectionMode() == MatchAny ) ) { - QList resources; - - // first check if all of the terms are usable - const QList subTerms = term.isAndTerm() ? term.toAndTerm().subTerms() : term.toOrTerm().subTerms(); - Q_FOREACH( const Query::Term& subTerm, subTerms ) { - Resource res = resourceForTerm(subTerm); - if( res.isValid() ) - resources << res; - else - return false; - } - - // all terms are in facet usable - Q_FOREACH( const Resource& res, resources ) { - setSelected( res ); - } - return true; - } - else { - return false; - } -} - - -void Nepomuk::Utils::DynamicResourceFacet::handleClientQueryChange() -{ - kDebug(); - d->rebuild( false ); -} - - -Nepomuk::Query::Query Nepomuk::Utils::DynamicResourceFacet::resourceQuery( const Query::Query& clientQuery ) const -{ - // we only select resources that make sense with the current query, ie. those that would actually - // change the current result set - Query::ComparisonTerm clientQueryRestrictionTerm( d->m_property, clientQuery.term() ); - clientQueryRestrictionTerm.setInverted(true); - - // we sort the resources by usage - Nepomuk::Query::ComparisonTerm term( d->m_property, Nepomuk::Query::Term() ); - term.setSortWeight( 1, Qt::DescendingOrder ); - term.setAggregateFunction( Nepomuk::Query::ComparisonTerm::Count ); - term.setInverted(true); - - return Query::Query( Query::ResourceTypeTerm( resourceType() ) && clientQueryRestrictionTerm && term ); -} - - -Nepomuk::Query::Term Nepomuk::Utils::DynamicResourceFacet::termForResource( const Resource& res ) const -{ - return d->m_property == Query::ResourceTerm( res ); -} - - -Nepomuk::Resource Nepomuk::Utils::DynamicResourceFacet::resourceForTerm( const Nepomuk::Query::Term& term ) const -{ - if( term.isComparisonTerm() && - term.toComparisonTerm().property() == d->m_property && - term.toComparisonTerm().subTerm().isResourceTerm() && - term.toComparisonTerm().subTerm().toResourceTerm().resource().hasType( d->resourceType() ) ) { - return term.toComparisonTerm().subTerm().toResourceTerm().resource(); - } - else { - return Resource(); - } -} - - -QList Nepomuk::Utils::DynamicResourceFacet::getMoreResources() const -{ - return SearchWidget::searchResources( 0, resourceQuery( d->m_currentQuery ), SearchWidget::NoConfigFlags ); -} - - -Nepomuk::Resource Nepomuk::Utils::DynamicResourceFacet::resourceAt(int i) const -{ - if( i < d->m_resources.count() ) - return d->m_resources[i]; - else - return Resource(); -} - -#include "dynamicresourcefacet.moc" diff --git a/nepomuk/utils/dynamicresourcefacet.h b/nepomuk/utils/dynamicresourcefacet.h deleted file mode 100644 index 81c75414..00000000 --- a/nepomuk/utils/dynamicresourcefacet.h +++ /dev/null @@ -1,271 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_DYNAMIC_RESOURCE_FACET_H_ -#define _NEPOMUK_QUERY_DYNAMIC_RESOURCE_FACET_H_ - -#include "facet.h" -#include "nepomukutils_export.h" - -#include - -namespace Nepomuk { - class Resource; - namespace Types { - class Property; - class Class; - } - namespace Query { - class Result; - } - - namespace Utils { - /** - * \class DynamicResourceFacet dynamicresourcefacet.h Nepomuk/Utils/DynamicResourceFacet - * - * \ingroup nepomuk_facets - * - * \brief A facet that presents a dynamic lists of resources with the possibility - * to search for more. - * - * The %DynamicResourceFacet provides a way for the user to choose one or more resources - * which in combination with a property are used to construct Query::ComparisonTerm instances - * that make up the facet's term. - * - * A typical use case would be the relation to a project or a person or a tag. The latter, - * however, is already provided via Facet::createTagFacet(). - * - * Usage is simple: set the property to use via setRelation() and optionally a resource type - * via setResourceType(). - * - * For customized query terms and resource listing DynamicResourceFacet might also be used - * as a base class for a new facet by reimplementing methods like resourceTerm() or - * getMoreResources(). - * - * \warning DynamicResourceFacet will create a local event loop in order to show a dialog when - * the user wants to search for more resource candidates. - * - * \author Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUKUTILS_EXPORT DynamicResourceFacet : public Facet - { - Q_OBJECT - - public: - /** - * Create a new empty facet. - */ - DynamicResourceFacet( QObject* parent = 0 ); - - /** - * Destructor - */ - virtual ~DynamicResourceFacet(); - - /** - * \return The currently selected Term. Depending on the - * selectionMode() this is either a single Term, a combination - * through Query::AndTerm, or a combination through Query::OrTerm. - */ - Query::Term queryTerm() const; - - /** - * Set the selection mode to use in this facet. The default is MatchAny. - */ - void setSelectionMode( SelectionMode mode ); - - /** - * The selection mode set via setSelectionMode() - */ - SelectionMode selectionMode() const; - - /** - * \return The number of choices in the facet. - */ - int count() const; - - /** - * The parameters used to render the choice at \p index. - */ - KGuiItem guiItem( int index ) const; - - /** - * \return \p true if the choice at \p index is selected, \p false otherwise. - */ - bool isSelected( int index ) const; - - /** - * Set the property to use in the facet. - */ - void setRelation( const Types::Property& prop ); - - /** - * This is optional and defaults to the property's - * range if not set. - */ - void setResourceType( const Types::Class& type ); - - /** - * Set the maximum rows to show by default. Further resources - * are accessible through a search dialog. - * By default the number of max rows is 5. - */ - void setMaxRows( int max ); - - /** - * \return The property set via setRelation() - */ - Types::Property relation() const; - - /** - * \return The resource type set via setResourceType() or the range - * of relation() in case no specific resource type was set. - */ - Types::Class resourceType() const; - - /** - * \return The number of maximum rows set via setMaxRows(). - */ - int maxRows() const; - - /** - * \return The resource that is represented by the choice at index - * \p i or an invalid Resource in case \i is out of bounds or points - * to the "more" action. - */ - Nepomuk::Resource resourceAt( int i ) const; - - /** - * \return The currently selected resources. - */ - QList selectedResources() const; - - public Q_SLOTS: - /** - * Clear the selection. If selectionMode() is MatchOne the first - * choice will be selected. - */ - void clearSelection(); - - /** - * Select or deselect the resource at \p index. - */ - void setSelected( int index, bool selected = true ); - - /** - * Select or deselect \p res. If \p res is not of the correct type - * nothing happens. - */ - void setSelected( const Nepomuk::Resource& res, bool selected = true ); - - /** - * The \p term is analyzed depending on the selectionMode(). - * - * \sa Facet::selectFromTerm() - */ - bool selectFromTerm( const Nepomuk::Query::Term& queryTerm ); - - protected: - /** - * Construct the query that will be used to determine the resources that - * are presented as choices in the facet. - * - * The default implementation uses resourceType() in combination with \p clientQuery - * to determine the resources that can actually change the final query results. - * - * \param clientQuery The query set via setClientQuery(). Reimplementations should - * use this to restrict the query to resources that actually change the final - * query results. - * - * Reimplementations might also call the default implementation to simply add - * additional restrictions to the query like so: - * - * \code - * Query::Query query = DynamicResourceFacet::resourceQuery( clientQuery ); - * query.setTerm( query.term() && myFancyQueryTerm ); - * \endcode - * - * \return The query that is used to fetch resources to be provided as choices - * in this facet. - */ - virtual Query::Query resourceQuery( const Query::Query& clientQuery ) const; - - /** - * Used by term() to construct the final query term this facet provides. - * Reimplementing this method allows to customize the way the term is built. - * - * The default implementation uses relation() in a Query::ComparisonTerm. - * - * When reimplementing this method resourceForTerm() also needs to be reimplemented. - */ - virtual Nepomuk::Query::Term termForResource( const Resource& res ) const; - - /** - * Used by selectFromTerm() to convert terms into resources. - * This is the counterpart to termForResource(). The default implementation checks - * if \p term is a Query::ComparisonTerm which uses relation(). - * - * When reimplementing this method termForResource() also needs to be reimplemented. - * - * \return The resource that is represented by \p term if the latter has the form - * as terms generated by termForResource(), an invalid Resource otherwise. - */ - virtual Nepomuk::Resource resourceForTerm( const Nepomuk::Query::Term& queryTerm ) const; - - /** - * Used to query additional resources if maxRows() is too small to fit all - * candidates. - * - * The default implementation simply uses SearchWidget to let the user query - * additional resources. - * - * \warning The default implementation opens a dialog which will start a local - * event loop. - * - * Reimplementations may use clientQuery() to optimize the resource selection. - * - * \return The list of resources that should be selected in addition to the - * already selected ones. - */ - virtual QList getMoreResources() const; - - /** - * Reimplemented to properly update the resource list on client query change. - */ - void handleClientQueryChange(); - -#ifdef BUILDING_NEPOMUK_TESTS - protected: -#else - private: -#endif - class Private; - Private* d; - - Q_PRIVATE_SLOT( d, void _k_newEntries( const QList& ) ) - Q_PRIVATE_SLOT( d, void _k_populateFinished() ) - }; - } -} - -#endif diff --git a/nepomuk/utils/dynamicresourcefacet_p.h b/nepomuk/utils/dynamicresourcefacet_p.h deleted file mode 100644 index 47919c78..00000000 --- a/nepomuk/utils/dynamicresourcefacet_p.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_DYNAMIC_RESOURCE_FACET_P_H_ -#define _NEPOMUK_QUERY_DYNAMIC_RESOURCE_FACET_P_H_ - -#include "dynamicresourcefacet.h" - -#include "query.h" -#include "queryserviceclient.h" -#include "property.h" -#include "class.h" -#include "resource.h" -#include "result.h" - -#include - -#ifdef Q_OS_WIN -#include "nepomukutils_export.h" - -class NEPOMUKUTILS_EXPORT Nepomuk::Utils::DynamicResourceFacet::Private -#else -class Nepomuk::Utils::DynamicResourceFacet::Private -#endif -{ -public: - Private() - : m_selectionMode(Facet::MatchAny), - m_maxRows( 5 ), - m_haveMore( false ) { - } - virtual ~Private() { - } - - Types::Class resourceType() const { - if ( m_resourceType.isValid() ) - return m_resourceType; - else - return m_property.range(); - } - - /// rebuild the choices from the query, optionally clearing the selection - void rebuild( bool clearSelection = true ); - - /// actually run the query in rebuild - this is virtual only for the unit test - virtual void startQuery( const Query::Query& query ); - - /// add a resource to the list of choices if it is not already in - void addResource( const Nepomuk::Resource& res ); - - void _k_newEntries( const QList& ); - void _k_populateFinished(); - - Query::QueryServiceClient m_queryClient; - - Facet::SelectionMode m_selectionMode; - Types::Property m_property; - Types::Class m_resourceType; - int m_maxRows; - bool m_haveMore; - - /// The query which the client is currently using and which we use - /// to select a subset of resources that make sense - Query::Query m_currentQuery; - - // list of resources built by rebuild() - QList m_resources; - - QSet m_selectedResources; - - DynamicResourceFacet* q; -}; - -#endif diff --git a/nepomuk/utils/facet.cpp b/nepomuk/utils/facet.cpp deleted file mode 100644 index 258c5835..00000000 --- a/nepomuk/utils/facet.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "facet.h" -#include "simplefacet.h" -#include "dynamicresourcefacet.h" -#include "datefacet.h" -#include "typefacet.h" - -#include - -#include "standardqueries.h" -#include "andterm.h" -#include "orterm.h" -#include "comparisonterm.h" -#include "literalterm.h" -#include "resourceterm.h" -#include "resourcetypeterm.h" -#include "query.h" - -#include "tag.h" -#include "property.h" - -#include "tmo.h" -#include "nmo.h" -#include "nco.h" -#include "nfo.h" -#include "nie.h" - -#include "kguiitem.h" -#include "kdebug.h" - -using namespace Nepomuk::Query; - - -class Nepomuk::Utils::Facet::FacetPrivate -{ -public: - Query::Query m_clientQuery; -}; - - -Nepomuk::Utils::Facet::Facet( QObject* parent ) - : QObject( parent ), - d(new FacetPrivate()) -{ -} - - -Nepomuk::Utils::Facet::~Facet() -{ - delete d; -} - - -QString Nepomuk::Utils::Facet::text( int index ) const -{ - return guiItem( index ).text(); -} - - -KGuiItem Nepomuk::Utils::Facet::guiItem( int index ) const -{ - Q_UNUSED(index); - return KGuiItem(); -} - - -void Nepomuk::Utils::Facet::setQueryTermChanged() -{ - emit queryTermChanged( this, queryTerm() ); -} - - -void Nepomuk::Utils::Facet::setLayoutChanged() -{ - emit layoutChanged( this ); -} - - -void Nepomuk::Utils::Facet::setSelectionChanged() -{ - emit selectionChanged( this ); -} - - -void Nepomuk::Utils::Facet::setClientQuery( const Nepomuk::Query::Query& query ) -{ - kDebug() << query; - if( query != d->m_clientQuery ) { - d->m_clientQuery = query; - handleClientQueryChange(); - } -} - - -Nepomuk::Query::Query Nepomuk::Utils::Facet::clientQuery() const -{ - return d->m_clientQuery; -} - - -void Nepomuk::Utils::Facet::handleClientQueryChange() -{ - // do nothing -} - - -// static -Nepomuk::Utils::Facet* Nepomuk::Utils::Facet::createFileTypeFacet( QObject* parent ) -{ - SimpleFacet* facetTypes = new SimpleFacet( parent ); - facetTypes->setSelectionMode( Facet::MatchAny ); - facetTypes->addTerm( i18nc("@option:check A filter on file type", "Documents"), - ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Document()) ); - - // need to check the mimetype as well since strigi is still not perfect - facetTypes->addTerm( i18nc("@option:check A filter on file type - audio files", "Audio"), - ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(), LiteralTerm(QLatin1String("audio"))) ); - facetTypes->addTerm( i18nc("@option:check A filter on file type - media video", "Video"), - ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(), LiteralTerm(QLatin1String("video"))) ); - - facetTypes->addTerm( i18nc("@option:check A filter on file type", "Images"), - ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Image()) ); - return facetTypes; -} - - -// static -Nepomuk::Utils::Facet* Nepomuk::Utils::Facet::createTypeFacet( QObject* parent ) -{ - return new TypeFacet( parent ); -} - - -// static -Nepomuk::Utils::Facet* Nepomuk::Utils::Facet::createDateFacet( QObject* parent ) -{ - return new DateFacet( parent ); -} - - -// static -Nepomuk::Utils::Facet* Nepomuk::Utils::Facet::createTagFacet( QObject* parent ) -{ - DynamicResourceFacet* facetTags = new DynamicResourceFacet( parent ); - facetTags->setSelectionMode( Facet::MatchAll ); - facetTags->setRelation( Soprano::Vocabulary::NAO::hasTag() ); - facetTags->setResourceType( Soprano::Vocabulary::NAO::Tag() ); - return facetTags; -} - - -// static -Nepomuk::Utils::Facet* Nepomuk::Utils::Facet::createPriorityFacet( QObject* parent ) -{ - SimpleFacet* priorityFacet = new SimpleFacet( parent ); - priorityFacet->setSelectionMode(Facet::MatchOne); - priorityFacet->addTerm( i18nc("@option:radio A filter on prioritizing/sorting a selection of resources", "No priority"), Term() ); - priorityFacet->addTerm( i18nc("@option:radio A filter on prioritizing/sorting a selection of resources", "Last modified"), standardQuery( LastModifiedFilesQuery ).term() ); - priorityFacet->addTerm( i18nc("@option:radio A filter on prioritizing/sorting a selection of resources", "Most important"), standardQuery( MostImportantResourcesQuery ).term() ); - priorityFacet->addTerm( i18nc("@option:radio A filter on prioritizing/sorting a selection of resources", "Never opened"), standardQuery( NeverOpenedFilesQuery ).term() ); - return priorityFacet; -} - - -// static -Nepomuk::Utils::Facet* Nepomuk::Utils::Facet::createRatingFacet( QObject* parent ) -{ - SimpleFacet* facet = new SimpleFacet(parent); - facet->setSelectionMode(Facet::MatchOne); - facet->addTerm( i18nc("@option:radio A filter on the rating of a resource", "Any Rating"), Term() ); - facet->addTerm( i18nc("@option:radio A filter on the rating of a resource", "1 or more"), Soprano::Vocabulary::NAO::numericRating() >= LiteralTerm( 1.5 ) ); - facet->addTerm( i18nc("@option:radio A filter on the rating of a resource", "2 or more"), Soprano::Vocabulary::NAO::numericRating() >= LiteralTerm( 3.5 ) ); - facet->addTerm( i18nc("@option:radio A filter on the rating of a resource", "3 or more"), Soprano::Vocabulary::NAO::numericRating() >= LiteralTerm( 5.5 ) ); - facet->addTerm( i18nc("@option:radio A filter on the rating of a resource", "4 or more"), Soprano::Vocabulary::NAO::numericRating() >= LiteralTerm( 7.5 ) ); - facet->addTerm( i18nc("@option:radio A filter on the rating of a resource", "Max Rating"), Soprano::Vocabulary::NAO::numericRating() >= LiteralTerm( 9.5 ) ); - return facet; -} - -#include "facet.moc" diff --git a/nepomuk/utils/facet.h b/nepomuk/utils/facet.h deleted file mode 100644 index da2c7057..00000000 --- a/nepomuk/utils/facet.h +++ /dev/null @@ -1,318 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_FACET_H_ -#define _NEPOMUK_QUERY_FACET_H_ - -#include - -#include "nepomukutils_export.h" - -class KGuiItem; - -namespace Nepomuk { - namespace Query { - class Term; - class Query; - } - - namespace Utils { - /** - * \class Facet facet.h Nepomuk/Utils/Facet - * - * \ingroup nepomuk_facets - * - * \brief The base class for all facets used to create query filters. - * - * A Facet represents one aspect of a query like the resource type or - * the modification date. By providing a list of facets to the user they - * can interactively construct a query by restricting the result set step - * by step. - * - * A Facet can be seen as a list of choices presented to the user. Depending - * on the selection (which is typically triggered by user interaction) the - * Facet produces a resulting term() which is then used in the final query. - * - * Each facet needs to implement a set of methods describing the choices: - * count(), guiItem(), isSelected(), setSelected(), and clearSelection(). - * In addition the term() method constructs the term this facet represents - * with its current selection. - * - * Methods selectFromTerm() and setClientQuery() are optional but allow for a - * more advanced usage and a better user experience. See the method documentation - * for details. - * - * Before implementing your own Facet subclass make sure that SimpleFacet or - * DynamicResourceFacet do not suit your needs. - * - * Facet also provides a set of static factory methods like createTagFacet() or - * createFileTypeFacet() to create standard facets that are useful in most - * query UI situations. - * - * \author Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUKUTILS_EXPORT Facet : public QObject - { - Q_OBJECT - - public: - /** - * Constructor - */ - Facet( QObject* parent = 0 ); - - /** - * Destructor - */ - virtual ~Facet(); - - /** - * A Facet can have one of three selection modes which is provided - * by selectionMode(). - */ - enum SelectionMode { - /** - * All of the choices need to be matched. This typically - * means that all choices' terms are combined using an - * AndTerm. - */ - MatchAll, - - /** - * At least one of the choices needs to be matched. This typically - * means that all choices' terms are combined using an - * OrTerm. - */ - MatchAny, - - /** - * Exactly one of the choices needs to match. This means - * that the Facet is exclusive, ie. only one choice - * can be selected at all times. - */ - MatchOne - }; - - /** - * The selection mode used by this facet. The GUI client - * can make use of this value to adjust the GUI accordingly. - * A typical example would be using radio buttons for - * MatchOne facets. - */ - virtual SelectionMode selectionMode() const = 0; - - /** - * The term currently produced by this facet. This is dependant - * on the subclass implementation and the selectionMode(). The SimpleFacet for example - * uses an AndTerm or an OrTerm to combine all its terms in MatchAll or MatchAny - * mode while it returns the one selected term in MatchOne mode. - */ - virtual Query::Term queryTerm() const = 0; - - /** - * The number of choices this facet provides. - */ - virtual int count() const = 0; - - /** - * The text to be displayed at \p index. The default implementation makes - * use of guiItem(). Normally subclasses would implement guItem() instead - * of this method. - */ - virtual QString text( int index ) const; - - /** - * The parameters used to render the choice at \p index. - */ - virtual KGuiItem guiItem( int index ) const; - - /** - * \return \p true if the choice at \p index is selected, \p false otherwise. - */ - virtual bool isSelected( int index ) const = 0; - - /** - * The client query set via setClientQuery(). See the documentation of setClientQuery() - * for details. - */ - Query::Query clientQuery() const; - - /** - * Creates a new Facet that allows to filter on the file type. Normally - * this facet would be used in combination with a FileQuery. - * \sa createTypeFacet() - */ - static Facet* createFileTypeFacet( QObject* parent = 0 ); - - /** - * Creates a new Facet that allows to filter on the resource type without - * a restriction to files. - * \sa createFileTypeFacet() - */ - static Facet* createTypeFacet( QObject* parent = 0 ); - - /** - * Creates a new Facet that allows to filter on the date. This includes - * the modification, creation, and access dates. - * \sa Query::dateRangeQuery() - */ - static Facet* createDateFacet( QObject* parent = 0 ); - - /** - * Creates a new Facet that allows to filter on tags, i.e. search for - * resources that are tagged with the selected tags. The list of tags - * is dynamic. This means it has a default selection of the most often - * used ones and provides a means to access all tags through a dialog. - */ - static Facet* createTagFacet( QObject* parent = 0 ); - - /** - * Creates a new Facet that allows to sort the results by one of several - * criteria like last modification date or a score calculated by the - * %Nepomuk system. - * Using this facet does only make sense when displaying sorted results - * or when using a limit on the number of results. - */ - static Facet* createPriorityFacet( QObject* parent = 0 ); - - /** - * Creates a new Facet that allows to filter on the rating of resources. - */ - static Facet* createRatingFacet( QObject* parent = 0 ); - - public Q_SLOTS: - /** - * Clear the selection. If selectionMode() is MatchOne the first - * choice should be selected. - */ - virtual void clearSelection() = 0; - - /** - * Called by client code to change the selection. - * - * \param index The index of the choice for which the selection should - * be changed. - * \param selected If \p true the item should be selected, otherwise - * it should be deselected. - */ - virtual void setSelected( int index, bool selected = true ) = 0; - - /** - * If a client application provides several ways to construct a query - * (one could think of a query editor which allows to insert certain - * constraints or simply another application providing a base query) - * the user expects to be able to modify that query using the available - * facets. Thus, a Facet should be able to extract parts from a query. - * - * Implement this method to create a selection based on the contents of - * \p term. The selection of the facet must only change if all of \p term - * can be used. This means that if \p term is for example an OrTerm and - * the Facet can only handle one of the sub terms it needs to ignore the - * whole term. FacetModel::setQuery() internally calls selectFromTerm() - * on all its facets. - * - * A simple example is SimpleFacet which compares all its terms which have been - * added via SimpleFacet::addTerm() to \p term. Depending on the selectionMode() - * it also checks for AndTerm or OrTerm. - * - * \warning Implementations of this method should \em never reset the selection - * before handling \p term. Instead the method should work similar to setSelected(), - * ie. in MatchAll or MatchAny facets calling it multiple times should select - * multiple choices. - * - * \return \p true if all of \p term could be used to select choices in - * this term, \p false otherwise. - */ - virtual bool selectFromTerm( const Nepomuk::Query::Term& queryTerm ) = 0; - - /** - * The FacetModel will set this to the final query that has been constructed - * from the facets and any other query part set by the client via FacetModel::setClientQuery(). - * The facet may use this information to filter the presented choices. A typical example - * is to only show terms that would actually change the result set. The latter is what - * DynamicResourceFacet does. - */ - void setClientQuery( const Nepomuk::Query::Query& query ); - - Q_SIGNALS: - /** - * Emitted when the term of the facet changed, ie. when the value returned by term() - * has changed. - * - * Subclasses should call setTermChanged() instead of emitting this signal manually. - * - * Be aware that in most situations queryTermChanged() and selectionChanged() will - * have to be emitted at the same time. - */ - void queryTermChanged( Nepomuk::Utils::Facet* facet, const Nepomuk::Query::Term& queryTerm ); - - /** - * Emitted when the layout of the facet changed, ie. one of count(), guitItem(), or - * text() return different values. - * - * Subclasses should call setLayoutChanged() instead of emitting this signal manually. - */ - void layoutChanged( Nepomuk::Utils::Facet* facet ); - - /** - * Emitted when the selection changed - normally triggered by a call to setSelected(). - * - * Subclasses should call setSelectionChanged() instead of emitting this signal manually. - * - * Be aware that in most situations queryTermChanged() and selectionChanged() will - * have to be emitted at the same time. - */ - void selectionChanged( Nepomuk::Utils::Facet* facet ); - - protected Q_SLOTS: - /** - * Subclasses should call this method instead of emitting termChanged() manually. - */ - void setQueryTermChanged(); - - /** - * Subclasses should call this method instead of emitting layoutChanged() manually. - */ - void setLayoutChanged(); - - /** - * Subclasses should call this method instead of emitting selectionChanged() manually. - */ - void setSelectionChanged(); - - protected: - /** - * This method is called from setClientQuery() and can be reimplemented by subclasses. - * - * The default implementation does nothing. - */ - virtual void handleClientQueryChange(); - - private: - class FacetPrivate; - FacetPrivate* const d; - }; - } -} - -#endif diff --git a/nepomuk/utils/facetdelegate.cpp b/nepomuk/utils/facetdelegate.cpp deleted file mode 100644 index 539e30c0..00000000 --- a/nepomuk/utils/facetdelegate.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - - -#include "facetdelegate.h" -#include "facet.h" -#include "facetmodel.h" - -#include -#include -#include - -Nepomuk::Utils::FacetDelegate::FacetDelegate( QObject* parent ) - : QItemDelegate( parent ), - m_isExclusive( false ) -{ -} - -Nepomuk::Utils::FacetDelegate::~FacetDelegate() -{ -} - -void Nepomuk::Utils::FacetDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const -{ - // hacky way to not paint anything on title items which we use as spacers for now - if( index.data(Qt::DisplayRole).toString().isEmpty() ) { - return; - } - - const QAbstractProxyModel* proxyModel = qobject_cast(index.model()); - const Facet* facet = proxyModel->data( index, FacetModel::FacetRole ).value(); - if( facet ) { - m_isExclusive = ( facet->selectionMode() == Facet::MatchOne ); - } - - QItemDelegate::paint( painter, option, index ); -} - -void Nepomuk::Utils::FacetDelegate::drawCheck( QPainter* painter, const QStyleOptionViewItem& option, const QRect& rect, Qt::CheckState state ) const -{ - if( m_isExclusive ) { - const QStyleOptionViewItemV3 *v3 = qstyleoption_cast( &option ); - const QWidget* widget = v3 ? v3->widget : 0; - - QStyleOptionViewItem opt(option); - opt.rect = rect; - opt.state = opt.state & ~QStyle::State_HasFocus; - - switch( state ) { - case Qt::Unchecked: - opt.state |= QStyle::State_Off; - break; - case Qt::PartiallyChecked: - opt.state |= QStyle::State_NoChange; - break; - case Qt::Checked: - opt.state |= QStyle::State_On; - break; - } - - QStyle *style = widget ? widget->style() : QApplication::style(); - style->drawPrimitive( QStyle::PE_IndicatorRadioButton, &opt, painter, widget ); - } - else { - QItemDelegate::drawCheck( painter, option, rect, state ); - } -} diff --git a/nepomuk/utils/facetdelegate.h b/nepomuk/utils/facetdelegate.h deleted file mode 100644 index cd4e7cc5..00000000 --- a/nepomuk/utils/facetdelegate.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - - -#ifndef NEPOMUK_QUERY_FACETDELEGATE_H -#define NEPOMUK_QUERY_FACETDELEGATE_H - -#include - - -namespace Nepomuk { - namespace Utils { - class FacetDelegate : public QItemDelegate - { - public: - explicit FacetDelegate( QObject* parent = 0 ); - virtual void paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const; - virtual ~FacetDelegate(); - - protected: - virtual void drawCheck( QPainter* painter, const QStyleOptionViewItem& option, const QRect& rect, Qt::CheckState state ) const; - - private: - mutable bool m_isExclusive; - }; - } -} - -#endif // NEPOMUK_QUERY_FACETDELEGATE_H diff --git a/nepomuk/utils/facetfiltermodel.cpp b/nepomuk/utils/facetfiltermodel.cpp deleted file mode 100644 index e636a89a..00000000 --- a/nepomuk/utils/facetfiltermodel.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "facetfiltermodel.h" -#include "facet.h" -#include "facetmodel.h" - -Nepomuk::Utils::FacetFilterModel::FacetFilterModel(QObject *parent) - : QSortFilterProxyModel(parent), - d(0) -{ -} - - -Nepomuk::Utils::FacetFilterModel::~FacetFilterModel() -{ - //delete d; -} - - -bool Nepomuk::Utils::FacetFilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const -{ - QModelIndex index = sourceModel()->index( source_row, 0, source_parent ); - return index.isValid() && index.data(FacetModel::FacetRole).value()->count() > 0; -} - -#include "facetfiltermodel.moc" diff --git a/nepomuk/utils/facetfiltermodel.h b/nepomuk/utils/facetfiltermodel.h deleted file mode 100644 index 9056563e..00000000 --- a/nepomuk/utils/facetfiltermodel.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef FACETFILTERMODEL_H -#define FACETFILTERMODEL_H - -#include - -namespace Nepomuk { - namespace Utils { - /** - * \class FacetFilterModel facetfiltermodel.h Nepomuk/Utils/FacetFilterModel - * - * \ingroup nepomuk_facets - * - * \brief Filter model that hides irrelevant Facets from a FacetModel. - * - * \author Sebastian Trueg - */ - class FacetFilterModel : public QSortFilterProxyModel - { - Q_OBJECT - - public: - FacetFilterModel(QObject *parent = 0); - ~FacetFilterModel(); - - protected: - bool filterAcceptsRow( int source_row, const QModelIndex& source_parent ) const; - - private: - class Private; - Private* const d; - }; - } -} - -#endif // FACETFILTERMODEL_H diff --git a/nepomuk/utils/facetmodel.cpp b/nepomuk/utils/facetmodel.cpp deleted file mode 100644 index 30177c23..00000000 --- a/nepomuk/utils/facetmodel.cpp +++ /dev/null @@ -1,410 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "facetmodel.h" -#include "simplefacet.h" -#include "dynamicresourcefacet.h" -#include "datefacet.h" -#include "facet.h" - -#include - -#include - -#include "query.h" -#include "andterm.h" -#include "orterm.h" -#include "comparisonterm.h" -#include "literalterm.h" -#include "resourceterm.h" -#include "resourcetypeterm.h" -#include "andterm.h" -#include "standardqueries.h" -#include "tag.h" - -#include "tmo.h" -#include "nmo.h" -#include "nco.h" -#include "nfo.h" -#include "nie.h" - -#include "kdebug.h" -#include "kglobal.h" -#include "klocale.h" -#include "kcalendarsystem.h" -#include "kguiitem.h" - -using namespace Nepomuk::Query; - - -class Nepomuk::Utils::FacetModel::Private -{ -public: - QList m_facets; - - bool m_blockQueryTermChangedSignal; - - void addFacet( Facet* facet ); - QModelIndex parentIndexForFacet( Facet* facet ) const; - - void handleFacetsChanged(); - - void _k_queryTermChanged(); - void _k_facetSelectionChanged( Nepomuk::Utils::Facet* facet ); - void _k_facetLayoutChanged( Nepomuk::Utils::Facet* ); - - FacetModel* q; -}; - - -void Nepomuk::Utils::FacetModel::Private::addFacet( Facet* facet ) -{ - q->connect(facet, SIGNAL(queryTermChanged(Nepomuk::Utils::Facet*,Nepomuk::Query::Term)), - SLOT(_k_queryTermChanged()) ); - q->connect(facet, SIGNAL(selectionChanged(Nepomuk::Utils::Facet*)), - SLOT(_k_facetSelectionChanged(Nepomuk::Utils::Facet*)) ); - q->connect(facet, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*)), - SLOT(_k_facetLayoutChanged(Nepomuk::Utils::Facet*)) ); - m_facets.append(facet); -} - - -QModelIndex Nepomuk::Utils::FacetModel::Private::parentIndexForFacet( Facet* facet ) const -{ - const int i = m_facets.indexOf( facet ); - return q->index( i, 0, QModelIndex() ); -} - - -void Nepomuk::Utils::FacetModel::Private::handleFacetsChanged() -{ - if( !m_blockQueryTermChangedSignal ) - emit q->queryTermChanged( q->queryTerm() ); -} - - -void Nepomuk::Utils::FacetModel::Private::_k_queryTermChanged() -{ - handleFacetsChanged(); -} - - -void Nepomuk::Utils::FacetModel::Private::_k_facetSelectionChanged( Nepomuk::Utils::Facet* facet ) -{ - kDebug(); - QModelIndex parent = parentIndexForFacet( facet ); - if( facet->count() ) - emit q->dataChanged( q->index( 0, 0, parent ), q->index( q->rowCount(parent)-1, 0, parent ) ); -} - - -void Nepomuk::Utils::FacetModel::Private::_k_facetLayoutChanged( Nepomuk::Utils::Facet* ) -{ - // sadly we do not know the differences - q->reset(); -} - - -Nepomuk::Utils::FacetModel::FacetModel( QObject* parent ) - : QAbstractItemModel( parent ), - d(new Private() ) -{ - d->q = this; - d->m_blockQueryTermChangedSignal = false; -} - - -Nepomuk::Utils::FacetModel::~FacetModel() -{ - qDeleteAll( d->m_facets ); - delete d; -} - - -int Nepomuk::Utils::FacetModel::columnCount( const QModelIndex& ) const -{ - return 1; -} - - -QVariant Nepomuk::Utils::FacetModel::data( const QModelIndex& index, int role ) const -{ - if( index.isValid() ) { - if( index.internalPointer() ) { - Facet* facet = static_cast( index.internalPointer() ); - - if ( role == FacetRole ) - return QVariant::fromValue( facet ); - - switch( role ) { - case Qt::DisplayRole: { - QString title = facet->text(index.row()); - return title; - } - case Qt::CheckStateRole: - return( facet->isSelected(index.row()) ? Qt::Checked : Qt::Unchecked ); - } - } - else { - switch( role ) { - case FacetRole: - return QVariant::fromValue( d->m_facets[index.row()] ); - -// case Qt::DisplayRole: -// return d->m_facets[index.row()]->facet().title(); - } - } - } - - return QVariant(); -} - - -bool Nepomuk::Utils::FacetModel::setData( const QModelIndex& index, const QVariant& value, int role ) -{ - if( role == Qt::CheckStateRole && index.internalPointer() ) { - Facet* facet = static_cast( index.internalPointer() ); - facet->setSelected( index.row(), value.toBool() ); - return true; - } - else { - return false; - } -} - - -bool Nepomuk::Utils::FacetModel::hasChildren( const QModelIndex& parent ) const -{ - // facet terms don't have children - if( parent.internalPointer() ) { - return false; - } - else { - return rowCount(parent) > 0; - } -} - - -QModelIndex Nepomuk::Utils::FacetModel::parent( const QModelIndex& index ) const -{ - if( index.internalPointer() ) { - return d->parentIndexForFacet( static_cast( index.internalPointer() ) ); - } - else { - return QModelIndex(); - } -} - - -int Nepomuk::Utils::FacetModel::rowCount( const QModelIndex& parent ) const -{ - if( !parent.isValid() ) { - return d->m_facets.count(); - } - else if( parent.row() < d->m_facets.count() ) { - return d->m_facets[parent.row()]->count(); - } - else { - return 0; - } -} - - -QModelIndex Nepomuk::Utils::FacetModel::index( int row, int column, const QModelIndex& parent ) const -{ - if(row < 0 || row >= rowCount(parent) || column < 0 || column >= columnCount(parent)) { - return QModelIndex(); - } - if( parent.isValid() ) { - return createIndex( row, column, d->m_facets[parent.row()] ); - } - else { - return createIndex( row, column ); - } -} - - -Qt::ItemFlags Nepomuk::Utils::FacetModel::flags( const QModelIndex& index ) const -{ - if(!index.isValid()) { - return Qt::NoItemFlags; - } - // we do not even allow selection since that does not make much sense for our use case - Qt::ItemFlags flags = Qt::ItemIsEnabled; - if( index.internalPointer() ) { - flags |= Qt::ItemIsUserCheckable; - } - return flags; -} - - -void Nepomuk::Utils::FacetModel::addFacet( Facet* facet ) -{ - d->addFacet( facet ); - reset(); - d->handleFacetsChanged(); - // TODO: do not use reset but the fancy begin/end methods -} - - -void Nepomuk::Utils::FacetModel::setFacets( const QList& facets ) -{ - clear(); - Q_FOREACH( Facet* facet, facets ) { - d->addFacet( facet ); - } - reset(); - d->handleFacetsChanged(); -} - - -void Nepomuk::Utils::FacetModel::clearSelection() -{ - d->m_blockQueryTermChangedSignal = true; - Q_FOREACH( Facet* facet, d->m_facets ) { - facet->clearSelection(); - } - d->m_blockQueryTermChangedSignal = false; - d->handleFacetsChanged(); -} - - -void Nepomuk::Utils::FacetModel::clear() -{ - qDeleteAll(d->m_facets); - d->m_facets.clear(); - reset(); -} - - -QList Nepomuk::Utils::FacetModel::facets() const -{ - return d->m_facets; -} - - -Nepomuk::Query::Term Nepomuk::Utils::FacetModel::queryTerm() const -{ - AndTerm term; - Q_FOREACH( Facet* facet, d->m_facets ) { - term.addSubTerm( facet->queryTerm() ); - } - return term.optimized(); -} - - -Nepomuk::Query::Query Nepomuk::Utils::FacetModel::extractFacetsFromQuery( const Nepomuk::Query::Query& query ) -{ - // safety net to prevent endless loops - // =============================== - if ( query.term() == queryTerm() ) { - Query::Query rest(query); - rest.setTerm(Query::Term()); - return rest; - } - - // we do not want to emit any queryTermChanged() signal during this method - // as it would confuse client code - // ================================ - d->m_blockQueryTermChangedSignal = true; - - // reset all facets in the model - // ================================ - Q_FOREACH( Facet* f, d->m_facets ) { - f->clearSelection(); - } - - // we extract all facets we can find and leave the rest in the query - // ================================ - Query::Query restQuery = query.optimized(); - Term restTerm = restQuery.term(); - - // Step one is to use the term in question as the client query for all facets - // this is necessary since otherwise facets like ProxyFacet will ignore all - // calls to selectFromTerm(). The client query can later be reset by the client. - // it is not wrong but may be only part of the actual client query. - setClientQuery( restQuery ); - - // first we check if the main term is already a facet term - // (this way we can also handle facets that use AndTerms) - // ================================ - - // if any of the facets contains the term, set it to selected - Q_FOREACH( Facet* f, d->m_facets ) { - if( f->selectFromTerm( restTerm ) ) { - restTerm = Term(); - break; - } - } - - // now go into an AndTerm and check each sub term for facet - // ================================ - if( restTerm.isAndTerm() ) { - // we need to cache the facets since we cannot use MatchOne facets more than once - QList facets = d->m_facets; - - AndTerm restAndTerm; - foreach( const Term& term, restTerm.toAndTerm().subTerms() ) { - bool termFound = false; - - Q_FOREACH( Facet* f, facets ) { - if( f->selectFromTerm( term ) ) { - termFound = true; - // we can only use MatchAll facets more than once - // Example: we have an exclusive facet that can handle both term A and B - // we now call selectFromTerm(A) and selectFromTerm(B) - // both return true but only the latter is the one that sticks. - // thus, we implicitely drop A from the query! - // None-exclusive facets are not a problem as they simply add to their - // existing selection. - if( f->selectionMode() != Facet::MatchAll ) - facets.removeAll(f); - break; - } - } - - // we did not find a matching facet - if( !termFound ) - restAndTerm.addSubTerm( term ); - } - - restTerm = restAndTerm; - } - - // done with the facet selection - // ================================ - d->m_blockQueryTermChangedSignal = false; - - d->handleFacetsChanged(); - - restQuery.setTerm(restTerm); - return restQuery.optimized(); -} - - -void Nepomuk::Utils::FacetModel::setClientQuery( const Nepomuk::Query::Query& query ) -{ - Q_FOREACH( Facet* facet, d->m_facets ) { - facet->setClientQuery( query ); - } -} - -#include "facetmodel.moc" diff --git a/nepomuk/utils/facetmodel.h b/nepomuk/utils/facetmodel.h deleted file mode 100644 index 9b61aa6b..00000000 --- a/nepomuk/utils/facetmodel.h +++ /dev/null @@ -1,231 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_FACET_MODEL_H_ -#define _NEPOMUK_QUERY_FACET_MODEL_H_ - -#include "query.h" -#include "term.h" -#include "nepomukutils_export.h" - -#include -#include - -namespace Nepomuk { - namespace Utils { - class Facet; - - /** - * \class FacetModel facetmodel.h Nepomuk/Utils/FacetModel - * - * \ingroup nepomuk_facets - * - * \brief A FacetModel contains a list of facets that are provided in a tree structure. - * - * The FacetModel manages a list of Facet instances that are layed out - * in a tree structure in which the leafs are checkable. This allows to - * easily configure the facets by clicking the tree. - * - * Facets are added via setFacets() and addFacet(). - * - * The FacetModel can be used to create and augment queries using the queryTerm() - * method and connecting to the queryTermChanged() signal. In addition %FacetModel - * provides the extractFacetsFromTerm() method which \em converts a query into - * facet selections. This is very convinient if the query comes from another source - * like a query bookmark or another application. - * - * An improved user experience can be created by setting the final query used to - * list the results via setClientQuery(). This allows the %FacetModel to filter - * the available choices, hiding those that do not make sense with the current - * result set or even showing facets that did not make sense before (compare the - * ProxyFacet example in \ref nepomuk_facet_examples). - * - * Typically one would use FacetWidget instead of creating ones own FacetModel. - * - * \author Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUKUTILS_EXPORT FacetModel : public QAbstractItemModel - { - Q_OBJECT - - public: - /** - * Creates an empty facet model - */ - FacetModel( QObject* parent = 0 ); - - /** - * Destructor - */ - ~FacetModel(); - - /** - * Special roles FacetModel provides through data() in - * addition to the standard Qt roles. - * - * \sa Qt::ItemDataRole - */ - enum CustomRoles { - /** - * Provides a pointer to the Facet instance itself. - * Used internally. - */ - FacetRole = 235265643 - }; - - /** - * Reimplemented to provide facet data to Qt's model/view framework. - */ - int columnCount( const QModelIndex& parent = QModelIndex() ) const; - - /** - * Reimplemented to provide facet data to Qt's model/view framework. - */ - QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const; - - /** - * Reimplemented to provide facet data to Qt's model/view framework. - */ - bool setData( const QModelIndex& index, const QVariant& value, int role ); - - /** - * Reimplemented to provide facet data to Qt's model/view framework. - */ - bool hasChildren(const QModelIndex &parent) const; - - /** - * Reimplemented to provide facet data to Qt's model/view framework. - */ - QModelIndex parent( const QModelIndex& index ) const; - - /** - * Reimplemented to provide facet data to Qt's model/view framework. - */ - int rowCount( const QModelIndex& parent = QModelIndex() ) const; - - /** - * Reimplemented to provide facet data to Qt's model/view framework. - */ - QModelIndex index( int row, int column, const QModelIndex& parent = QModelIndex() ) const; - - /** - * Reimplemented to provide facet data to Qt's model/view framework. - */ - Qt::ItemFlags flags( const QModelIndex& index ) const; - - /** - * \return All Facet instances added via addFacet() and setFacets(). - */ - QList facets() const; - - /** - * Construct a query term from the selected facets in this model. - * - * \return A new query which combines the facets in this model. - */ - Query::Term queryTerm() const; - - public Q_SLOTS: - /** - * Extract as many facets from a query as possible. This method is not able to handle all - * kinds of queries but works well on queries created via queryTerm(). - * - * Facets supported by this model will be extracted from \p query and configured - * accordingly in the model. - * - * Be aware that this method is not related to setClientQuery(). It is intended to - * split up a query in order to represent it graphically. It will, however change the - * client query in order to achieve the best possible term extraction. Thus, one would typically - * call setClientQuery after calling this method if \p query does not already contain - * the full client query. - * - * Typically a client would call this method and then try to handle the returned - * rest query in another way like converting it into a desktop user query string - * that can be shown in a search line edit. Another idea would be to use custom - * filters or a simple warning for the user that additional conditions are in place - * that could not be "translated" into facets. - * - * \return The rest query after facets have been extracted. - */ - Nepomuk::Query::Query extractFacetsFromQuery( const Nepomuk::Query::Query& query ); - - /** - * Can be used to set the full query the client is using (this includes facets - * created through this model). It allows the facet system to disable certain - * choices that would not change the result set or do not make sense otherwise. - * - * Be aware that this method is not related to extractFacetsFromTerm(). It is merely - * intended to improve the overall user experienceby filtering the facet choices - * depending on the current query. - * - * Typically a client would call both extractFacetsFromTerm() and setClientQuery() - * seperately. However, they will often be called with the same query/term. - * - * \sa Facet::setClientQuery() - */ - void setClientQuery( const Nepomuk::Query::Query& query ); - - /** - * Add \p facet to the model. Used to populate the model with facets. - * Ownership of \p facet is transferred to the model. - */ - void addFacet( Nepomuk::Utils::Facet* facet ); - - /** - * Set \p facets as the list of facets used in this model. Used to populate the model with facets. - * Ownership of the facets is transferred to the model. - */ - void setFacets( const QList& facets ); - - /** - * Convenience method that clears the selection on all facets. - * \sa Facet::clearSelection() - */ - void clearSelection(); - - /** - * Remove all facets from the model. - */ - void clear(); - - Q_SIGNALS: - /** - * Emitted whenever the facets change, i.e. when the user changes the selection - * or it is changed programmatically via extractFacetsFromQuery() - */ - void queryTermChanged( const Nepomuk::Query::Term& term ); - - private: - class Private; - Private* const d; - - Q_PRIVATE_SLOT( d, void _k_queryTermChanged() ) - Q_PRIVATE_SLOT( d, void _k_facetSelectionChanged( Nepomuk::Utils::Facet* ) ) - Q_PRIVATE_SLOT( d, void _k_facetLayoutChanged( Nepomuk::Utils::Facet* ) ) - }; - } -} - -Q_DECLARE_METATYPE( Nepomuk::Utils::Facet* ) - -#endif diff --git a/nepomuk/utils/facetwidget.cpp b/nepomuk/utils/facetwidget.cpp deleted file mode 100644 index dd4b1f25..00000000 --- a/nepomuk/utils/facetwidget.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* - Copyright (c) 2010 Oszkar Ambrus - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "facetwidget.h" -#include "facetmodel.h" -#include "facet.h" -#include "facetdelegate.h" -#include "facetfiltermodel.h" - -#include -#include -#include -#include -#include -#include - -#include "query.h" -#include "queryparser.h" -#include "result.h" -#include "comparisonterm.h" -#include "resourceterm.h" -#include "resourcetypeterm.h" -#include "resource.h" - -#include - -#include "kdebug.h" -#include "kdescendantsproxymodel.h" - - -class Nepomuk::Utils::FacetWidget::Private -{ -public: - Nepomuk::Utils::FacetModel *m_facetModel; - QListView *m_facetView; -}; - - -Nepomuk::Utils::FacetWidget::FacetWidget( QWidget *parent ) - : QWidget( parent ), - d( new Private() ) -{ - d->m_facetModel = new Nepomuk::Utils::FacetModel( this ); - connect( d->m_facetModel, SIGNAL(queryTermChanged(Nepomuk::Query::Term)), - this, SIGNAL(queryTermChanged(Nepomuk::Query::Term)) ); - - d->m_facetView = new QListView( this ); - d->m_facetView->setItemDelegate( new FacetDelegate( d->m_facetView ) ); - d->m_facetView->setBackgroundRole(QPalette::NoRole); - d->m_facetView->viewport()->setBackgroundRole(QPalette::NoRole); - d->m_facetView->setFrameStyle(QFrame::NoFrame); - - FacetFilterModel* facetFilterModel = new FacetFilterModel( this ); - facetFilterModel->setSourceModel( d->m_facetModel ); - connect( d->m_facetModel, SIGNAL(queryTermChanged(Nepomuk::Query::Term)), facetFilterModel, SLOT(invalidate())); - connect( d->m_facetModel, SIGNAL(modelReset()), facetFilterModel, SLOT(invalidate())); - - KDescendantsProxyModel* proxy = new KDescendantsProxyModel( this ); - proxy->setSourceModel( facetFilterModel ); - d->m_facetView->setModel( proxy ); - - new QVBoxLayout( this ); - layout()->addWidget( d->m_facetView ); -} - -Nepomuk::Utils::FacetWidget::~FacetWidget() -{ - delete d; -} - - -QList Nepomuk::Utils::FacetWidget::facets() const -{ - return d->m_facetModel->facets(); -} - - -Nepomuk::Query::Query Nepomuk::Utils::FacetWidget::extractFacetsFromQuery( const Nepomuk::Query::Query& query ) -{ - return d->m_facetModel->extractFacetsFromQuery( query ); -} - - -Nepomuk::Query::Term Nepomuk::Utils::FacetWidget::queryTerm() const -{ - return d->m_facetModel->queryTerm(); -} - - -void Nepomuk::Utils::FacetWidget::setClientQuery(const Nepomuk::Query::Query& query) -{ - d->m_facetModel->setClientQuery(query); -} - - -void Nepomuk::Utils::FacetWidget::addFacet( Nepomuk::Utils::Facet* facet ) -{ - d->m_facetModel->addFacet(facet); -} - - -void Nepomuk::Utils::FacetWidget::setFacets( const QList& facets ) -{ - d->m_facetModel->setFacets(facets); -} - - -void Nepomuk::Utils::FacetWidget::clear() -{ - d->m_facetModel->clear(); -} - -#include "facetwidget.moc" diff --git a/nepomuk/utils/facetwidget.h b/nepomuk/utils/facetwidget.h deleted file mode 100644 index 8ca07cb0..00000000 --- a/nepomuk/utils/facetwidget.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - Copyright (c) 2010 Oszkar Ambrus - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef FACETSWIDGET_H -#define FACETSWIDGET_H - -#include -#include - -#include "facet.h" -#include "nepomukutils_export.h" - -namespace Nepomuk { - namespace Query { - class Query; - class Term; - } - - namespace Utils { - /** - * \class FacetWidget facetwidget.h Nepomuk/Utils/FacetWidget - * - * \ingroup nepomuk_facets - * - * \brief A widget providing a list of facets to add filters to a query. - * - * The basic usage of FacetWidget is rather simple: create a new instance, - * add facets to it through the addFacet() method, connect to the queryTermChanged() - * signal, and wait for the user to change the filters. - * - * More sophisticated usage involves extractFacetsFromTerm() or setClientQuery(). - * For more details see the documentation of FacetModel which provides a similar - * API since FacetWidget is using it internally. - * - * \author Oszkar Ambrus , Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUKUTILS_EXPORT FacetWidget : public QWidget - { - Q_OBJECT - - public: - /** - * Create a new empty FacetWidget. - */ - FacetWidget( QWidget *parent = 0 ); - - /** - * Destructor - */ - ~FacetWidget(); - - /** - * \return All Facet instances added via addFacet() and setFacets(). - */ - QList facets() const; - - /** - * Extract as many facets from a query as possible. This method is not able to handle all - * kinds of queries but works well on queries created via queryTerm(). - * - * Facets supported by this widget will be extracted from \p term and configured - * accordingly. - * - * \sa FacetModel::extractFacetsFromTerm() - * - * \return The rest term after facets have been extracted. - */ - Nepomuk::Query::Query extractFacetsFromQuery( const Nepomuk::Query::Query& query ); - - /** - * @returns the query term composed by the facets - */ - Nepomuk::Query::Term queryTerm() const; - - /** - * Can be used to set the full query the client is using (this includes facets - * created through this widget). It allows the facet system to disable certain - * choices that would not change the result set or do not make sense otherwise. - * - * \sa FacetModel::setClientQuery() - */ - void setClientQuery( const Nepomuk::Query::Query& query ); - - public Q_SLOTS: - /** - * Add \p facet to the widget. Used to populate the widget with facets. - * Ownership of \p facet is transferred to the widget. - */ - void addFacet( Nepomuk::Utils::Facet* facet ); - - /** - * Set \p facets as the list of facets used in this widget. Used to populate the widget with facets. - * Ownership of the facets is transferred to the widget. - */ - void setFacets( const QList& facets ); - - /** - * Remove all facets from the widget. - */ - void clear(); - - Q_SIGNALS: - /** - * Emitted whenever the facets change, i.e. when the user changes the selection - * or it is changed programmatically via extractFacetsFromQuery() - */ - void queryTermChanged( const Nepomuk::Query::Term& term ); - - private: - class Private; - Private * const d; - }; - } -} - -#endif // FACETSWIDGET_H diff --git a/nepomuk/utils/nepomukutils_export.h b/nepomuk/utils/nepomukutils_export.h deleted file mode 100644 index 718bd7c3..00000000 --- a/nepomuk/utils/nepomukutils_export.h +++ /dev/null @@ -1,40 +0,0 @@ -/* This file is part of the KDE project - Copyright (C) 2007 David Faure - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef NEPOMUKUTILS_EXPORT_H -#define NEPOMUKUTILS_EXPORT_H - -/* needed for KDE_EXPORT and KDE_IMPORT macros */ -#include - -#ifndef NEPOMUKUTILS_EXPORT -# if defined(KDELIBS_STATIC_LIBS) - /* No export/import for static libraries */ -# define NEPOMUKUTILS_EXPORT -# elif defined(MAKE_NEPOMUKUTILS_LIB) - /* We are building this library */ -# define NEPOMUKUTILS_EXPORT KDE_EXPORT -# else - /* We are using this library */ -# define NEPOMUKUTILS_EXPORT KDE_IMPORT -# endif -#endif - -#endif diff --git a/nepomuk/utils/proxyfacet.cpp b/nepomuk/utils/proxyfacet.cpp deleted file mode 100644 index cb9d7b13..00000000 --- a/nepomuk/utils/proxyfacet.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "proxyfacet.h" -#include "andterm.h" -#include "query.h" - -#include "kguiitem.h" -#include "kdebug.h" - -class Nepomuk::Utils::ProxyFacet::Private -{ -public: - Private() - : m_sourceFacet(0), - m_facetConditionMet(true) { - } - - void updateConditionStatus(); - - Facet* m_sourceFacet; - - Query::Term m_facetCondition; - bool m_facetConditionMet; - - ProxyFacet* q; -}; - - -namespace { - /** - * Checks if a query contains a certain term in a non-optional manner. Basically this means - * that either the query's term is the term in question or the query term is an AndTerm which - * contains the requested term. All other situations result in an optional usage of \p term - * or are too complex to handle here. - */ - bool containsTerm( const Nepomuk::Query::Query& query, const Nepomuk::Query::Term& term ) { - Nepomuk::Query::Term queryTerm = query.term().optimized(); - if( queryTerm == term ) { - return true; - } - else if( queryTerm.isAndTerm() ) { - Q_FOREACH( const Nepomuk::Query::Term& subTerm, queryTerm.toAndTerm().subTerms() ) { - if( subTerm == term ) { - return true; - } - } - } - - // fallback - return false; - } -} - -void Nepomuk::Utils::ProxyFacet::Private::updateConditionStatus() -{ - bool newFacetConditionMet = true; - if( m_facetCondition.isValid() ) { - newFacetConditionMet = containsTerm( q->clientQuery(), m_facetCondition ); - kDebug() << m_facetConditionMet << newFacetConditionMet; - } - - if( newFacetConditionMet != m_facetConditionMet ) { - m_facetConditionMet = newFacetConditionMet; - q->setLayoutChanged(); - q->setQueryTermChanged(); - } - - if( !m_facetConditionMet ) { - q->clearSelection(); - } -} - - -Nepomuk::Utils::ProxyFacet::ProxyFacet( QObject* parent ) - : Facet(parent), - d(new Private()) -{ - d->q = this; -} - - -Nepomuk::Utils::ProxyFacet::~ProxyFacet() -{ - delete d; -} - - -void Nepomuk::Utils::ProxyFacet::setSourceFacet( Facet* source ) -{ - if( d->m_sourceFacet ) { - d->m_sourceFacet->disconnect(this); - } - - d->m_sourceFacet = source; - if( d->m_sourceFacet ) { - connect(d->m_sourceFacet, SIGNAL(queryTermChanged(Nepomuk::Utils::Facet*,Nepomuk::Query::Term)), - this, SIGNAL(queryTermChanged(Nepomuk::Utils::Facet*,Nepomuk::Query::Term))); - connect(d->m_sourceFacet, SIGNAL(selectionChanged(Nepomuk::Utils::Facet*)), - this, SIGNAL(selectionChanged(Nepomuk::Utils::Facet*))); - connect(d->m_sourceFacet, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*)), - this, SIGNAL(layoutChanged(Nepomuk::Utils::Facet*))); - } - - setLayoutChanged(); - setQueryTermChanged(); - setSelectionChanged(); -} - - -Nepomuk::Utils::Facet* Nepomuk::Utils::ProxyFacet::sourceFacet() const -{ - return d->m_sourceFacet; -} - - -Nepomuk::Utils::Facet::SelectionMode Nepomuk::Utils::ProxyFacet::selectionMode() const -{ - return d->m_sourceFacet ? d->m_sourceFacet->selectionMode() : MatchOne; -} - - -Nepomuk::Query::Term Nepomuk::Utils::ProxyFacet::queryTerm() const -{ - return facetConditionMet() && d->m_sourceFacet ? d->m_sourceFacet->queryTerm() : Query::Term(); -} - - -int Nepomuk::Utils::ProxyFacet::count() const -{ - return d->m_sourceFacet && facetConditionMet() ? d->m_sourceFacet->count() : 0; -} - - -bool Nepomuk::Utils::ProxyFacet::isSelected( int index ) const -{ - return d->m_sourceFacet ? d->m_sourceFacet->isSelected(index) : false; -} - - -KGuiItem Nepomuk::Utils::ProxyFacet::guiItem( int index ) const -{ - return d->m_sourceFacet ? d->m_sourceFacet->guiItem(index) : KGuiItem(); -} - - -void Nepomuk::Utils::ProxyFacet::setSelected( int index, bool selected ) -{ - if( d->m_sourceFacet && facetConditionMet() ) { - d->m_sourceFacet->setSelected( index, selected ); - } -} - - -void Nepomuk::Utils::ProxyFacet::clearSelection() -{ - if( d->m_sourceFacet ) { - d->m_sourceFacet->clearSelection(); - } -} - - -bool Nepomuk::Utils::ProxyFacet::selectFromTerm( const Nepomuk::Query::Term& term ) -{ - if( d->m_sourceFacet && facetConditionMet() ) { - return d->m_sourceFacet->selectFromTerm( term ); - } - else { - return false; - } -} - - -void Nepomuk::Utils::ProxyFacet::handleClientQueryChange() -{ - d->updateConditionStatus(); - if( d->m_sourceFacet ) { - d->m_sourceFacet->setClientQuery( clientQuery() ); - } -} - - -void Nepomuk::Utils::ProxyFacet::setFacetCondition( const Nepomuk::Query::Term& term ) -{ - d->m_facetCondition = term; - d->updateConditionStatus(); -} - - -bool Nepomuk::Utils::ProxyFacet::facetConditionMet() const -{ - return d->m_facetConditionMet; -} - -#include "proxyfacet.moc" diff --git a/nepomuk/utils/proxyfacet.h b/nepomuk/utils/proxyfacet.h deleted file mode 100644 index 7d6f39b6..00000000 --- a/nepomuk/utils/proxyfacet.h +++ /dev/null @@ -1,160 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_PROXY_FACET_H_ -#define _NEPOMUK_QUERY_PROXY_FACET_H_ - -#include "facet.h" -#include "nepomukutils_export.h" - -namespace Nepomuk { - namespace Utils { - /** - * \class ProxyFacet proxyfacet.h Nepomuk/Utils/ProxyFacet - * - * \ingroup nepomuk_facets - * - * \brief A facet forwarding the filtered choices from another facet. - * - * The ProxyFacet allows to perform filter operations on another facet. - * Most noticable one can set a general condition which needs to be fulfilled - * in the client query in order for the facet to show any choices. - * - * \sa \ref nepomuk_facet_examples - * - * \author Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUKUTILS_EXPORT ProxyFacet : public Facet - { - Q_OBJECT - - public: - /** - * Create a new proxy facet without a source. - */ - ProxyFacet( QObject* parent = 0 ); - - /** - * Destructor. - */ - virtual ~ProxyFacet(); - - /** - * Set the source facet. The proxy will forward all calls to - * \p source. - */ - void setSourceFacet( Facet* source ); - - /** - * The source facet which this proxy facet is forwarding. - * \sa setSourceFacet() - */ - Facet* sourceFacet() const; - - /** - * The selection mode forwarded from the sourceFacet(). - */ - SelectionMode selectionMode() const; - - /** - * The query term forwarded and optionally filtered from the sourceModel(). - */ - virtual Nepomuk::Query::Term queryTerm() const; - - /** - * \return The number of terms forwarded from the sourceFacet(). - */ - int count() const; - - /** - * The gui item forwarded from the sourceFacet(). - */ - KGuiItem guiItem( int index ) const; - - /** - * \return \p true if the term at \p index has been selected via - * setSelected(). - */ - bool isSelected( int index ) const; - - /** - * The facet condition set via setFacetCondition() - */ - Nepomuk::Query::Term facetCondition() const; - - public Q_SLOTS: - /** - * Allows to set a condition for the entire facet. Unless it is not met in the - * client query set via setClientQuery() the facet does not provide any choices. - * - * \param term The condition term. If valid this facet will only show any choices - * if the client query contains \p term in a non-optional way. - * - * A typical example is a facet which filters images by size. In that case the - * condition would be - * \code - * Query::ResourceTypeTerm( Vocabulary::NFO::RasterImage() ); - * \endcode - * since filtering by image size does only make sense if only images are selected. - */ - void setFacetCondition( const Nepomuk::Query::Term& queryTerm ); - - /** - * Clear the selection. If selectionMode() is MatchOne the first - * choice should be selected. - */ - void clearSelection(); - - /** - * Selects or deselects the term at \p index. Depending on the selectionMode() - * this will also affect the selection of other terms. - */ - void setSelected( int index, bool selected = true ); - - /** - * The \p term is analyzed depending on the selectionMode(). - * - * \sa Facet::selectFromTerm() - */ - bool selectFromTerm( const Nepomuk::Query::Term& queryTerm ); - - protected: - /** - * Used internally to determine if the facet condition is met. Can be - * reimplemented for customized filtering. - * - * \return \p true if the facet condition is met and all choices from the - * source facet should be forwarded. - */ - virtual bool facetConditionMet() const; - - void handleClientQueryChange(); - - private: - class Private; - Private* const d; - }; - } -} - -#endif diff --git a/nepomuk/utils/resourcemodel.cpp b/nepomuk/utils/resourcemodel.cpp deleted file mode 100644 index 1cbf6af3..00000000 --- a/nepomuk/utils/resourcemodel.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . - */ - -#include "resourcemodel.h" - -#include -#include -#include - -#include "kurl.h" -#include "kdebug.h" -#include "kcategorizedsortfilterproxymodel.h" -#include "kicon.h" -#include "klocale.h" - -#include "resource.h" -#include "class.h" -#include "variant.h" - -#include -#include - - -Q_DECLARE_METATYPE(Nepomuk::Types::Class) - - -class Nepomuk::Utils::ResourceModel::Private -{ -public: -}; - - -Nepomuk::Utils::ResourceModel::ResourceModel( QObject* parent ) - : QAbstractItemModel( parent ), - d( new Private() ) -{ -} - - -Nepomuk::Utils::ResourceModel::~ResourceModel() -{ - delete d; -} - - -QModelIndex Nepomuk::Utils::ResourceModel::parent( const QModelIndex& child ) const -{ - Q_UNUSED(child); - return QModelIndex(); -} - - -int Nepomuk::Utils::ResourceModel::columnCount( const QModelIndex& parent ) const -{ - Q_UNUSED(parent); - return ResourceModelColumnCount; -} - - -QVariant Nepomuk::Utils::ResourceModel::data( const QModelIndex& index, int role ) const -{ - Nepomuk::Resource res = resourceForIndex( index ); - if( !res.isValid() ) { - return QVariant(); - } - - // - // Part 1: column specific data - // - switch( index.column() ) { - case ResourceColumn: - switch( role ) { - case Qt::DisplayRole: - case Qt::EditRole: - return res.genericLabel(); - - case Qt::DecorationRole: { - QString iconName = res.genericIcon(); - if( !iconName.isEmpty() ) { - return KIcon( iconName ); - } - else { - QIcon icon = Types::Class(res.resourceType()).icon(); - if( !icon.isNull() ) - return icon; - else - return QVariant(); - } - } - - case Qt::ToolTipRole: - return KUrl( res.resourceUri() ).prettyUrl(); - - } - - case ResourceTypeColumn: - switch( role ) { - case Qt::DisplayRole: - case Qt::EditRole: - return Types::Class( res.resourceType() ).label(); - - case Qt::DecorationRole: { - QIcon icon = Types::Class(res.resourceType()).icon(); - if( !icon.isNull() ) - return icon; - else - return QVariant(); - } - - case Qt::ToolTipRole: - return KUrl(res.resourceType()).prettyUrl(); - } - } - - - // - // Part 2: column-independant data - // - switch( role ) { - case KCategorizedSortFilterProxyModel::CategorySortRole: - // FIXME: sort files before other stuff and so on - - case KCategorizedSortFilterProxyModel::CategoryDisplayRole: { - Q_ASSERT( !res.resourceType().isEmpty() ); - Nepomuk::Types::Class c( res.resourceType() ); - QString cat = c.label(); - if ( cat.isEmpty() ) { - cat = c.name(); - } - if ( c.uri() == Soprano::Vocabulary::RDFS::Resource() || cat.isEmpty() ) { - cat = i18nc( "@title KCategorizedSortFilterProxyModel grouping for all Nepomukj resources that are of type rdfs:Resource", "Miscellaneous" ); - } - - return cat; - } - - case ResourceRole: - return QVariant::fromValue( res ); - - case ResourceTypeRole: - return QVariant::fromValue( Nepomuk::Types::Class(res.resourceType()) ); - - case ResourceCreationDateRole: - return res.property( Soprano::Vocabulary::NAO::created() ).toDateTime(); - } - - // fallback - return QVariant(); -} - - -QVariant Nepomuk::Utils::ResourceModel::headerData(int section, Qt::Orientation orientation, int role) const -{ - if( role == Qt::DisplayRole ) { - switch( section ) { - case ResourceColumn: - return i18nc("@title:column The Nepomuk resource label and icon", "Resource"); - case ResourceTypeColumn: - return i18nc("@title:column The Nepomuk resource's RDF type", "Resource Type"); - } - } - - return QAbstractItemModel::headerData(section, orientation, role); -} - - -Qt::ItemFlags Nepomuk::Utils::ResourceModel::flags( const QModelIndex& index ) const -{ - if ( index.isValid() ) { - return QAbstractItemModel::flags( index ) | Qt::ItemIsDragEnabled; - } - else { - return QAbstractItemModel::flags( index ); - } -} - - -QMimeData* Nepomuk::Utils::ResourceModel::mimeData( const QModelIndexList& indexes ) const -{ - KUrl::List uris; - foreach ( const QModelIndex& index, indexes ) { - if (index.isValid()) { - uris << index.data( ResourceRole ).value().resourceUri(); - } - } - - QMimeData* mimeData = new QMimeData(); - uris.populateMimeData( mimeData ); - - QByteArray data; - QDataStream s( &data, QIODevice::WriteOnly ); - s << uris; - mimeData->setData( mimeTypes().first(), data ); - - return mimeData; -} - - -QStringList Nepomuk::Utils::ResourceModel::mimeTypes() const -{ - return( QStringList() - << QLatin1String( "application/x-nepomuk-resource-uri" ) - << KUrl::List::mimeDataTypes() ); -} - - -bool Nepomuk::Utils::ResourceModel::setData( const QModelIndex& index, const QVariant& value, int role ) -{ - return QAbstractItemModel::setData(index, value, role); -} - -#include "resourcemodel.moc" diff --git a/nepomuk/utils/resourcemodel.h b/nepomuk/utils/resourcemodel.h deleted file mode 100644 index 763d2378..00000000 --- a/nepomuk/utils/resourcemodel.h +++ /dev/null @@ -1,177 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2007-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . - */ - -#ifndef _NEPOMUK_RESOUCE_MODEL_H_ -#define _NEPOMUK_RESOUCE_MODEL_H_ - -#include - -#include "nepomukutils_export.h" - -namespace Nepomuk { - - class Resource; - - namespace Utils { - /** - * \class ResourceModel resourcemodel.h Nepomuk/Utils/ResourceModel - * - * \brief Base class for all models providing a plain list of resources. - * - * The %ResourceModel is a base class for models that handle a set of - * %Nepomuk Resource instances. This can be a simple list as in SimpleResourceModel - * or a set of query results as in ResultModel. It could also be a dynamic list - * which is updated while the user scrolls it. - * - * %ResourceModel cannot be instanciated by itself. Use one of the subclasses - * or derive your own subclass from it. - * - * At least the following methods need to be implemented in a subclass: - * \li resourceForIndex() - * \li indexForResource(), - * \li QAbstractItemModel::rowCount() - * \li QAbstractItemModel::index() - * - * \author Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUKUTILS_EXPORT ResourceModel : public QAbstractItemModel - { - Q_OBJECT - - public: - /** - * Constructor. - */ - ResourceModel( QObject* parent = 0 ); - - /** - * Destructor - */ - virtual ~ResourceModel(); - - /** - * The columns supported by ResourceModel are identified - * by this enumeration. - */ - enum ResourceModelColumns { - /// The first column displays the label of the resource and its icon - ResourceColumn = 0, - - /// The second column displays the resource's type - ResourceTypeColumn = 1, - - /// The number of columns - ResourceModelColumnCount = 2 - }; - - /** - * Custom roles that can be accessed for example in delegates. - */ - enum ResourceRoles { - /** - * The resource itself, provided as a Nepomuk::Resource instance. - */ - ResourceRole = 7766897, - - /** - * The type of the resource, provided as a Nepomuk::Types::Class - * instance. - */ - ResourceTypeRole = 687585, - - /** - * The creation date of the resource. - */ - ResourceCreationDateRole = 7766898 - }; - - /** - * Get the Resource which corresponds to \p index. - * - * \return The Resource which corresponds to \p index or an invalid Resource - * if \p index is invalid. - */ - virtual Resource resourceForIndex( const QModelIndex& index ) const = 0; - - /** - * Get the index for a resource. - * - * \return The index which corresponds to \p res of an invalid QModelIndex - * if \p res is not part of this model. - */ - virtual QModelIndex indexForResource( const Resource& res ) const = 0; - - /** - * The default implementation returns an invalid QModelIndex, thus providing - * a plain list. - */ - virtual QModelIndex parent( const QModelIndex& child ) const; - - /** - * The default implementation returns 2 with the first column representing the resource - * itself and the second one showing the type. - */ - virtual int columnCount( const QModelIndex& parent ) const; - - /** - * Handles most roles typically used in applications like Qt::DisplayRole, Qt::ToolTipRole, - * and Qt::DecorationRole. Additionally KCategorizedSortFilterProxyModel roles are supported - * categorizing by resource types. - */ - virtual QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const; - - /** - * Provides header data for the supported columns. - */ - virtual QVariant headerData( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const; - - /** - * Reimplemented to support dragging of resources out of the model. - */ - virtual Qt::ItemFlags flags( const QModelIndex& index ) const; - - /** - * Stores the resource URIs via KUrl::List::populateMimeData() and as a specific - * "application/x-nepomuk-resource-uri" mime type to indicate that these are URIs - * corresponding to actual %Nepomuk resources. - */ - virtual QMimeData* mimeData( const QModelIndexList& indexes ) const; - - /** - * \return The KUrl mime types and "application/x-nepomuk-resource-uri". - */ - virtual QStringList mimeTypes() const; - - /** - * Provided for future extensions. - */ - virtual bool setData( const QModelIndex& index, const QVariant& value, int role ); - - private: - class Private; - Private* const d; - }; - } -} - -#endif diff --git a/nepomuk/utils/searchlineedit.cpp b/nepomuk/utils/searchlineedit.cpp deleted file mode 100644 index 29418468..00000000 --- a/nepomuk/utils/searchlineedit.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* - Copyright (c) 2010 Oszkar Ambrus - Copyright (c) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "searchlineedit.h" - -#include "klineedit.h" - -#include - -#include "queryparser.h" -#include "andterm.h" -#include "orterm.h" -#include "literalterm.h" - -using namespace Nepomuk::Query; - - -class Nepomuk::Utils::SearchLineEdit::Private { -public: - KLineEdit* m_lineEdit; - bool searchWhileTyping; - - QString m_currentQueryString; - Query::Query m_currentQuery; - - void updateCurrentQuery(); - void _k_queryStringChanged(const QString&); - - SearchLineEdit* q; -}; - -void Nepomuk::Utils::SearchLineEdit::Private::updateCurrentQuery() -{ - // cache the current query for performance reasons - if( m_currentQueryString != m_lineEdit->text() ) { - m_currentQueryString = m_lineEdit->text(); - m_currentQuery = Nepomuk::Query::QueryParser::parseQuery( m_currentQueryString ); - } -} - - -void Nepomuk::Utils::SearchLineEdit::Private::_k_queryStringChanged( const QString& /*queryString*/ ) -{ - emit q->queryChanged( q->query() ); -} - - -Nepomuk::Utils::SearchLineEdit::SearchLineEdit(QWidget *parent) - : QWidget(parent), - d(new Private) -{ - d->q = this; - - d->m_lineEdit = new KLineEdit( this ); - d->m_lineEdit->setClearButtonShown(true); - d->m_lineEdit->setClickMessage(i18n("Enter Search Terms...")); - QHBoxLayout* lay = new QHBoxLayout( this ); - lay->setMargin(0); - lay->addWidget( d->m_lineEdit ); - - setFocusProxy( d->m_lineEdit ); - - setSearchWhileTypingEnabled(false); -} - -Nepomuk::Utils::SearchLineEdit::~SearchLineEdit() -{ - delete d; -} - -void Nepomuk::Utils::SearchLineEdit::setSearchWhileTypingEnabled(bool enable) -{ - d->searchWhileTyping = enable; - disconnect( d->m_lineEdit, 0, this, SLOT(_k_queryStringChanged(QString)) ); - - if(d->searchWhileTyping == true) { - connect( d->m_lineEdit, SIGNAL(textChanged(QString)), this, SLOT(_k_queryStringChanged(QString)) ); - } - else { - connect( d->m_lineEdit, SIGNAL(returnPressed(QString)), this, SLOT(_k_queryStringChanged(QString)) ); - } -} - -Nepomuk::Query::Term Nepomuk::Utils::SearchLineEdit::extractUsableTerms( const Nepomuk::Query::Term& term ) -{ - Term restTerm( term ); - QString queryString; - - // now extract as much as possible to put in the literal search line - if(restTerm.isLiteralTerm()) { - queryString = restTerm.toLiteralTerm().value().toString(); - restTerm = Term(); - } - - // from an AndTerm we can extract as many literal values as we like - else if ( restTerm.isAndTerm() ) { - QStringList searchTerms; - foreach( const Nepomuk::Query::Term& subTerm, restTerm.toAndTerm().subTerms() ) { - if(subTerm.isLiteralTerm()) { - searchTerms << subTerm.toLiteralTerm().value().toString(); - } - else { - restTerm = restTerm && subTerm; - } - } - queryString = searchTerms.join( QLatin1String( " " ) ); - } - - // from an OrTerm we can only extract if all the sub terms are literals since - // otherwise the final query would be different as all the parts are combined - // via an AndTerm. - else if ( restTerm.isOrTerm() ) { - QStringList searchTerms; - OrTerm restOrTerm; - foreach( const Nepomuk::Query::Term& subTerm, restTerm.toAndTerm().subTerms() ) { - if(subTerm.isLiteralTerm()) { - searchTerms << subTerm.toLiteralTerm().value().toString(); - } - else { - restOrTerm.addSubTerm(subTerm); - } - } - if ( restOrTerm.subTerms().isEmpty() ) { - restTerm = restOrTerm.optimized(); - queryString = searchTerms.join( QLatin1String( " OR " ) ); - } - } - - d->m_lineEdit->setText(queryString); - return restTerm; -} - -Nepomuk::Query::Query Nepomuk::Utils::SearchLineEdit::query() const -{ - d->updateCurrentQuery(); - return d->m_currentQuery; -} - -#include "searchlineedit.moc" diff --git a/nepomuk/utils/searchlineedit.h b/nepomuk/utils/searchlineedit.h deleted file mode 100644 index 0cd67416..00000000 --- a/nepomuk/utils/searchlineedit.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - Copyright (c) 2010 Oszkar Ambrus - Copyright (c) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef SEARCHLINEEDIT_H -#define SEARCHLINEEDIT_H - -#include - -#include "query.h" - -namespace Nepomuk { - namespace Utils { - /** - * \class SearchLineEdit searchlineedit.h Nepomuk/Utils/SearchLineEdit - * - * \brief A line edit which allows to enter user queries. - * - * In the future this class will provide some fancy autocompletion. - * - * \author Oszkar Ambrus , Sebastian Trueg - */ - class SearchLineEdit : public QWidget - { - Q_OBJECT - - public: - /** - * Creates a new query edit line with an empty query. - */ - SearchLineEdit(QWidget *parent = 0); - - /** - * Destructor - */ - ~SearchLineEdit(); - - /** - * Sets search while typing option to @p enable. - * If search while typing is enabled, the queryChanged signal will be emitted when the text is changed, - * if it is disabled, the signal will be emitted when the user activates it (e.g. presses Enter) - */ - void setSearchWhileTypingEnabled(bool enable); - - /** - * @returns true if search while typing is enabled, false otherwise - */ - bool searchWhileTypingEnabled(); - - /** - * @returns the current query - */ - Nepomuk::Query::Query query() const; - - public Q_SLOTS: - /** - * Extracts parts from \p term which can be converted into a query using the - * simple desktop query language that is supported by this widget through - * Nepomuk::Query::QueryParser. - * - * \return The rest term that could not be converted into a query string. - */ - Nepomuk::Query::Term extractUsableTerms( const Nepomuk::Query::Term& term ); - - Q_SIGNALS: - /** - * Acivated when the query is changed (while typing or when finished) - */ - void queryChanged( const Nepomuk::Query::Query& query ); - - private: - class Private; - Private * const d; - - Q_PRIVATE_SLOT( d, void _k_queryStringChanged(const QString&) ) - }; - } -} - -#endif // SEARCHLINEEDIT_H diff --git a/nepomuk/utils/searchwidget.cpp b/nepomuk/utils/searchwidget.cpp deleted file mode 100644 index f46e72aa..00000000 --- a/nepomuk/utils/searchwidget.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/* - Copyright (c) 2010 Oszkar Ambrus - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "searchwidget.h" -#include "searchwidget_p.h" - -#include "searchlineedit.h" -#include "facetwidget.h" -#include "simpleresourcemodel.h" -#include "proxyfacet.h" -#include "simplefacet.h" - -#include -#include -#include -#include -#include - -#include "kdebug.h" -#include "kpushbutton.h" -#include "kdialog.h" - -#include "query.h" -#include "queryparser.h" -#include "result.h" -#include "andterm.h" -#include "orterm.h" -#include "literalterm.h" -#include "comparisonterm.h" -#include "resourceterm.h" -#include "resourcetypeterm.h" -#include "queryserviceclient.h" -#include "resource.h" -#include "filequery.h" -#include "negationterm.h" -#include "nfo.h" -#include "variant.h" - -#include -#include - -void Nepomuk::Utils::SearchWidget::SearchWidgetPrivate::setupFacetWidget() -{ - m_facetWidget->clear(); - m_facetWidget->addFacet(Facet::createTypeFacet(m_facetWidget)); - m_facetWidget->addFacet(Facet::createDateFacet(m_facetWidget)); - m_facetWidget->addFacet(Facet::createPriorityFacet(m_facetWidget)); - m_facetWidget->addFacet(Facet::createTagFacet(m_facetWidget)); -} - - -void Nepomuk::Utils::SearchWidget::SearchWidgetPrivate::_k_queryComponentChanged() -{ - if ( !m_inQueryComponentChanged ) { - m_inQueryComponentChanged = true; - const Query::Query query = currentQuery(); - if( query != m_currentQuery ) { - m_resourceModel->clear(); - // TODO: show busy indicator - kDebug() << query; - m_queryClient.close(); - if( query.isValid() ) { - m_queryClient.query(query); - } - m_facetWidget->setClientQuery(query); - m_currentQuery = query; - } - m_inQueryComponentChanged = false; - } - else { - // we need to handle all component changes since one may trigger another - QMetaObject::invokeMethod(q, "_k_queryComponentChanged", Qt::QueuedConnection); - } -} - - -void Nepomuk::Utils::SearchWidget::SearchWidgetPrivate::_k_listingFinished() -{ - // TODO: disable busy indicator -} - -void Nepomuk::Utils::SearchWidget::SearchWidgetPrivate::_k_forwardCurrentChanged( - const QModelIndex & previous, const QModelIndex & current ) -{ - Resource prevRes; - Resource currRes; - if ( previous.isValid() ) { - prevRes = previous.data(Utils::ResourceModel::ResourceRole).value(); - } - if ( current.isValid() ) { - currRes = current.data(Utils::ResourceModel::ResourceRole).value(); - } - - emit q->currentResourceChanged(prevRes,currRes); -} - -Nepomuk::Query::Query Nepomuk::Utils::SearchWidget::SearchWidgetPrivate::currentQuery( bool withBaseQuery ) const -{ - Query::Query query; - if( withBaseQuery ) { - kDebug() << "************ baseQuery: " << m_baseQuery; - query = m_baseQuery; - } - - Query::Term facetTerm = m_facetWidget->queryTerm(); - Query::Term userQueryTerm = m_queryEdit->query().term(); - - kDebug() << "************ userQuery: " << userQueryTerm; - kDebug() << "************ facetQuery: " << facetTerm; - - return query && facetTerm && userQueryTerm; -} - - -Nepomuk::Utils::SearchWidget::SearchWidget(QWidget *parent) - : QWidget(parent), - d_ptr(new SearchWidgetPrivate()) -{ - Q_D(SearchWidget); - d->q = this; - - //query editor widget - d->m_queryEdit = new SearchLineEdit(this); - d->m_queryButton = new KPushButton(i18n("Search"), this); - connect(d->m_queryEdit, SIGNAL(queryChanged(Nepomuk::Query::Query)), this, SLOT(_k_queryComponentChanged())); - connect(d->m_queryButton, SIGNAL(clicked()), this, SLOT(_k_queryComponentChanged())); - - //item widget - d->m_itemWidget = new QListView(this); - d->m_resourceModel = new Utils::SimpleResourceModel(this); - d->m_itemWidget->setModel(d->m_resourceModel); - connect(d->m_itemWidget->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SIGNAL(selectionChanged())); - connect(d->m_itemWidget->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), - this, SLOT(_k_forwardCurrentChanged(QModelIndex,QModelIndex))); - - //facets widget - d->m_facetWidget = new Nepomuk::Utils::FacetWidget(this); - d->setupFacetWidget(); - connect(d->m_facetWidget, SIGNAL(queryTermChanged(Nepomuk::Query::Term)), this, SLOT(_k_queryComponentChanged())); - - //layout and config - QSplitter* facetSplitter = new QSplitter(this); - facetSplitter->addWidget(d->m_itemWidget); - facetSplitter->addWidget(d->m_facetWidget); - - QGridLayout* layout = new QGridLayout( this ); - layout->setMargin(0); - layout->addWidget( d->m_queryEdit, 0, 0 ); - layout->addWidget( d->m_queryButton, 0, 1 ); - layout->addWidget( facetSplitter, 1, 0, 1, 2 ); - layout->setRowStretch(1,1); - - // query client setup - connect( &d->m_queryClient, SIGNAL(newEntries(QList)), - d->m_resourceModel, SLOT(addResults(QList)) ); - connect( &d->m_queryClient, SIGNAL(finishedListing()), - this, SLOT(_k_listingFinished())); - - setSelectionMode(QListView::ExtendedSelection); - setConfigFlags( DefaultConfigFlags ); -} - -Nepomuk::Utils::SearchWidget::~SearchWidget() -{ - delete d_ptr; -} - -void Nepomuk::Utils::SearchWidget::setConfigFlags( ConfigFlags flags ) -{ - Q_D(SearchWidget); - d->m_configFlags = flags; - d->m_facetWidget->setShown( flags&ShowFacets ); - d->m_queryButton->setShown( !( flags&SearchWhileYouType ) ); - d->m_queryEdit->setSearchWhileTypingEnabled( flags&SearchWhileYouType ); -} - -Nepomuk::Utils::SearchWidget::ConfigFlags Nepomuk::Utils::SearchWidget::configFlags() const -{ - Q_D(const SearchWidget); - return d->m_configFlags; -} - -void Nepomuk::Utils::SearchWidget::setSelectionMode ( QAbstractItemView::SelectionMode mode ) -{ - Q_D(SearchWidget); - - d->m_itemWidget->setSelectionMode(mode); -} - -QAbstractItemView::SelectionMode Nepomuk::Utils::SearchWidget::selectionMode () const -{ - Q_D(const SearchWidget); - - return d->m_itemWidget->selectionMode(); -} - -Nepomuk::Query::Query Nepomuk::Utils::SearchWidget::setQuery( const Nepomuk::Query::Query &query ) -{ - Q_D(SearchWidget); - - // try to extract as much as possible from the query as facets - Query::Query restQuery = d->m_facetWidget->extractFacetsFromQuery( query ); - - // try to get the rest into the line edit - restQuery.setTerm( d->m_queryEdit->extractUsableTerms( restQuery.term() ) ); - - return restQuery; -} - -void Nepomuk::Utils::SearchWidget::setBaseQuery( const Query::Query& query ) -{ - Q_D(SearchWidget); - d->m_baseQuery = query; - d->_k_queryComponentChanged(); -} - -Nepomuk::Query::Query Nepomuk::Utils::SearchWidget::baseQuery() const -{ - Q_D(const SearchWidget); - return d->m_baseQuery; -} - -Nepomuk::Query::Query Nepomuk::Utils::SearchWidget::query() const -{ - Q_D(const SearchWidget); - return d->currentQuery(); -} - -Nepomuk::Resource Nepomuk::Utils::SearchWidget::currentResource() const -{ - Q_D(const SearchWidget); - return d->m_itemWidget->currentIndex().data(Utils::ResourceModel::ResourceRole).value(); -} - -QList Nepomuk::Utils::SearchWidget::selectedResources() const -{ - Q_D(const SearchWidget); - QList resourceList; - foreach(const QModelIndex& index, d->m_itemWidget->selectionModel()->selectedIndexes()) { - resourceList << index.data(Utils::ResourceModel::ResourceRole).value(); - } - return resourceList; -} - - -Nepomuk::Utils::FacetWidget* Nepomuk::Utils::SearchWidget::facetWidget() const -{ - Q_D(const SearchWidget); - return d->m_facetWidget; -} - - -// static -Nepomuk::Resource Nepomuk::Utils::SearchWidget::searchResource( QWidget* parent, - const Nepomuk::Query::Query& baseQuery, - SearchWidget::ConfigFlags flags ) -{ - KDialog dlg( parent ); - dlg.setButtons(KDialog::Ok | KDialog::Cancel); - SearchWidget* searchWidget = new SearchWidget(&dlg); - dlg.setMainWidget(searchWidget); - - searchWidget->setBaseQuery( baseQuery ); - searchWidget->setConfigFlags( flags ); - searchWidget->setSelectionMode( QAbstractItemView::SingleSelection ); - - if( dlg.exec() == QDialog::Accepted ) { - return searchWidget->currentResource(); - } - else { - return Nepomuk::Resource(); - } -} - - -// static -QList Nepomuk::Utils::SearchWidget::searchResources( QWidget* parent, - const Nepomuk::Query::Query& baseQuery, - SearchWidget::ConfigFlags flags ) -{ - KDialog dlg( parent ); - dlg.setButtons(KDialog::Ok | KDialog::Cancel); - SearchWidget* searchWidget = new SearchWidget(&dlg); - dlg.setMainWidget(searchWidget); - - searchWidget->setBaseQuery( baseQuery ); - searchWidget->setConfigFlags( flags ); - searchWidget->setSelectionMode( QAbstractItemView::ExtendedSelection ); - - if( dlg.exec() == QDialog::Accepted ) { - return searchWidget->selectedResources(); - } - else { - return QList(); - } -} - -#include "searchwidget.moc" diff --git a/nepomuk/utils/searchwidget.h b/nepomuk/utils/searchwidget.h deleted file mode 100644 index 11e3c4e4..00000000 --- a/nepomuk/utils/searchwidget.h +++ /dev/null @@ -1,214 +0,0 @@ -/* - Copyright (c) 2010 Oszkar Ambrus - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef RESOURCESEARCHWIDGET_H -#define RESOURCESEARCHWIDGET_H - -#include -#include - -#include "query.h" -#include "nepomukutils_export.h" - -namespace Nepomuk { - class Resource; - - namespace Utils { - class FacetWidget; - - /** - * \class SearchWidget searchwidget.h Nepomuk/Utils/SearchWidget - * - * \brief Provides a GUI for searching files or resources of any type. - * - * The SearchWidget combines the different search GUI elements provided in - * Nepomuk in one widget: a line edit which allows to type in a query and - * the facet widget. - * - * The SearchWidget allows to specify a base query which is fixed and cannot - * be changed by the user. This allows to restrict the set of resources searched - * by the user. - * - * \author Oszkar Ambrus , Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUKUTILS_EXPORT SearchWidget : public QWidget - { - Q_OBJECT - - public: - /** - * Constructor. - */ - SearchWidget(QWidget *parent = 0); - - /** - * Destructor - */ - ~SearchWidget(); - - /** - * The config flags can be used to configure - * the search widget to fit the needs of the application. - */ - enum ConfigFlag { - /// no flags, a plain search widget - NoConfigFlags = 0x0, - - /// show the facets allowing the user to modify the query - ShowFacets = 0x1, - - /// enable auto searching while the user is typing in the query (live query) - SearchWhileYouType = 0x2, - - /// the default: show facets and disable live query - DefaultConfigFlags = ShowFacets - }; - Q_DECLARE_FLAGS( ConfigFlags, ConfigFlag ) - - /** - * Set the config flags to be used. Defaults to DefaultConfigFlags. - * - * \sa configFlags() - */ - void setConfigFlags( ConfigFlags flags ); - - /** - * The config flags set via setConfigFlags(). - */ - ConfigFlags configFlags() const; - - /** - * Sets the selection mode of the view to @p mode - */ - void setSelectionMode(QAbstractItemView::SelectionMode mode); - - /** - * @returns the selection mode of the view - */ - QAbstractItemView::SelectionMode selectionMode () const; - - /** - * @returns the base query set via setBaseQuery(). - */ - Query::Query baseQuery() const; - - /** - * Construct the query currently used by this widget including - * the baseQuery(), all facets, and the user desktop query. - */ - Query::Query query() const; - - /** - * @returns the current resource if any, an invalid resource if none is selected - */ - Resource currentResource() const; - - /** - * @returns a list of all selected resources. - */ - QList selectedResources() const; - - /** - * The facet widget that is used internally. By default a predefined set of facets - * is used. This method can be used to access the FacetWidget in order to change its - * configuration. - */ - FacetWidget* facetWidget() const; - - /** - * Creates a dialog embedding a SearchWidget that allows the user to select one resource from the - * result set. - * - * \return The Resource the user selected or an invalid one in case there was no result to choose - * or the user canceled the search. - */ - static Nepomuk::Resource searchResource( QWidget* parent = 0, - const Nepomuk::Query::Query& baseQuery = Nepomuk::Query::Query(), - SearchWidget::ConfigFlags flags = SearchWidget::DefaultConfigFlags ); - - /** - * Creates a dialog embedding a SearchWidget that allows the user to select resources from the - * result set. - * - * \return The resources the user selected or an empty list in case there was no result to choose - * or the user canceled the search. - */ - static QList searchResources( QWidget* parent = 0, - const Nepomuk::Query::Query& baseQuery = Nepomuk::Query::Query(), - SearchWidget::ConfigFlags flags = SearchWidget::DefaultConfigFlags ); - - public Q_SLOTS: - /** - * Set the query currently configured in the widget. Parts that cannot be converted into - * facets or a user desktop query string are returned. - * - * \param query The query that the widget should represent after the call. - * - * \return The rest query which could not be converted into facets and a desktop query. - */ - Nepomuk::Query::Query setQuery( const Nepomuk::Query::Query& query ); - - /** - * Set the base query. The base query is the fixed part of the query - * which cannot be changed by the user. It allows to restrict the - * searched set of resources. - * - * Be default the base query is empty, ie. an invalid Query. - * - * \param query The new base query. - * - * Be aware that setting the base query will reset widget's query components. - */ - void setBaseQuery( const Nepomuk::Query::Query& query ); - - Q_SIGNALS: - /** - * Emitted when the selection is changed, ie. the values returned by currentResource() and - * selectedResources() have changed. - */ - void selectionChanged(); - - /** - * \brief Emited when current resource is changed - */ - void currentResourceChanged(const Nepomuk::Resource & previous, const Nepomuk::Resource & current ); - - - private: - class SearchWidgetPrivate; - SearchWidgetPrivate * const d_ptr; - - Q_DECLARE_PRIVATE(SearchWidget) - - /*! \brief Convert QModelIndex to Nepomuk::Resource and emit currentResourceChanged signal - */ - Q_PRIVATE_SLOT( d_ptr, void _k_forwardCurrentChanged( const QModelIndex &, const QModelIndex &)); - Q_PRIVATE_SLOT( d_ptr, void _k_queryComponentChanged() ) - Q_PRIVATE_SLOT( d_ptr, void _k_listingFinished() ) - }; - } -} - -Q_DECLARE_OPERATORS_FOR_FLAGS( Nepomuk::Utils::SearchWidget::ConfigFlags ) - -#endif // RESOURCESEARCHWIDGET_H diff --git a/nepomuk/utils/searchwidget_p.h b/nepomuk/utils/searchwidget_p.h deleted file mode 100644 index 22cb751e..00000000 --- a/nepomuk/utils/searchwidget_p.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright (c) 2010 Oszkar Ambrus - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef RESOURCESEARCHWIDGET_P_H -#define RESOURCESEARCHWIDGET_P_H - -#include "searchwidget.h" - -#include "query.h" -#include "queryserviceclient.h" - -class QListView; -namespace Nepomuk { - namespace Utils { - class SimpleResourceModel; - class FacetWidget; - class SearchLineEdit; - } -} -class KPushButton; - -/** - * WARNING: This class is just an implementation detail. - */ -class Nepomuk::Utils::SearchWidget::SearchWidgetPrivate -{ -public: - SearchWidgetPrivate() - : m_inQueryComponentChanged( false ) { - } - - /// creates the default set of facets - void setupFacetWidget(); - - /** - * Get the current query. - * \param withBaseQuery If \p true the base query is included, otherwise it is not included. - * \return The currently selected query. - */ - Query::Query currentQuery( bool withBaseQuery = true ) const; - - void _k_queryComponentChanged(); - void _k_listingFinished(); - void _k_forwardCurrentChanged( const QModelIndex &, const QModelIndex &); - - SearchLineEdit *m_queryEdit; - KPushButton *m_queryButton; - QListView *m_itemWidget; - Utils::SimpleResourceModel* m_resourceModel; - Nepomuk::Utils::FacetWidget *m_facetWidget; - - Nepomuk::Query::QueryServiceClient m_queryClient; - Nepomuk::Query::Query m_currentQuery; - - Nepomuk::Query::Query m_baseQuery; - - SearchWidget::ConfigFlags m_configFlags; - - bool m_inQueryComponentChanged; - - SearchWidget* q; -}; - -#endif // RESOURCESEARCHWIDGET_P_H diff --git a/nepomuk/utils/simplefacet.cpp b/nepomuk/utils/simplefacet.cpp deleted file mode 100644 index 568f0edf..00000000 --- a/nepomuk/utils/simplefacet.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "simplefacet.h" -#include "andterm.h" -#include "orterm.h" -#include "query.h" - -#include "kguiitem.h" -#include "kdebug.h" - -#include - -using namespace Nepomuk::Query; - - -class Nepomuk::Utils::SimpleFacet::Private -{ -public: - Private() - : m_selectionMode(Facet::MatchOne) { - } - - int indexOf( const Term& term ) const; - - Facet::SelectionMode m_selectionMode; - - QList m_terms; - QList m_titles; - - QSet m_selectedFacets; - - SimpleFacet* q; -}; - - -int Nepomuk::Utils::SimpleFacet::Private::indexOf( const Term& term ) const -{ - return m_terms.indexOf( term ); -} - - -Nepomuk::Utils::SimpleFacet::SimpleFacet( QObject* parent ) - : Facet(parent), - d(new Private()) -{ - d->q = this; -} - - -Nepomuk::Utils::SimpleFacet::~SimpleFacet() -{ - delete d; -} - - -void Nepomuk::Utils::SimpleFacet::setSelectionMode( SelectionMode mode ) -{ - d->m_selectionMode = mode; - clearSelection(); -} - - -Nepomuk::Utils::Facet::SelectionMode Nepomuk::Utils::SimpleFacet::selectionMode() const -{ - return d->m_selectionMode; -} - - -Nepomuk::Query::Term Nepomuk::Utils::SimpleFacet::queryTerm() const -{ - if( d->m_terms.isEmpty() || - d->m_selectedFacets.isEmpty() ) { - return Term(); - } - else { - switch( d->m_selectionMode ) { - case MatchAll: { - AndTerm andTerm; - Q_FOREACH( int i, d->m_selectedFacets ) { - andTerm.addSubTerm( termAt(i) ); - } - return andTerm.optimized(); - } - case MatchAny: { - OrTerm orTerm; - Q_FOREACH( int i, d->m_selectedFacets ) { - orTerm.addSubTerm( termAt(i) ); - } - return orTerm.optimized(); - } - case MatchOne: - return termAt( *d->m_selectedFacets.constBegin() ); - } - } - - // make gcc shut up - return Term(); -} - - -int Nepomuk::Utils::SimpleFacet::count() const -{ - return d->m_terms.count(); -} - - -Nepomuk::Query::Term Nepomuk::Utils::SimpleFacet::termAt( int index ) const -{ - return d->m_terms[index]; -} - - -bool Nepomuk::Utils::SimpleFacet::isSelected( int index ) const -{ - return d->m_selectedFacets.contains( index ); -} - - -KGuiItem Nepomuk::Utils::SimpleFacet::guiItem( int index ) const -{ - return d->m_titles[index]; -} - - -void Nepomuk::Utils::SimpleFacet::clear() -{ - d->m_terms.clear(); - d->m_titles.clear(); - d->m_selectedFacets.clear(); - setQueryTermChanged(); -} - - -void Nepomuk::Utils::SimpleFacet::addTerm( const QString& text, const Nepomuk::Query::Term& term ) -{ - addTerm( KGuiItem(text), term ); -} - - -void Nepomuk::Utils::SimpleFacet::addTerm( const KGuiItem& title, const Nepomuk::Query::Term& term ) -{ - d->m_titles.append( title ); - d->m_terms.append( term ); - clearSelection(); - setLayoutChanged(); -} - - -void Nepomuk::Utils::SimpleFacet::setSelected( int index, bool selected ) -{ - if( selectionMode() == MatchOne ) { - if( d->m_selectedFacets.contains(index) && !selected ) { - clearSelection(); - } - else if( selected ) { - d->m_selectedFacets.clear(); - d->m_selectedFacets.insert(index); - } - } - else if( selected ) { - d->m_selectedFacets.insert(index); - } - else { - d->m_selectedFacets.remove(index); - } - setSelectionChanged(); - setQueryTermChanged(); -} - - -void Nepomuk::Utils::SimpleFacet::clearSelection() -{ - d->m_selectedFacets.clear(); - if( selectionMode() == MatchOne ) - d->m_selectedFacets.insert(0); - setSelectionChanged(); - setQueryTermChanged(); -} - - -bool Nepomuk::Utils::SimpleFacet::selectFromTerm( const Nepomuk::Query::Term& term ) -{ - // 1. check if term is in our list of terms - const int i = d->indexOf( term ); - if( i >= 0 ) { - kDebug() << "Found term at" << i << term; - setSelected( i, true ); - return true; - } - - // 2. an OrTerm may be a set of terms in a MatchOne facet - // 3. an AndTerm may be a set of terms in a MatchAll facet - if( ( term.isOrTerm() && - selectionMode() == MatchAny ) || - ( term.isAndTerm() && - selectionMode() == MatchAll ) ) { - - QSet selectedTerms; - - // since single terms could consist of OrTerms or AndTerms as well - // and thus, could be "merged" into the surrounding term, we check - // every sensible combination of terms instead of only single ones - - QList subTerms; - if( term.isAndTerm() ) - subTerms = term.toAndTerm().subTerms(); - else - subTerms = term.toOrTerm().subTerms(); - - while( !subTerms.isEmpty() ) { - bool found = false; - for( int len = 1; len <= subTerms.count(); ++len ) { - const QList excerpt = subTerms.mid( 0, len ); - Term subTerm; - if( term.isAndTerm() ) - subTerm = AndTerm(excerpt).optimized(); - else - subTerm = OrTerm(excerpt).optimized(); - const int i = d->indexOf( subTerm ); - if( i >= 0 ) { - kDebug() << "Found term at" << i << subTerm; - selectedTerms << i; - subTerms = subTerms.mid(len); - found = true; - break; - } - } - if( !found ) { - kDebug() << "Term not found (not even as subterm):" << subTerms; - return false; - } - } - - d->m_selectedFacets = selectedTerms; - setSelectionChanged(); - setQueryTermChanged(); - - return true; - } - - else { - kDebug() << "Term not found" << term; - return false; - } -} - -#include "simplefacet.moc" diff --git a/nepomuk/utils/simplefacet.h b/nepomuk/utils/simplefacet.h deleted file mode 100644 index b680b737..00000000 --- a/nepomuk/utils/simplefacet.h +++ /dev/null @@ -1,152 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_QUERY_SIMPLE_FACET_H_ -#define _NEPOMUK_QUERY_SIMPLE_FACET_H_ - -#include "facet.h" -#include "nepomukutils_export.h" - -namespace Nepomuk { - namespace Utils { - /** - * \class SimpleFacet simplefacet.h Nepomuk/Utils/SimpleFacet - * - * \ingroup nepomuk_facets - * - * \brief A simple facet using a list of terms. - * - * The %SimpleFacet maintains a list of Query::Term objects combined - * with a label (or a full KGuiItem if required). The usage is very - * simple: Create a new instance of SimpleFacet, add terms via the addTerm() - * methods, choose a selection mode via setSelectionMode(), and let - * SimpleFacet do the rest. - * - * %SimpleFacet even implements the selectFromTerm() method which - * provides enhanced user experience by converting queries into facets. - * - * \author Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUKUTILS_EXPORT SimpleFacet : public Facet - { - Q_OBJECT - - public: - /** - * Create a new empty facet. - */ - SimpleFacet( QObject* parent = 0 ); - - /** - * Destructor - */ - ~SimpleFacet(); - - /** - * \return The currently selected Term. Depending on the - * selectionMode() this is either a single Term, a combination - * through Query::AndTerm, or a combination through Query::OrTerm. - */ - Query::Term queryTerm() const; - - /** - * Set the selection mode to use in this facet. The default is MatchOne. - */ - void setSelectionMode( SelectionMode mode ); - - /** - * The selection mode set via setSelectionMode() - */ - SelectionMode selectionMode() const; - - /** - * \return The number of terms added via addTerm(). - */ - int count() const; - - /** - * \return The gui item set via addTerm() for the Term at \p index - * or an empty KGuiItem if \p index is out of range. - */ - KGuiItem guiItem( int index ) const; - - /** - * \return The term set via addTerm() for \p index - * or an invalid Query::Term if \p index is out of range. - */ - Query::Term termAt( int index ) const; - - /** - * \return \p true if the term at \p index has been selected via - * setSelected(). - */ - bool isSelected( int index ) const; - - public Q_SLOTS: - /** - * Clear the list of terms. - */ - void clear(); - - /** - * Add a new term. This is equivalent to calling - * \code - * addTerm(KGuiItem(text), term); - * \endcode - */ - void addTerm( const QString& text, const Nepomuk::Query::Term& queryTerm ); - - /** - * Add a new term. - * \param item The gui item used to present the choice to the user. - * \param term The query term which represents this choice. - */ - void addTerm( const KGuiItem& item, const Nepomuk::Query::Term& queryTerm ); - - /** - * Clear the selection. If selectionMode() is MatchOne the first - * choice should be selected. - */ - void clearSelection(); - - /** - * Selects or deselects the term at \p index. Depending on the selectionMode() - * this will also affect the selection of other terms. - */ - void setSelected( int index, bool selected = true ); - - /** - * The \p term is analyzed depending on the selectionMode(). - * - * \sa Facet::selectFromTerm() - */ - bool selectFromTerm( const Nepomuk::Query::Term& queryTerm ); - - private: - class Private; - Private* d; - }; - } -} - -#endif diff --git a/nepomuk/utils/simpleresourcemodel.cpp b/nepomuk/utils/simpleresourcemodel.cpp deleted file mode 100644 index d56524a2..00000000 --- a/nepomuk/utils/simpleresourcemodel.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . - */ - -#include "simpleresourcemodel.h" - -#include -#include - -#include "resource.h" -#include "result.h" - -#include "kdebug.h" -#include "kurl.h" - - -class Nepomuk::Utils::SimpleResourceModel::Private -{ -public: - QList resources; -}; - - -Nepomuk::Utils::SimpleResourceModel::SimpleResourceModel( QObject* parent ) - : ResourceModel( parent ), - d( new Private() ) -{ -} - - -Nepomuk::Utils::SimpleResourceModel::~SimpleResourceModel() -{ - delete d; -} - - -QModelIndex Nepomuk::Utils::SimpleResourceModel::indexForResource( const Resource& res ) const -{ - Q_ASSERT( res.isValid() ); - // FIXME: performance - int i = 0; - QList::const_iterator end = d->resources.constEnd(); - for ( QList::const_iterator it = d->resources.constBegin(); it != end; ++it ) { - if ( *it == res ) { - return index( i, 0 ); - } - ++i; - } - - return QModelIndex(); -} - - -Nepomuk::Resource Nepomuk::Utils::SimpleResourceModel::resourceForIndex( const QModelIndex& index ) const -{ - if ( index.isValid() && index.row() < d->resources.count() ) { - return d->resources[index.row()]; - } - else { - return Resource(); - } -} - - -int Nepomuk::Utils::SimpleResourceModel::rowCount( const QModelIndex& parent ) const -{ - if ( parent.isValid() ) { - return 0; - } - else { - return d->resources.count(); - } -} - - -QModelIndex Nepomuk::Utils::SimpleResourceModel::index( int row, int column, const QModelIndex& parent ) const -{ - if ( !parent.isValid() && row < d->resources.count() ) { - return createIndex( row, column, 0 ); - } - else { - return QModelIndex(); - } -} - - -bool Nepomuk::Utils::SimpleResourceModel::removeRows(int row, int count, const QModelIndex& parent) -{ - if( count < 1 || row < 0 || (row + count) > d->resources.size() || parent.isValid() ) - return false; - - beginRemoveRows( parent, row, row + count -1 ); - - QList::iterator begin, end; - begin = end = d->resources.begin(); - begin += row; - end += row + count; - d->resources.erase( begin, end ); - - endRemoveRows(); - return true; -} - - -void Nepomuk::Utils::SimpleResourceModel::setResources( const QList& resources ) -{ - d->resources = resources; - reset(); -} - - -void Nepomuk::Utils::SimpleResourceModel::addResources( const QList& resources ) -{ - if(!resources.isEmpty()) { - beginInsertRows( QModelIndex(), d->resources.count(), d->resources.count() + resources.count() - 1 ); - d->resources << resources; - endInsertRows(); - } -} - - -void Nepomuk::Utils::SimpleResourceModel::addResource( const Nepomuk::Resource& resource ) -{ - addResources( QList() << resource ); -} - - -void Nepomuk::Utils::SimpleResourceModel::setResults( const QList& results) -{ - clear(); - addResults( results ); -} - -void Nepomuk::Utils::SimpleResourceModel::addResults( const QList& results ) -{ - Q_FOREACH( const Query::Result& result, results ) { - addResource( result.resource() ); - } -} - -void Nepomuk::Utils::SimpleResourceModel::addResult( const Nepomuk::Query::Result result ) -{ - addResource( result.resource() ); -} - - -void Nepomuk::Utils::SimpleResourceModel::clear() -{ - d->resources.clear(); - reset(); -} - -#include "simpleresourcemodel.moc" diff --git a/nepomuk/utils/simpleresourcemodel.h b/nepomuk/utils/simpleresourcemodel.h deleted file mode 100644 index cdbe37f0..00000000 --- a/nepomuk/utils/simpleresourcemodel.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2008-2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . - */ - -#ifndef _NEPOMUK_SIMPLE_RESOURCE_MODEL_H_ -#define _NEPOMUK_SIMPLE_RESOURCE_MODEL_H_ - -#include "resourcemodel.h" - -#include "nepomukutils_export.h" - -#include "resource.h" -#include "result.h" - -#include - -namespace Nepomuk { - namespace Utils { - /** - * \class SimpleResourceModel simpleresourcemodel.h Nepomuk/Utils/SimpleResourceModel - * - * A simple ResourceModel that handles a list of Resource instances which - * can be managed via the setResources(), addResource(), addResources(), and - * clear() methods. - * - * \author Sebastian Trueg - * - * \since 4.6 - */ - class NEPOMUKUTILS_EXPORT SimpleResourceModel : public ResourceModel - { - Q_OBJECT - - public: - /** - * Creates an empty resource model. - */ - SimpleResourceModel( QObject* parent = 0 ); - - /** - * Destructor - */ - ~SimpleResourceModel(); - - /** - * Get the Resource which corresponds to \p index. - * - * \return The Resource which corresponds to \p index or an invalid Resource - * if \p index is invalid. - */ - QModelIndex indexForResource( const Resource& res ) const; - - /** - * Get the index for a resource. - * - * \return The index which corresponds to \p res of an invalid QModelIndex - * if \p res is not part of this model. - */ - Resource resourceForIndex( const QModelIndex& index ) const; - - /** - * \return The number of resources added to the model for an invalid parent index. - */ - int rowCount( const QModelIndex& parent = QModelIndex() ) const; - - /** - * Creates an index for the cell at \p row and \p column. - */ - QModelIndex index( int row, int column, const QModelIndex& parent = QModelIndex() ) const; - - /** - * Removes those resources from the model. - */ - bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()); - - public Q_SLOTS: - /** - * Set the resources to be provided by the model to \p resources. - */ - void setResources( const QList& resources ); - - /** - * Add \p resources to the list of resources being provided by the - * model. - */ - void addResources( const QList& resources ); - - /** - * Add \p resource to the list of resources being provided by the - * model. - */ - void addResource( const Nepomuk::Resource& resource ); - - /** - * This method is similar to setResources(). It is provided for - * allowing convenient connections from signals that provide - * Query::Result objects. - */ - void setResults( const QList& results ); - - /** - * This method is similar to addResources(). It is provided for - * allowing convenient connections from signals that provide - * Query::Result objects like Query::QueryServiceClient::newResults(). - */ - void addResults( const QList& results ); - - /** - * This method is similar to addResource(). It is provided for - * allowing convenient connections from signals that provide - * Query::Result objects. - */ - void addResult( const Nepomuk::Query::Result result ); - - /** - * Clear the model by removing all resources added via setResources() and friends. - */ - void clear(); - - private: - class Private; - Private* const d; - }; - } -} - -#endif diff --git a/nepomuk/utils/typefacet.cpp b/nepomuk/utils/typefacet.cpp deleted file mode 100644 index fb11dc33..00000000 --- a/nepomuk/utils/typefacet.cpp +++ /dev/null @@ -1,417 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "typefacet.h" -#include "filequery.h" -#include "term.h" -#include "class.h" -#include "andterm.h" -#include "orterm.h" -#include "resourcetypeterm.h" -#include "negationterm.h" -#include "literalterm.h" -#include "comparisonterm.h" -#include "nfo.h" -#include "nie.h" -#include "tmo.h" -#include "nco.h" -#include "nmo.h" - -#include "kguiitem.h" -#include "kdebug.h" - -#include -#include - -#include - - -namespace { -enum RootSelection { - None, - File, - Other -}; -} - -class Nepomuk::Utils::TypeFacet::Private -{ -public: - Private() - : m_rootSelection(None), - m_usedTypes(0) { - // - // Default file types - // - m_fileTypes.append( qMakePair(i18nc("@option:check A filter on file type", "Documents"), - Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Document())) ); - - // need to check the mimetype as well since strigi is still not perfect - m_fileTypes.append( qMakePair(i18nc("@option:check A filter on file type - audio files", "Audio"), - Query::ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(), Query::LiteralTerm(QLatin1String("audio")))) ); - m_fileTypes.append( qMakePair(i18nc("@option:check A filter on file type - media video", "Video"), - Query::ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(), Query::LiteralTerm(QLatin1String("video")))) ); - - m_fileTypes.append( qMakePair(i18nc("@option:check A filter on file type", "Images"), - Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Image())) ); - - - // - // Default other types - // - m_otherTypes.append(qMakePair(i18nc("@option:check A filter on resource type", "Contacts"), - Query::ResourceTypeTerm(Nepomuk::Vocabulary::NCO::Contact()))); - m_otherTypes.append(qMakePair(i18nc("@option:check A filter on resource type", "Emails"), - Query::ResourceTypeTerm(Nepomuk::Vocabulary::NMO::Email()))); - m_otherTypes.append(qMakePair(i18nc("@option:check A filter on resource type", "Tasks"), - Query::ResourceTypeTerm(Nepomuk::Vocabulary::TMO::Task()))); - m_otherTypes.append(qMakePair(i18nc("@option:check A filter on resource type", "Tags"), - Query::ResourceTypeTerm(Soprano::Vocabulary::NAO::Tag()))); - } - - bool findTerm( const Query::Term& term, int* index, RootSelection* rootSelection ) const; - void setRootSelection( RootSelection selection ); - - RootSelection m_rootSelection; - QList > m_fileTypes; - QList > m_otherTypes; - - /// points to m_fileTypes or m_otherTypes based on m_rootSelection - QList >* m_usedTypes; - - /// a list of custom types which is filled by selectFromTerm() - QList m_customTypes; - - /// indexes into m_fileTypes or m_otherTypes depending on the value of m_rootSelection - /// only used to avoid code duplication - QSet m_selectedTypes; - - /// indexes into m_customTypes - QSet m_selectedCustomTypes; -}; - - -bool Nepomuk::Utils::TypeFacet::Private::findTerm( const Query::Term& term, int* index, RootSelection* rootSelection ) const -{ - for( int i = 0; i < m_fileTypes.count(); ++i ) { - if( term == m_fileTypes[i].second ) { - *index = i; - *rootSelection = File; - return true; - } - } - for( int i = 0; i < m_otherTypes.count(); ++i ) { - if( term == m_otherTypes[i].second ) { - *index = i; - *rootSelection = Other; - return true; - } - } - return false; -} - - -void Nepomuk::Utils::TypeFacet::Private::setRootSelection( RootSelection selection ) -{ - m_rootSelection = selection; - if( m_rootSelection == File ) - m_usedTypes = &m_fileTypes; - else if( m_rootSelection == Other ) - m_usedTypes = &m_otherTypes; - else - m_usedTypes = 0; -} - -Nepomuk::Utils::TypeFacet::TypeFacet(QObject *parent) - : Nepomuk::Utils::Facet(parent), - d(new Private()) -{ -} - - -Nepomuk::Utils::TypeFacet::~TypeFacet() -{ - delete d; -} - -Nepomuk::Utils::Facet::SelectionMode Nepomuk::Utils::TypeFacet::selectionMode() const -{ - return MatchAny; -} - -// while we do return file/other query terms even if there is no sub-selection we do not notify this change since -// to the user it should just be a preselection -Nepomuk::Query::Term Nepomuk::Utils::TypeFacet::queryTerm() const -{ - switch(d->m_rootSelection) { - case None: - return Query::Term(); - - case File: - if( d->m_selectedTypes.isEmpty() && d->m_selectedCustomTypes.isEmpty() ) { - return Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::FileDataObject()); - } - else { - Query::OrTerm term; - Q_FOREACH( int i, d->m_selectedTypes ) { - term.addSubTerm( d->m_fileTypes[i].second ); - } - Q_FOREACH( int i, d->m_selectedCustomTypes ) { - term.addSubTerm( Query::ResourceTypeTerm( d->m_customTypes[i] ) ); - } - return term.optimized(); - } - - case Other: - if( d->m_selectedTypes.isEmpty() && d->m_selectedCustomTypes.isEmpty() ) { - return Query::NegationTerm::negateTerm(Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::FileDataObject())); - } - else { - Query::OrTerm term; - Q_FOREACH( int i, d->m_selectedTypes ) { - term.addSubTerm( d->m_otherTypes[i].second ); - } - Q_FOREACH( int i, d->m_selectedCustomTypes ) { - term.addSubTerm( Query::ResourceTypeTerm( d->m_customTypes[i] ) ); - } - return term.optimized(); - } - } - - // make gcc shut up - return Query::Term(); -} - -int Nepomuk::Utils::TypeFacet::count() const -{ - if( d->m_rootSelection == None ) { - // File and Other - return 2; - } - else { - // File/Other selection + fixed types + custom types - return 1 + d->m_usedTypes->count() + d->m_customTypes.count(); - } -} - -KGuiItem Nepomuk::Utils::TypeFacet::guiItem(int index) const -{ - if( d->m_rootSelection == None ) { - switch( index ) { - case 0: - return KGuiItem(i18nc("@option:check Do filter on type - show only files", "Files")); - case 1: - return KGuiItem(i18nc("@option:check Do filter on type - show everything but files", "Other")); - break; - } - } - else { - if( index == 0 ) { - if( d->m_rootSelection == File ) - return KGuiItem(i18nc("@option:check Do filter on type - show only files", "Files")); - else - return KGuiItem(i18nc("@option:check Do filter on type - show everything but files", "Other")); - } - else { - --index; - } - if( index < d->m_usedTypes->count() ) { - return KGuiItem(d->m_usedTypes->at(index).first); - } - else if( index - d->m_usedTypes->count() < d->m_customTypes.count() ) { - return KGuiItem(d->m_customTypes[index - d->m_usedTypes->count()].label()); - } - } - - return KGuiItem(); -} - -bool Nepomuk::Utils::TypeFacet::isSelected(int index) const -{ - if( d->m_rootSelection == None ) { - return false; - } - else if( index == 0 ) { - return true; - } - else { - --index; - if( index < d->m_usedTypes->count() ) { - return d->m_selectedTypes.contains(index); - } - else { - index -= d->m_usedTypes->count(); - return d->m_selectedCustomTypes.contains(index); - } - } -} - -void Nepomuk::Utils::TypeFacet::clearSelection() -{ - kDebug(); - d->m_selectedTypes.clear(); - d->m_selectedCustomTypes.clear(); - d->m_customTypes.clear(); - d->setRootSelection(None); - setLayoutChanged(); - setSelectionChanged(); - setQueryTermChanged(); -} - -void Nepomuk::Utils::TypeFacet::setSelected(int index, bool selected) -{ - kDebug() << index << selected; - if( d->m_rootSelection == None ) { - if( selected ) { - if( index == 0 ) { - d->setRootSelection(File); - setLayoutChanged(); - setSelectionChanged(); - } - else if( index == 1 ) { - d->setRootSelection(Other); - setLayoutChanged(); - setSelectionChanged(); - } - } - } - else { - if( selected ) { - if( index > 0 ) { - --index; - if( index < d->m_usedTypes->count() ) { - kDebug() << "Checking fixed type" << index; - if( !d->m_selectedTypes.contains(index) ) { - d->m_selectedTypes.insert(index); - setSelectionChanged(); - setQueryTermChanged(); - } - } - else { - index -= d->m_usedTypes->count(); - kDebug() << "Checking custom type" << index; - if( index < d->m_customTypes.count() ) { - if( !d->m_selectedCustomTypes.contains(index) ) { - d->m_selectedCustomTypes.insert(index); - setSelectionChanged(); - setQueryTermChanged(); - } - } - } - } - } - else { - if( index == 0 ) { - clearSelection(); - } - else { - --index; - if( index < d->m_usedTypes->count() ) { - if( d->m_selectedTypes.contains(index) ) { - d->m_selectedTypes.remove(index); - setSelectionChanged(); - setQueryTermChanged(); - } - } - else { - index -= d->m_usedTypes->count(); - if( index < d->m_customTypes.count() ) { - if( d->m_selectedCustomTypes.contains(index) ) { - d->m_selectedCustomTypes.remove(index); - setSelectionChanged(); - setQueryTermChanged(); - } - } - } - } - } - } -} - -bool Nepomuk::Utils::TypeFacet::selectFromTerm(const Nepomuk::Query::Term &queryTerm) -{ - // 1. compare to all the terms in d->m_fileTypes and d->m_otherTypes - // 2. check if it is a ResourceTypeTerm - // 3. check if it is a negation of the file term - // 4. check if it is an OrTerm and do the above with all terms in it - // 5. do not add nfo:FileDataObject as a custom type! - - int index = -1; - RootSelection rootSel = None; - if( d->findTerm( queryTerm, &index, &rootSel ) ) { - if( d->m_rootSelection == None || - d->m_rootSelection == rootSel ) { - d->m_selectedTypes.insert(index); - setSelectionChanged(); - return true; - } - } - else if( queryTerm.isResourceTypeTerm() ) { - const Types::Class type = queryTerm.toResourceTypeTerm().type(); - if( type == Nepomuk::Vocabulary::NFO::FileDataObject() ) { - if( d->m_rootSelection == None ) { - setSelected(0); - return true; - } - else { - return d->m_rootSelection == File; - } - } - else { - const RootSelection reqSel = type.isSubClassOf(Nepomuk::Vocabulary::NFO::FileDataObject()) ? File : Other; - if( d->m_rootSelection == None ) { - d->setRootSelection(reqSel); - d->m_customTypes.append(type); - d->m_selectedCustomTypes.insert(d->m_customTypes.count()-1); - setLayoutChanged(); - setSelectionChanged(); - setQueryTermChanged(); - return true; - } - else if( d->m_rootSelection == reqSel ) { - if( !d->m_customTypes.contains(type) ) { - d->m_customTypes.append(type); - setLayoutChanged(); - } - d->m_selectedCustomTypes.insert(d->m_customTypes.indexOf(type)); - setSelectionChanged(); - setQueryTermChanged(); - return true; - } - } - } - else if( queryTerm.isNegationTerm() && - queryTerm.toNegationTerm().subTerm().isResourceTypeTerm() && - queryTerm.toNegationTerm().subTerm().toResourceTypeTerm().type() == Nepomuk::Vocabulary::NFO::FileDataObject() ) { - if( d->m_rootSelection == None ) { - setSelected(1); - return true; - } - else { - return d->m_rootSelection == Other; - } - } - - // fallback - return false; -} - -#include "typefacet.moc" diff --git a/nepomuk/utils/typefacet.h b/nepomuk/utils/typefacet.h deleted file mode 100644 index c21bf351..00000000 --- a/nepomuk/utils/typefacet.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_TYPEFACET_H_ -#define _NEPOMUK_TYPEFACET_H_ - -#include "facet.h" - -namespace Nepomuk { - namespace Utils { - - class TypeFacet : public Nepomuk::Utils::Facet - { - Q_OBJECT - - public: - TypeFacet( QObject *parent = 0 ); - ~TypeFacet(); - - SelectionMode selectionMode() const; - Query::Term queryTerm() const; - int count() const; - KGuiItem guiItem( int index ) const; - bool isSelected( int index ) const; - - public Q_SLOTS: - void clearSelection(); - void setSelected( int index, bool selected = true ); - bool selectFromTerm( const Nepomuk::Query::Term& queryTerm ); - - private: - class Private; - Private* const d; - }; - } -} - -#endif diff --git a/nepomuk/utils/utils.cpp b/nepomuk/utils/utils.cpp deleted file mode 100644 index d4c1f28c..00000000 --- a/nepomuk/utils/utils.cpp +++ /dev/null @@ -1,217 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#include "utils.h" - -#include "variant.h" -#include "resourcemanager.h" -#include "resource.h" - -#include "filequery.h" -#include "comparisonterm.h" -#include "andterm.h" -#include "resourceterm.h" -#include "resourcetypeterm.h" -#include "optionalterm.h" - -#include "nie.h" -#include "nfo.h" -#include "nuao.h" -#include "ndo.h" - -#include -#include -#include - -#include -#include -#include - - -QString Nepomuk::Utils::formatPropertyValue( const Nepomuk::Types::Property& property, - const Nepomuk::Variant& value, - const QList& resources, - PropertyFormatFlags flags ) -{ - // first handle lists - if( value.isList() ) { - QList values = value.toVariantList(); - QStringList valueStrings; - Q_FOREACH( const Variant& v, values ) { - valueStrings << formatPropertyValue( property, v, resources, flags ); - } - return valueStrings.join( QLatin1String(", ") ); - } - - // - // We handle the one special case of referrer URLs of downloads - // TODO: put stuff like this in a generic rule-based framework - // - if( property == Nepomuk::Vocabulary::NDO::copiedFrom() && - !resources.isEmpty() ) { - Nepomuk::Query::Query query( - Nepomuk::Query::AndTerm( - Nepomuk::Query::ResourceTypeTerm( - Nepomuk::Vocabulary::NDO::DownloadEvent() - ), - Nepomuk::Query::ComparisonTerm( - Nepomuk::Vocabulary::NUAO::involves(), - Nepomuk::Query::ResourceTerm(resources.first()) - ) - ) - ); - query.setLimit(1); - - QList results = - Nepomuk::ResourceManager::instance()->mainModel()->executeQuery( - query.toSparqlQuery(), - Soprano::Query::QueryLanguageSparql).iterateBindings(0).allNodes(); - if( !results.isEmpty() ) { - Nepomuk::Resource dlRes(results.first().uri()); - KUrl url; - QString label; - if( dlRes.hasProperty(Nepomuk::Vocabulary::NDO::referrer()) ) { - Nepomuk::Resource referrerWebPage = dlRes.property(Nepomuk::Vocabulary::NDO::referrer()).toResource(); - url = referrerWebPage.property(Nepomuk::Vocabulary::NIE::url()).toUrl(); - KUrl referrerDomain(url); - referrerDomain.setPath(QString()); - referrerDomain.setQuery(QString()); - label = referrerDomain.prettyUrl(); - } - else { - Nepomuk::Resource res(value.toResource()); - url = res.resourceUri(); - label = res.genericLabel(); - } - - if( flags & WithKioLinks ) { - return QString::fromLatin1("%2") - .arg(url.url(), label); - } - else { - return label; - } - } - } - - // do not use else here since the above code might fall through - - QString valueString; - if (value.isDateTime()) { - valueString = KGlobal::locale()->formatDateTime(value.toDateTime().toLocalTime(), KLocale::FancyLongDate); - } - - else if(value.isDouble()) { - valueString = KGlobal::locale()->formatNumber(value.toDouble()); - } - - else if(value.isInt() && property == Vocabulary::NFO::duration() ) { - QTime time = QTime().addSecs( value.toInt() ); - valueString = KGlobal::locale()->formatTime( time, true, true ); - } - - else if(value.isResource() && - value.toResource().exists()) { - valueString = value.toResource().genericLabel(); - } - - else if(property == Vocabulary::NIE::contentSize()) { - valueString = KGlobal::locale()->formatByteSize(value.toDouble()); - } - - else if(property == Vocabulary::NIE::mimeType()) { - KMimeType::Ptr mimeType = KMimeType::mimeType(value.toString()); - valueString = (mimeType ? mimeType->comment() : value.toString()); - } - - else { - valueString = value.toString(); - } - - if( flags & WithKioLinks ) { - // for all property/value pairs we create a default query - Nepomuk::Query::FileQuery query( Nepomuk::Query::Term::fromProperty(property, value) ); - return QString::fromLatin1("%2") - .arg(query.toSearchUrl(property.label() + QLatin1String(": '") + valueString + '\'').url(), - valueString); - } - else { - return valueString; - } -} - - -Nepomuk::Resource Nepomuk::Utils::createCopyEvent( const KUrl& srcUrl, const KUrl& destUrl, const QDateTime& startTime, const KUrl& referrer ) -{ - // - // Remember where a file was downloaded from the semantic way: - // We have two file resources: - // one for the source file (which in most cases is a remote file) - // and one for the destination file (which will be or is already indexed) - // the latter is marked as being copied from the former - // and then there is the download event which links to the referrer. - // - - QUrl srcType; - QUrl destType; - if(srcUrl.isLocalFile()) { - srcType = Nepomuk::Vocabulary::NFO::FileDataObject(); - } - else { - srcType = Nepomuk::Vocabulary::NFO::RemoteDataObject(); - } - if(destUrl.isLocalFile()) { - destType = Nepomuk::Vocabulary::NFO::FileDataObject(); - } - else { - destType = Nepomuk::Vocabulary::NFO::RemoteDataObject(); - } - - // source and dest resources - Nepomuk::Resource srcFileRes(srcUrl, srcType); - Nepomuk::Resource destFileRes(destUrl, destType); - srcFileRes.setProperty(Nepomuk::Vocabulary::NIE::url(), srcUrl); - destFileRes.setProperty(Nepomuk::Vocabulary::NIE::url(), destUrl); - - // relate src and dest - destFileRes.setProperty(Nepomuk::Vocabulary::NDO::copiedFrom(), srcFileRes); - - // details in the download event - Nepomuk::Resource downloadEventRes(QUrl(), Nepomuk::Vocabulary::NDO::DownloadEvent()); - downloadEventRes.addProperty(Nepomuk::Vocabulary::NUAO::involves(), destFileRes); - downloadEventRes.addProperty(Nepomuk::Vocabulary::NUAO::start(), startTime); - - // set the referrer - if(referrer.isValid()) { - // TODO: we could at this point index the referrer site via strigi - Nepomuk::Resource referrerRes(referrer, Nepomuk::Vocabulary::NFO::Website()); - downloadEventRes.addProperty(Nepomuk::Vocabulary::NDO::referrer(), referrerRes); - } - - return downloadEventRes; -} - - -void Nepomuk::Utils::finishCopyEvent( Resource& /*eventResource*/, const QDateTime& /*endTime*/ ) -{ - // FIXME: NUAO doesn't have end() yet. - // eventResource.setProperty(Nepomuk::Vocabulary::NUAO::end(), endTime); -} diff --git a/nepomuk/utils/utils.h b/nepomuk/utils/utils.h deleted file mode 100644 index 773c28e1..00000000 --- a/nepomuk/utils/utils.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - This file is part of the Nepomuk KDE project. - Copyright (C) 2010 Sebastian Trueg - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 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 6 of version 3 of the license. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library. If not, see . -*/ - -#ifndef _NEPOMUK_UTILS_GLOBAL_H_ -#define _NEPOMUK_UTILS_GLOBAL_H_ - -#include "nepomukutils_export.h" -#include "resource.h" - -#include -#include -#include - -#include "kurl.h" - -namespace Nepomuk { - class Variant; - - namespace Types { - class Property; - } - - namespace Utils { - /** - * Flags to change the behaviour of formatPropertyValue(). - * - * \since 4.6 - */ - enum PropertyFormatFlag { - /** - * No flags, ie. default behaviour. - */ - NoPropertyFormatFlags = 0x0, - - /** - * Include html links to %Nepomuk resources, files, and - * %Nepomuk queries. - */ - WithKioLinks = 0x1 - }; - Q_DECLARE_FLAGS( PropertyFormatFlags, PropertyFormatFlag ) - - /** - * Format a property to be displayed to the user. - * - * \param property The actual property to which the value applies to. - * \param value The actual value to be formatted. - * \param flags Optional flags to change the resulting string. - * \param resources The resources which the property applies to. Depending on the property - * the user readable representation might differ based on the resources' types. Using an - * empty list is perfectly valid. - * - * \return A user readable representation of the value which corresponds to \p resource - * and \p property. This string may contain Qt-style HTML tags for links and special formatting. - * - * \since 4.6 - */ - NEPOMUKUTILS_EXPORT QString formatPropertyValue( const Nepomuk::Types::Property& property, - const Nepomuk::Variant& value, - const QList& resources = QList(), - PropertyFormatFlags flags = NoPropertyFormatFlags ); - - /** - * Save a copy event in %Nepomuk stating that \p src has been copied to \p dest - * with an optional download \p startTime and an optional \p referrer URL that - * indicates from which webpage a download was initiated. - * - * \return The download event resource. Use finishCopyEvent() to store the event's end time. - * - * \since 4.6 - */ - NEPOMUKUTILS_EXPORT Nepomuk::Resource createCopyEvent( const KUrl& src, - const KUrl& dest, - const QDateTime& startTime = QDateTime(), - const KUrl& referrer = KUrl() ); - - /** - * Save the end time of a copy event created via createCopyEvent(). - * - * \param eventResource The resource returned by createCopyEvent(). - * \param endTime The time the copy event ended to the saved. - * - * \since 4.6 - */ - NEPOMUKUTILS_EXPORT void finishCopyEvent( Nepomuk::Resource& eventResource, const QDateTime& endTime ); - } -} - -Q_DECLARE_OPERATORS_FOR_FLAGS( Nepomuk::Utils::PropertyFormatFlags ) - -#endif diff --git a/solid/solid/backends/udisks2/udisksdevicebackend.h b/solid/solid/backends/udisks2/udisksdevicebackend.h index e7f3cc8f..0f11d517 100644 --- a/solid/solid/backends/udisks2/udisksdevicebackend.h +++ b/solid/solid/backends/udisks2/udisksdevicebackend.h @@ -82,4 +82,4 @@ class DeviceBackend: public QObject { } /* namespace Backends */ } /* namespace Solid */ -#endif /* UDISKSDEVICEBACKEND_H */ \ No newline at end of file +#endif /* UDISKSDEVICEBACKEND_H */