removed nepomuk support

This commit is contained in:
Ivailo Monev 2014-11-13 03:32:20 +02:00
parent af5c3ad053
commit 3c165c6f01
303 changed files with 2 additions and 43466 deletions

View file

@ -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)

View file

@ -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, <sebastian@trueg.de>
#
# 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)

View file

@ -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, <sebastian@trueg.de>
#
# 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})

View file

@ -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, <sebastian@trueg.de>
# Copyright (c) 2009, Alexander Neundorf, <neundorf@kde.org>
#
# 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
)

View file

@ -1,115 +0,0 @@
#
# Use the Nepomuk resource class generator to generate convinient Resource subclasses
# from ontologies.
#
# Usage:
# NEPOMUK_ADD_ONTOLOGY_CLASSES(<sources-var>
# [FAST]
# [ONTOLOGIES] <onto-file1> [<onto-file2> ...]
# [CLASSES <class1> [<class2> ...]]
# [VISIBILITY <visibility-name>]
# )
#
# 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 <visibility-name> 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 <trueg@kde.org>
#
# 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)

View file

@ -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 <trueg@kde.org>
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)

View file

@ -1 +0,0 @@
#cmakedefine HAVE_NEPOMUK

View file

@ -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

View file

@ -1 +0,0 @@
#include "../../nepomuk/file.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/kratingpainter.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/kratingwidget.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/nepomukmassupdatejob.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/andterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/comparisonterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/filequery.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/groupterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/literalterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/negationterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/optionalterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/orterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/query.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/queryparser.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/queryserviceclient.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/resourceterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/resourcetypeterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/result.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/simpleterm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/standardqueries.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/term.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/resource.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/resourcemanager.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/nepomukservice.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/tag.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/tagwidget.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/thing.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/class.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/literal.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/ontology.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/property.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/dynamicresourcefacet.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/facet.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/facetwidget.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/proxyfacet.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/resourcemodel.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/searchwidget.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/simplefacet.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/simpleresourcemodel.h"

View file

@ -1 +0,0 @@
#include "../../nepomuk/variant.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/ncal.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/nco.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/ndo.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/nexif.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/nfo.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/nie.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/nmm.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/nmo.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/nuao.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/pimo.h"

View file

@ -1 +0,0 @@
#include "../../../nepomuk/tmo.h"

View file

@ -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 {};

View file

@ -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)

View file

@ -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} )

View file

@ -1,150 +0,0 @@
/*****************************************************************************
* Copyright (C) 2008 by Sebastian Trueg <trueg@kde.org> *
* Copyright (C) 2009 by Peter Penz <peter.penz@gmx.at> *
* *
* 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 <kdialog.h>
#include <klocale.h>
#include <QEvent>
#include <QLabel>
#include <QPointer>
#include <QTextEdit>
#include <QVBoxLayout>
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 = "<a href=\"addComment\">" + i18nc("@label", "Add Comment...") + "</a>";
}
} else {
if (m_readOnly) {
text = Qt::escape(comment);
} else {
text = "<p>" + Qt::escape(comment) + " <a href=\"changeComment\">" + i18nc("@label", "Change...") + "</a></p>";
}
}
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<KDialog> 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"

View file

@ -1,69 +0,0 @@
/*****************************************************************************
* Copyright (C) 2008 by Sebastian Trueg <trueg@kde.org> *
* Copyright (C) 2009 by Peter Penz <peter.penz@gmx.at> *
* *
* 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 <QString>
#include <QWidget>
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

View file

@ -27,15 +27,6 @@
#include <klocale.h>
#include <config-kio.h>
#ifndef KIO_NO_NEPOMUK
#define DISABLE_NEPOMUK_LEGACY
#include <resource.h>
#include <resourcemanager.h>
#include <property.h>
#include <variant.h>
#include "kfilemetadataprovider_p.h"
#endif
#include <QEvent>
#include <QListWidget>
@ -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<KUrl, Nepomuk::Variant> data = m_provider->data();
QHash<KUrl, Nepomuk::Variant>::const_iterator it = data.constBegin();
while (it != data.constEnd()) {
addItem(it.key());
++it;
}
#endif
}
KFileMetaDataConfigurationWidget::KFileMetaDataConfigurationWidget(QWidget* parent) :

View file

@ -1,559 +0,0 @@
/*****************************************************************************
* Copyright (C) 2010 by Peter Penz <peter.penz@gmx.at> *
* *
* 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 <kfileitem.h>
#include <kfilemetadatareader_p.h>
#include "knfotranslator_p.h"
#include <klocale.h>
#include <kstandarddirs.h>
#include <kurl.h>
#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 <QEvent>
#include <QLabel>
// Required includes for subDirectoriesCount():
#ifdef Q_WS_WIN
#include <QDir>
#else
#include <dirent.h>
#include <QFile>
#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<Nepomuk::Tag>& 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<Nepomuk::Resource> resourceList() const;
QWidget* createRatingWidget(int rating, QWidget* parent);
QWidget* createTagWidget(const QList<Nepomuk::Tag>& 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<KFileItem> m_fileItems;
#ifndef KIO_NO_NEPOMUK
QHash<KUrl, Nepomuk::Variant> m_data;
QList<KFileMetaDataReader*> m_metaDataReaders;
KFileMetaDataReader* m_latestMetaDataReader;
QWeakPointer<KRatingWidget> m_ratingWidget;
QWeakPointer<Nepomuk::TagWidget> m_tagWidget;
QWeakPointer<KCommentWidget> 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<KFileMetaDataReader*>(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<Nepomuk::Tag>& 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<Nepomuk::Resource> KFileMetaDataProvider::Private::resourceList() const
{
QList<Nepomuk::Resource> 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<Nepomuk::Tag>& 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<Nepomuk::Tag>)),
q, SLOT(slotTagsChanged(QList<Nepomuk::Tag>)));
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<KUrl> 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<QString, QString> 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<KUrl, Nepomuk::Variant> 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<Nepomuk::Tag> 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 <faure@kde.org>
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"

View file

@ -1,145 +0,0 @@
/*****************************************************************************
* Copyright (C) 2010 by Peter Penz <peter.penz@gmx.at> *
* *
* 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 <kurl.h>
#include <QtCore/QHash>
#include <QtCore/QObject>
#include <QtCore/QString>
#include <config-kio.h>
#ifndef KIO_NO_NEPOMUK
#define DISABLE_NEPOMUK_LEGACY
#include <variant.h>
#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<KUrl, Nepomuk::Variant> 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<Nepomuk::Tag>& 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

View file

@ -1,146 +0,0 @@
/*****************************************************************************
* Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
* *
* 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 <kprocess.h>
#include <kstandarddirs.h>
class KFileMetaDataReader::Private
{
public:
Private(KFileMetaDataReader* parent);
~Private();
void slotLoadingFinished(int exitCode, QProcess::ExitStatus exitStatus);
bool m_readContextData;
KProcess* m_process;
QHash<KUrl, Nepomuk::Variant> 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<KUrl>& 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<KUrl, Nepomuk::Variant> KFileMetaDataReader::metaData() const
{
return d->m_metaData;
}
#include "kfilemetadatareader_p.moc"

View file

@ -1,92 +0,0 @@
/*****************************************************************************
* Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
* *
* 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 <kurl.h>
#include <nepomuk/core/variant.h>
#include <QtCore/QHash>
#include <QtCore/QList>
#include <QtCore/QObject>
#include <QtCore/QProcess>
#include <QtCore/QString>
/**
* @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<KUrl>& 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<KUrl, Nepomuk::Variant> 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

View file

@ -1,257 +0,0 @@
/*****************************************************************************
* Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
* *
* 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 <iostream>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kfilemetainfo.h>
#include <kcomponentdata.h>
#include <kconfiggroup.h>
#include <klocale.h>
#include <QtCore/QByteArray>
#include <QtCore/QCoreApplication>
#include <QtCore/QDataStream>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QTimer>
#define DISABLE_NEPOMUK_LEGACY
#include "config-nepomuk.h"
#include <nepomuk/query/filequery.h>
#include <nepomuk/query/comparisonterm.h>
#include <nepomuk/query/andterm.h>
#include <nepomuk/query/resourceterm.h>
#include <nepomuk/query/resourcetypeterm.h>
#include <nepomuk/query/optionalterm.h>
#include <nepomuk/utils/utils.h>
#include <nepomuk/types/property.h>
#include <nepomuk/core/tag.h>
#include <nepomuk/core/variant.h>
#include <nepomuk/core/resourcemanager.h>
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<KUrl, Nepomuk::Variant>& data);
QHash<KUrl, Nepomuk::Variant> readFileMetaData(const QList<KUrl>& urls) const;
QHash<KUrl, Nepomuk::Variant> readFileAndContextMetaData(const QList<KUrl>& 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<KUrl, Nepomuk::Variant> metaData;
if (args->isSet("file")) {
metaData = readFileMetaData(urls);
} else {
metaData = readFileAndContextMetaData(urls);
}
sendMetaData(metaData);
quit();
}
void KFileMetaDataReaderApplication::sendMetaData(const QHash<KUrl, Nepomuk::Variant>& data)
{
QByteArray byteArray;
QDataStream out(&byteArray, QIODevice::WriteOnly);
QHashIterator<KUrl, Nepomuk::Variant> 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<KUrl, Nepomuk::Variant> KFileMetaDataReaderApplication::readFileMetaData(const QList<KUrl>& urls) const
{
QHash<KUrl, Nepomuk::Variant> 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<QString, KFileMetaInfoItem> 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<KUrl, Nepomuk::Variant> KFileMetaDataReaderApplication::readFileAndContextMetaData(const QList<KUrl>& urls) const
{
QHash<KUrl, Nepomuk::Variant> 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<Nepomuk::Tag> 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<QUrl, Nepomuk::Variant> variants = file.properties();
QHash<QUrl, Nepomuk::Variant>::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<Nepomuk::Resource>() << 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<KUrl>() << 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<Nepomuk::Variant> 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"

View file

@ -33,16 +33,6 @@
#include <QTimer>
#include <config-kio.h>
#ifndef KIO_NO_NEPOMUK
#define DISABLE_NEPOMUK_LEGACY
#include <property.h>
#include <tag.h>
#include <QSpacerItem>
#include "kfilemetadataprovider_p.h"
#endif
class KFileMetaDataWidget::Private
{
@ -77,20 +67,8 @@ public:
void slotDataChangeStarted();
void slotDataChangeFinished();
#ifndef KIO_NO_NEPOMUK
QList<KUrl> sortedKeys(const QHash<KUrl, Nepomuk::Variant>& 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<Row> 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<KUrl, Nepomuk::Variant> 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<KUrl, Nepomuk::Variant>::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<KUrl> 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<KUrl> KFileMetaDataWidget::Private::sortedKeys(const QHash<KUrl, Nepomuk::Variant>& 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<QString, KUrl> map;
QHash<KUrl, Nepomuk::Variant>::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<KUrl> list;
QMap<QString, KUrl>::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

View file

@ -24,10 +24,6 @@
#include <kurl.h>
#include <config-kio.h>
#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) {

View file

@ -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
}
/*

View file

@ -21,7 +21,6 @@
#include "kfilemetainfoitem.h"
#include "kfilemetainfoitem_p.h"
#include <config-nepomuk.h>
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&

View file

@ -27,9 +27,6 @@
#ifndef KDE_NO_DEPRECATED
#include <predicateproperties.h>
#else
#ifndef KIO_NO_NEPOMUK
#include <nepomuk/types/property.h>
#endif
#endif
#include <QtCore/QHash>
@ -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;

View file

@ -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}

View file

@ -24,14 +24,8 @@
#include <kio/copyjob.h>
#include <kdebug.h>
#include "config-nepomuk.h"
#include <QtCore/QDateTime>
#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
}
}

View file

@ -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

View file

@ -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)

View file

@ -1,647 +0,0 @@
/*
This file is part of the Nepomuk KDE project.
Copyright (C) 2006-2010 Sebastian Trueg <trueg@kde.org>
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 <http://www.gnu.org/licenses/>.
*/
/** \mainpage The Nepomuk Meta Data Library
<p><b>
Overview |
\ref hacking "Using" |
\ref examples "Examples" |
\ref page_ontology "Desktop Ontologies" |
\ref nepomuk-rcgen "Resource Generator"
</b></p>
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
- <a href="http://techbase.kde.org/Development/Tutorials#Nepomuk">The Nepomuk techbase tutorials</a>
\authors
Sebastian Trueg \<trueg@kde.org\>
\maintainers
Sebastian Trueg \<trueg@kde.org\>
\licenses
\lgpl
*/
/** \page hacking Using Nepomuk
<p><b>
\ref index "Overview" |
Using |
\ref examples "Examples" |
\ref page_ontology "Desktop Ontologies" |
\ref nepomuk-rcgen "Resource Generator"
</b></p>
\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
<p><b>
\ref index "Overview" |
\ref hacking "Using" |
Examples |
\ref page_ontology "Desktop Ontologies" |
\ref nepomuk-rcgen "Resource Generator"
</b></p>
\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<Resource> tags = f.getProperty( Soprano::Vocabulary::NAO::hasTag() ).toResourceList();
QListIterator<Resource> 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<Tag> tags = f.getTags();
QListIterator<Tag> 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<QUrl, Variant> properties = f.properties();
QHashIterator<QUrl, Variant> 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
<a href="http://api.kde.org/kdesupport-api/kdesupport-apidocs/soprano/html/soprano_devel_tools.html">onto2vocabularyclass</a>
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
<p><b>
\ref index "Overview" |
\ref hacking "Using" |
\ref examples "Examples" |
Desktop Ontologies |
\ref nepomuk-rcgen "Resource Generator"
</b></p>
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
<p><b>
\ref index "Overview" |
\ref hacking "Using" |
\ref examples "Examples" |
\ref page_ontology "Desktop Ontologies" |
Resource Generator
</b></p>
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(<sources-var>
[FAST]
[ONTOLOGIES] <onto-file1> [<onto-file2> ...]
[CLASSES <classname1> [<classname2> ...]]
[VISIBILITY <visibility-name>]
)
\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 <visibility-name> 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

View file

@ -1,59 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2010 Sebastian Trueg <trueg@kde.org>
* Copyright (C) 2010 David Faure <faure@kde.org>
*
* 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 <QThreadStorage>
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<DBusConnectionPoolPrivate *> s_perThreadConnection;
QDBusConnection DBusConnectionPool::threadConnection()
{
if (!s_perThreadConnection.hasLocalData()) {
s_perThreadConnection.setLocalData(new DBusConnectionPoolPrivate);
}
return s_perThreadConnection.localData()->connection();
}

View file

@ -1,39 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2010 Sebastian Trueg <trueg@kde.org>
*
* 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 <QtDBus/QDBusConnection>
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

View file

@ -1,136 +0,0 @@
/*
This file is part of the Nepomuk KDE project.
Copyright (C) 2011 Sebastian Trueg <trueg@kde.org>
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 <http://www.gnu.org/licenses/>.
*/
#include "dbustypes.h"
#include <QtCore/QStringList>
#include <QtCore/QDate>
#include <QtCore/QTime>
#include <QtCore/QDateTime>
#include <QtDBus/QDBusMetaType>
#include "kurl.h"
#include "kdebug.h"
QString Nepomuk::DBus::convertUri(const QUrl& uri)
{
return KUrl(uri).url();
}
QStringList Nepomuk::DBus::convertUriList(const QList<QUrl>& uris)
{
QStringList uriStrings;
foreach(const QUrl& uri, uris)
uriStrings << convertUri(uri);
return uriStrings;
}
QVariantList Nepomuk::DBus::normalizeVariantList(const QVariantList& l)
{
QVariantList newL;
QListIterator<QVariant> it(l);
while(it.hasNext()) {
QVariant v = it.next();
if(v.userType() == qMetaTypeId<KUrl>()) {
newL.append(QVariant(QUrl(v.value<KUrl>())));
}
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<QDBusArgument>()) {
const QDBusArgument arg = v.value<QDBusArgument>();
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<QVariant> 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<QUrl>();
}
// 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;
}

View file

@ -1,59 +0,0 @@
/*
This file is part of the Nepomuk KDE project.
Copyright (C) 2011 Sebastian Trueg <trueg@kde.org>
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 <http://www.gnu.org/licenses/>.
*/
#ifndef DBUSTYPES_H
#define DBUSTYPES_H
#include <QtCore/QMetaType>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QUrl>
#include <QtDBus/QDBusVariant>
#include <QtDBus/QDBusArgument>
// #include "simpleresource.h"
// #include "nepomukdatamanagement_export.h"
#include "nepomuk_export.h"
//CAUTION: Q_DECLARE_METATYPE doesn't accept template arguments like QHash<T, T>
typedef QHash<QString, QString> __nepomuk_QHashQStringQString;
Q_DECLARE_METATYPE( __nepomuk_QHashQStringQString )
namespace Nepomuk {
namespace DBus {
QString NEPOMUK_EXPORT convertUri(const QUrl& uri);
QStringList NEPOMUK_EXPORT convertUriList(const QList<QUrl>& 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

View file

@ -1,65 +0,0 @@
/*
This file is part of the Nepomuk KDE project.
Copyright (C) 2010 Sebastian Trueg <trueg@kde.org>
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 <http://www.gnu.org/licenses/>.
*/
#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();
}
}

View file

@ -1,89 +0,0 @@
/*
This file is part of the Nepomuk KDE project.
Copyright (C) 2010 Sebastian Trueg <trueg@kde.org>
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 <http://www.gnu.org/licenses/>.
*/
#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 <trueg@kde.org>
*
* \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

View file

@ -1,265 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2008-2012 Sebastian Trueg <trueg@kde.org>
*
* 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 <Soprano/Node>
#include <Soprano/Statement>
#include <Soprano/StatementIterator>
#include <Soprano/NodeIterator>
#include <Soprano/QueryResultIterator>
#include <Soprano/Query/QueryLanguage>
#include <Soprano/Util/DummyModel>
#include <Soprano/StorageModel>
#include <Soprano/Backend>
#include <Soprano/PluginManager>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <ksharedconfig.h>
#include <kconfiggroup.h>
#include <QtCore/QTimer>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
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"

View file

@ -1,126 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2008-2010 Sebastian Trueg <trueg@kde.org>
*
* 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 <Soprano/Model>
#include <Soprano/Vocabulary/RDFS>
#include <QtCore/QDateTime>
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 <trueg@kde.org>
*
* \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

View file

@ -1,62 +0,0 @@
/* This file is part of the KDE Project
Copyright (c) 2008 Sebastian Trueg <trueg@kde.org>
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 <QtCore/QTimer>
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"

View file

@ -1,145 +0,0 @@
/* This file is part of the KDE Project
Copyright (c) 2008 Sebastian Trueg <trueg@kde.org>
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 <QtCore/QObject>
#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 <trueg@kde.org>
*
* \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<classname>();) \
K_EXPORT_PLUGIN(factory(#libname))
#endif

View file

@ -1,14 +0,0 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.kde.nepomuk.ResourceWatcher">
<method name="stopWatcher">
<arg name="objectName" type="s" direction="in"/>
</method>
<method name="watch">
<arg name="resources" type="as" direction="in"/>
<arg name="properties" type="as" direction="in"/>
<arg name="types" type="as" direction="in"/>
<arg name="queryobject" type="o" direction="out" />
</method>
</interface>
</node>

View file

@ -1,65 +0,0 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.kde.nepomuk.ResourceWatcherConnection">
<signal name="resourceCreated">
<arg name="uri" type="s" direction="out"/>
<arg name="types" type="as" direction="out"/>
</signal>
<signal name="resourceRemoved">
<arg name="uri" type="s" direction="out"/>
<arg name="types" type="as" direction="out"/>
</signal>
<signal name="resourceTypeAdded">
<arg name="resUri" type="s" direction="out"/>
<arg name="type" type="s" direction="out"/>
</signal>
<signal name="resourceTypeRemoved">
<arg name="resUri" type="s" direction="out"/>
<arg name="type" type="s" direction="out"/>
</signal>
<signal name="propertyAdded">
<arg name="resource" type="s" direction="out"/>
<arg name="property" type="s" direction="out"/>
<arg name="values" type="av" direction="out"/>
</signal>
<signal name="propertyRemoved">
<arg name="resource" type="s" direction="out"/>
<arg name="property" type="s" direction="out"/>
<arg name="values" type="av" direction="out"/>
</signal>
<signal name="propertyChanged">
<arg name="resource" type="s" direction="out"/>
<arg name="property" type="s" direction="out"/>
<arg name="oldValues" type="av" direction="out"/>
<arg name="newValues" type="av" direction="out"/>
</signal>
<method name="setResources">
<arg name="resources" type="as" direction="in"/>
</method>
<method name="addResource">
<arg name="resource" type="s" direction="in"/>
</method>
<method name="removeResource">
<arg name="resource" type="s" direction="in"/>
</method>
<method name="setProperties">
<arg name="properties" type="as" direction="in"/>
</method>
<method name="addProperty">
<arg name="property" type="s" direction="in"/>
</method>
<method name="removeProperty">
<arg name="property" type="s" direction="in"/>
</method>
<method name="setTypes">
<arg name="types" type="as" direction="in"/>
</method>
<method name="addType">
<arg name="type" type="s" direction="in"/>
</method>
<method name="removeType">
<arg name="type" type="s" direction="in"/>
</method>
<method name="close" />
</interface>
</node>

File diff suppressed because it is too large Load diff

View file

@ -1,810 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2006-2009 Sebastian Trueg <trueg@kde.org>
*
* 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 <QtCore/QHash>
#include <QtCore/QStringList>
#include <kurl.h>
#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/<UUID> 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/<UUID>.
*
* \author Sebastian Trueg <trueg@kde.org>
*/
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<QUrl> types() const;
/**
* Set the types of the resource. Previous types will be overwritten.
*
* \since 4.2
*/
void setTypes( const QList<QUrl>& 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<QString, Variant> allProperties() const;
#endif
/**
* \return A list of all defined properties
*/
QHash<QUrl, Variant> 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<Resource> annotations() const;
/**
* Set property 'annotation'.
*/
void setAnnotations( const QList<Resource>& 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<Tag> 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<Tag>& 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<Resource> topics() const;
/**
* Set property 'Topic'.
*/
void setTopics( const QList<Resource>& 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<Resource> isTopicOfs() const;
/**
* Set property 'isTopicOf'.
*/
void setIsTopicOfs( const QList<Resource>& 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<Resource> isRelateds() const;
/**
* Set property 'isRelated'.
*/
void setIsRelateds( const QList<Resource>& 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<Resource> annotationOf() const;
/**
* Get all resources that have this resource set as property 'isRelated'.
* \sa ResourceManager::allResourcesWithProperty
*/
QList<Resource> 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<Resource> 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

View file

@ -1,858 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2006-2010 Sebastian Trueg <trueg@kde.org>
* Copyright (C) 2010-2012 Vishesh Handa <handa.vish@gmail.com>
*
* 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 <Soprano/Statement>
#include <Soprano/StatementIterator>
#include <Soprano/QueryResultIterator>
#include <Soprano/Model>
#include <Soprano/Vocabulary/RDFS>
#include <Soprano/Vocabulary/RDF>
#include <Soprano/Vocabulary/Xesam>
#include <Soprano/Vocabulary/NAO>
#include <QtCore/QFile>
#include <QtCore/QDateTime>
#include <QtCore/QMutexLocker>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusReply>
#include <kdebug.h>
#include <kurl.h>
#include <kcomponentdata.h>
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<QUrl> Nepomuk::ResourceData::allTypes()
{
load();
return m_types;
}
void Nepomuk::ResourceData::setTypes( const QList<QUrl>& types )
{
store();
QMutexLocker lock(&m_modificationMutex);
// reset types
m_types.clear();
m_mainType = Soprano::Vocabulary::RDFS::Resource();
QList<Node> 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<QUrl, Nepomuk::Variant> Nepomuk::ResourceData::allProperties()
{
load();
return m_cache;
}
bool Nepomuk::ResourceData::hasProperty( const QUrl& uri )
{
load();
QHash<QUrl, Variant>::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<QUrl, Variant>::const_iterator it = m_cache.constFind( p );
if( it == m_cache.constEnd() )
return false;
QList<Variant> thisVals = it.value().toVariantList();
QList<Variant> 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<QUrl>::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<QUrl, Variant>::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>() ) {
Resource res = var.toResource();
res.determineFinalResourceData();
res.m_data->store();
varList << res.resourceUri();
}
else {
varList << var.variant();
}
}
msg.setArguments( QVariantList()
<< DBus::convertUriList(QList<QUrl>() << 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>() ) {
Resource res = var.toResource();
res.determineFinalResourceData();
res.m_data->store();
varList << res.resourceUri();
}
else {
varList << var.variant();
}
}
msg.setArguments( QVariantList()
<< DBus::convertUriList(QList<QUrl>() << 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 );
}
}
}

View file

@ -1,220 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2006-2010 Sebastian Trueg <trueg@kde.org>
*
* 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 <QtCore/QString>
#include <QtCore/QList>
#include <QtCore/QHash>
#include <QtCore/QMutex>
#include <QtCore/QAtomicInt>
#include <QtCore/QSet>
#include "variant.h"
#include "thing.h"
#include <kurl.h>
#include <soprano/statement.h>
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<QUrl> allTypes();
void setTypes( const QList<QUrl>& types );
QHash<QUrl, Variant> 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<Resource*> 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<KUrl> m_kickoffUris;
QHash<QUrl, Variant> 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<QUrl> 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

View file

@ -1,562 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2006-2012 Sebastian Trueg <trueg@kde.org>
* Copyright (C) 2010 Vishesh Handa <handa.vish@gmail.com>
*
* 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 <kglobal.h>
#include <kdebug.h>
#include <krandom.h>
#include <Soprano/Node>
#include <Soprano/Statement>
#include <Soprano/Vocabulary/RDF>
#include <Soprano/StatementIterator>
#include <Soprano/QueryResultIterator>
#include <QtCore/QFileInfo>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QUuid>
#include <QtCore/QMutableHashIterator>
#include <QtCore/QCoreApplication>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
#include <QtDBus/QDBusServiceWatcher>
#include <QtDBus/QDBusMetaType>
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::ResourceData*> Nepomuk::ResourceManagerPrivate::allResourceDataOfType( const QUrl& type )
{
QList<ResourceData*> l;
if( !type.isEmpty() ) {
mutex.lock();
QSet<ResourceData*> rdl = m_uriKickoffData.values().toSet();
mutex.unlock();
for( QSet<ResourceData*>::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::ResourceData*> Nepomuk::ResourceManagerPrivate::allResourceDataWithProperty( const QUrl& uri, const Variant& v )
{
QList<ResourceData*> l;
//
// We need to cache m_uriKickoffData since it might be changed
// in the loop by ResourceData::load()
//
mutex.lock();
QSet<ResourceData*> 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<Resource> tmp;
foreach( ResourceData* rd, rdl ) {
tmp << Resource( rd );
}
for( QSet<ResourceData*>::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::ResourceData*> Nepomuk::ResourceManagerPrivate::allResourceData()
{
return m_uriKickoffData.values().toSet().toList();
}
void Nepomuk::ResourceManagerPrivate::cleanupCache( int num )
{
QMutexLocker lock( &mutex );
QSet<ResourceData*> rdl = m_uriKickoffData.values().toSet() + m_initializedData.values().toSet();
for( QSet<ResourceData*>::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<KUrl> & 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::Resource> Nepomuk::ResourceManager::allResourcesOfType( const QString& type )
{
return allResourcesOfType( QUrl(type) );
}
#endif
QList<Nepomuk::Resource> Nepomuk::ResourceManager::allResourcesOfType( const QUrl& type )
{
QSet<Resource> set;
if( !type.isEmpty() ) {
// check local data
QList<ResourceData*> localData = d->allResourceDataOfType( type );
for( QList<ResourceData*>::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::Resource> Nepomuk::ResourceManager::allResources()
{
QList<Nepomuk::Resource> 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::Resource> Nepomuk::ResourceManager::allResourcesWithProperty( const QString& uri, const Variant& v )
{
return allResourcesWithProperty( QUrl(uri), v );
}
#endif
QList<Nepomuk::Resource> Nepomuk::ResourceManager::allResourcesWithProperty( const QUrl& uri, const Variant& v )
{
QSet<Resource> set;
if( v.isList() ) {
kDebug() << "(ResourceManager::allResourcesWithProperty) list values not supported.";
}
else {
// check local data
QList<ResourceData*> localData = d->allResourceDataWithProperty( uri, v );
for( QList<ResourceData*>::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<QUrl, Variant>::iterator cacheIt = data->m_cache.find(prop.uri());
if(cacheIt != data->m_cache.end()) {
Variant v = *cacheIt;
const Variant value(value_);
QList<Variant> 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"

View file

@ -1,289 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2006-2009 Sebastian Trueg <trueg@kde.org>
*
* 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 <QtCore/QObject>
#include <QtCore/QUrl>
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 <trueg@kde.org>
*/
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<Resource> 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<Resource> allResourcesOfType( const QUrl& type );
/**
* \deprecated Use allResourcesOfType( const QString& type )
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED QList<Resource> 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<Resource> allResourcesWithProperty( const QUrl& uri, const Variant& v );
/**
* \deprecated Use allResourcesWithProperty( const QString& type )
*/
#ifndef KDE_NO_DEPRECATED
KDE_DEPRECATED QList<Resource> 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

View file

@ -1,131 +0,0 @@
/*
* This file is part of the Nepomuk KDE project.
* Copyright (C) 2006-2009 Sebastian Trueg <trueg@kde.org>
*
* 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 <QtCore/QMutex>
#include <kurl.h>
#include <Soprano/Node> // for qHash(QUrl)
#include "resourcedata.h"
namespace Soprano {
class Model;
}
namespace Nepomuk {
class ResourceManager;
class MainModel;
class ResourceWatcher;
typedef QHash<KUrl, Nepomuk::ResourceData*> 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<KUrl>& uris );
QList<ResourceData*> allResourceData();
QList<ResourceData*> allResourceDataOfType( const QUrl& type );
QList<ResourceData*> 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

View file

@ -1,307 +0,0 @@
/*
This file is part of the Nepomuk KDE project.
Copyright (C) 2011 Vishesh Handa <handa.vish@gmail.com>
Copyright (C) 2011 Sebastian Trueg <trueg@kde.org>
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 <QtDBus>
#include "resource.h"
#include "kurl.h"
#include "kdebug.h"
namespace {
QString convertUri(const QUrl& uri) {
return KUrl(uri).url();
}
QStringList convertUris(const QList<QUrl>& uris) {
QStringList cs;
foreach(const QUrl& uri, uris) {
cs << convertUri(uri);
}
return cs;
}
QList<QUrl> convertUris(const QStringList& uris) {
QList<QUrl> us;
foreach(const QString& uri, uris) {
us << KUrl(uri);
}
return us;
}
}
class Nepomuk::ResourceWatcher::Private {
public:
QList<QUrl> m_types;
QList<QUrl> m_resources;
QList<QUrl> 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<QString> uris = convertUris(d->m_resources);
QList<QString> props = convertUris(d->m_properties);
QList<QString> 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<QDBusObjectPath> 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::Resource> Nepomuk::ResourceWatcher::resources() const
{
QList<Nepomuk::Resource> resources;
foreach(const QUrl& uri, d->m_resources)
resources << Resource::fromResourceUri(uri);
return resources;
}
QList< Nepomuk::Types::Class > Nepomuk::ResourceWatcher::types() const
{
QList<Nepomuk::Types::Class> 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"

Some files were not shown because too many files have changed in this diff Show more