unity-scopes-shell-0.4.0+14.04.20140408/0000755000015301777760000000000012320777302017665 5ustar pbusernogroup00000000000000unity-scopes-shell-0.4.0+14.04.20140408/cmake/0000755000015301777760000000000012320777302020745 5ustar pbusernogroup00000000000000unity-scopes-shell-0.4.0+14.04.20140408/cmake/modules/0000755000015301777760000000000012320777302022415 5ustar pbusernogroup00000000000000unity-scopes-shell-0.4.0+14.04.20140408/cmake/modules/FindLcov.cmake0000644000015301777760000000172012320776744025134 0ustar pbusernogroup00000000000000# - Find lcov # Will define: # # LCOV_EXECUTABLE - the lcov binary # GENHTML_EXECUTABLE - the genhtml executable # # Copyright (C) 2010 by Johannes Wienke # # This program is free software; you can redistribute it # and/or modify it under the terms of the GNU General # Public License as published by the Free Software Foundation; # either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # INCLUDE(FindPackageHandleStandardArgs) FIND_PROGRAM(LCOV_EXECUTABLE lcov) FIND_PROGRAM(GENHTML_EXECUTABLE genhtml) FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lcov DEFAULT_MSG LCOV_EXECUTABLE GENHTML_EXECUTABLE) # only visible in advanced view MARK_AS_ADVANCED(LCOV_EXECUTABLE GENHTML_EXECUTABLE) unity-scopes-shell-0.4.0+14.04.20140408/cmake/modules/EnableCoverageReport.cmake0000644000015301777760000001661112320776744027473 0ustar pbusernogroup00000000000000# - Creates a special coverage build type and target on GCC. # # Defines a function ENABLE_COVERAGE_REPORT which generates the coverage target # for selected targets. Optional arguments to this function are used to filter # unwanted results using globbing expressions. Moreover targets with tests for # the source code can be specified to trigger regenerating the report if the # test has changed # # ENABLE_COVERAGE_REPORT(TARGETS target... [FILTER filter...] [TESTS test targets...]) # # To generate a coverage report first build the project with # CMAKE_BUILD_TYPE=coverage, then call make test and afterwards make coverage. # # The coverage report is based on gcov. Depending on the availability of lcov # a HTML report will be generated and/or an XML report of gcovr is found. # The generated coverage target executes all found solutions. Special targets # exist to create e.g. only the xml report: coverage-xml. # # Copyright (C) 2010 by Johannes Wienke # # This program is free software; you can redistribute it # and/or modify it under the terms of the GNU General # Public License as published by the Free Software Foundation; # either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # INCLUDE(ParseArguments) FIND_PACKAGE(Lcov) FIND_PACKAGE(gcovr) FUNCTION(ENABLE_COVERAGE_REPORT) # argument parsing PARSE_ARGUMENTS(ARG "FILTER;TARGETS;TESTS" "" ${ARGN}) SET(COVERAGE_RAW_FILE "${CMAKE_BINARY_DIR}/coverage.raw.info") SET(COVERAGE_FILTERED_FILE "${CMAKE_BINARY_DIR}/coverage.info") SET(COVERAGE_REPORT_DIR "${CMAKE_BINARY_DIR}/coveragereport") SET(COVERAGE_XML_FILE "${CMAKE_BINARY_DIR}/coverage.xml") SET(COVERAGE_XML_COMMAND_FILE "${CMAKE_BINARY_DIR}/coverage-xml.cmake") # decide if there is any tool to create coverage data SET(TOOL_FOUND FALSE) IF(LCOV_FOUND OR GCOVR_FOUND) SET(TOOL_FOUND TRUE) ENDIF() IF(NOT TOOL_FOUND) MESSAGE(STATUS "Cannot enable coverage targets because neither lcov nor gcovr are found.") ENDIF() STRING(TOLOWER "${CMAKE_BUILD_TYPE}" COVERAGE_BUILD_TYPE) IF(CMAKE_COMPILER_IS_GNUCXX AND TOOL_FOUND AND "${COVERAGE_BUILD_TYPE}" MATCHES "coverage") MESSAGE(STATUS "Coverage support enabled for targets: ${ARG_TARGETS}") # create coverage build type SET(CMAKE_CXX_FLAGS_COVERAGE ${CMAKE_CXX_FLAGS_DEBUG} PARENT_SCOPE) SET(CMAKE_C_FLAGS_COVERAGE ${CMAKE_C_FLAGS_DEBUG} PARENT_SCOPE) SET(CMAKE_CONFIGURATION_TYPES ${CMAKE_CONFIGURATION_TYPES} coverage PARENT_SCOPE) # instrument targets SET_TARGET_PROPERTIES(${ARG_TARGETS} PROPERTIES COMPILE_FLAGS --coverage LINK_FLAGS --coverage) # html report IF (LCOV_FOUND) MESSAGE(STATUS "Enabling HTML coverage report") # set up coverage target ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_RAW_FILE} COMMAND ${LCOV_EXECUTABLE} -c -d ${CMAKE_BINARY_DIR} -o ${COVERAGE_RAW_FILE} WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMENT "Collecting coverage data" DEPENDS ${ARG_TARGETS} ${ARG_TESTS} VERBATIM) # filter unwanted stuff LIST(LENGTH ARG_FILTER FILTER_LENGTH) IF(${FILTER_LENGTH} GREATER 0) SET(FILTER COMMAND ${LCOV_EXECUTABLE}) FOREACH(F ${ARG_FILTER}) SET(FILTER ${FILTER} -r ${COVERAGE_FILTERED_FILE} ${F}) ENDFOREACH() SET(FILTER ${FILTER} -o ${COVERAGE_FILTERED_FILE}) ELSE() SET(FILTER "") ENDIF() ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_FILTERED_FILE} COMMAND ${LCOV_EXECUTABLE} -e ${COVERAGE_RAW_FILE} "${CMAKE_SOURCE_DIR}*" -o ${COVERAGE_FILTERED_FILE} ${FILTER} DEPENDS ${COVERAGE_RAW_FILE} COMMENT "Filtering recorded coverage data for project-relevant entries" VERBATIM) ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_REPORT_DIR} COMMAND ${CMAKE_COMMAND} -E make_directory ${COVERAGE_REPORT_DIR} COMMAND ${GENHTML_EXECUTABLE} --legend --show-details -t "${PROJECT_NAME} test coverage" -o ${COVERAGE_REPORT_DIR} ${COVERAGE_FILTERED_FILE} DEPENDS ${COVERAGE_FILTERED_FILE} COMMENT "Generating HTML coverage report in ${COVERAGE_REPORT_DIR}" VERBATIM) ADD_CUSTOM_TARGET(coverage-html DEPENDS ${COVERAGE_REPORT_DIR}) ENDIF() # xml coverage report IF(GCOVR_FOUND) MESSAGE(STATUS "Enabling XML coverage report") # filter unwanted stuff SET(GCOV_FILTER "") LIST(LENGTH ARG_FILTER FILTER_LENGTH) IF(${FILTER_LENGTH} GREATER 0) FOREACH(F ${ARG_FILTER}) SET(GCOV_FILTER "${GCOV_FILTER} -e \"${F}\"") ENDFOREACH() ENDIF() # gcovr cannot write directly to a file so the execution needs to # be wrapped in a cmake file that generates the file output FILE(WRITE ${COVERAGE_XML_COMMAND_FILE} "SET(ENV{LANG} en)\n") FILE(APPEND ${COVERAGE_XML_COMMAND_FILE} "EXECUTE_PROCESS(COMMAND \"${GCOVR_EXECUTABLE}\" -x -r \"${CMAKE_SOURCE_DIR}\" ${GCOV_FILTER} OUTPUT_FILE \"${COVERAGE_XML_FILE}\" WORKING_DIRECTORY \"${CMAKE_BINARY_DIR}\")\n") ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_XML_FILE} COMMAND ${CMAKE_COMMAND} ARGS -P ${COVERAGE_XML_COMMAND_FILE} COMMENT "Generating coverage XML report" VERBATIM) ADD_CUSTOM_TARGET(coverage-xml DEPENDS ${COVERAGE_XML_FILE}) ENDIF() # provide a global coverage target executing both steps if available SET(GLOBAL_DEPENDS "") IF(LCOV_FOUND) LIST(APPEND GLOBAL_DEPENDS ${COVERAGE_REPORT_DIR}) ENDIF() IF(GCOVR_FOUND) LIST(APPEND GLOBAL_DEPENDS ${COVERAGE_XML_FILE}) ENDIF() IF(LCOV_FOUND OR GCOVR_FOUND) ADD_CUSTOM_TARGET(coverage DEPENDS ${GLOBAL_DEPENDS}) ENDIF() ENDIF() # This gets rid of any stale .gcda files. Run this if a running a binary causes lots of messages about # about a "merge mismatch for summaries". ADD_CUSTOM_TARGET(clean-coverage COMMAND find ${CMAKE_BINARY_DIR} -name '*.gcda' | xargs rm -f COMMAND rm -rf "${CMAKE_BINARY_DIR}/coveragereport" "${CMAKE_BINARY_DIR}/coverage.info" "${CMAKE_BINARY_DIR}/coverage.raw.info") ENDFUNCTION() unity-scopes-shell-0.4.0+14.04.20140408/cmake/modules/Findgcovr.cmake0000644000015301777760000000170212320776744025351 0ustar pbusernogroup00000000000000# - Find gcovr scrip # Will define: # # GCOVR_EXECUTABLE - the gcovr script # # Uses: # # GCOVR_ROOT - root to search for the script # # Copyright (C) 2011 by Johannes Wienke # # This program is free software; you can redistribute it # and/or modify it under the terms of the GNU General # Public License as published by the Free Software Foundation; # either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # INCLUDE(FindPackageHandleStandardArgs) FIND_PROGRAM(GCOVR_EXECUTABLE gcovr HINTS ${GCOVR_ROOT} "${GCOVR_ROOT}/bin") FIND_PACKAGE_HANDLE_STANDARD_ARGS(gcovr DEFAULT_MSG GCOVR_EXECUTABLE) # only visible in advanced view MARK_AS_ADVANCED(GCOVR_EXECUTABLE) unity-scopes-shell-0.4.0+14.04.20140408/cmake/modules/ParseArguments.cmake0000644000015301777760000000340612320776744026373 0ustar pbusernogroup00000000000000# Parse arguments passed to a function into several lists separated by # upper-case identifiers and options that do not have an associated list e.g.: # # SET(arguments # hello OPTION3 world # LIST3 foo bar # OPTION2 # LIST1 fuz baz # ) # PARSE_ARGUMENTS(ARG "LIST1;LIST2;LIST3" "OPTION1;OPTION2;OPTION3" ${arguments}) # # results in 7 distinct variables: # * ARG_DEFAULT_ARGS: hello;world # * ARG_LIST1: fuz;baz # * ARG_LIST2: # * ARG_LIST3: foo;bar # * ARG_OPTION1: FALSE # * ARG_OPTION2: TRUE # * ARG_OPTION3: TRUE # # taken from http://www.cmake.org/Wiki/CMakeMacroParseArguments MACRO(PARSE_ARGUMENTS prefix arg_names option_names) SET(DEFAULT_ARGS) FOREACH(arg_name ${arg_names}) SET(${prefix}_${arg_name}) ENDFOREACH(arg_name) FOREACH(option ${option_names}) SET(${prefix}_${option} FALSE) ENDFOREACH(option) SET(current_arg_name DEFAULT_ARGS) SET(current_arg_list) FOREACH(arg ${ARGN}) SET(larg_names ${arg_names}) LIST(FIND larg_names "${arg}" is_arg_name) IF (is_arg_name GREATER -1) SET(${prefix}_${current_arg_name} ${current_arg_list}) SET(current_arg_name ${arg}) SET(current_arg_list) ELSE (is_arg_name GREATER -1) SET(loption_names ${option_names}) LIST(FIND loption_names "${arg}" is_option) IF (is_option GREATER -1) SET(${prefix}_${arg} TRUE) ELSE (is_option GREATER -1) SET(current_arg_list ${current_arg_list} ${arg}) ENDIF (is_option GREATER -1) ENDIF (is_arg_name GREATER -1) ENDFOREACH(arg) SET(${prefix}_${current_arg_name} ${current_arg_list}) ENDMACRO(PARSE_ARGUMENTS) unity-scopes-shell-0.4.0+14.04.20140408/cmake/modules/Plugins.cmake0000644000015301777760000000415312320776744025054 0ustar pbusernogroup00000000000000find_program(qmlplugindump_exe qmlplugindump) if(NOT qmlplugindump_exe) msg(FATAL_ERROR "Could not locate qmlplugindump.") endif() # Creates target for copying and installing qmlfiles # # export_qmlfiles(plugin sub_path) # # # Target to be created: # - plugin-qmlfiles - Copies the qml files (*.qml, *.js, qmldir) into the shadow build folder. macro(export_qmlfiles PLUGIN PLUGIN_SUBPATH) file(GLOB QMLFILES *.qml *.js qmldir ) # copy the qmldir file add_custom_target(${PLUGIN}-qmlfiles ALL COMMAND cp ${QMLFILES} ${CMAKE_CURRENT_BINARY_DIR} DEPENDS ${QMLFILES} ) # install the qmlfiles file. install(FILES ${QMLFILES} DESTINATION ${SHELL_PLUGINDIR}/${PLUGIN_SUBPATH} ) endmacro(export_qmlfiles) # Creates target for generating the qmltypes file for a plugin and installs plugin files # # export_qmlplugin(plugin version sub_path [TARGETS target1 [target2 ...]]) # # TARGETS additional install targets (eg the plugin shared object) # # Target to be created: # - plugin-qmltypes - Generates the qmltypes file in the shadow build folder. macro(export_qmlplugin PLUGIN VERSION PLUGIN_SUBPATH) set(multi_value_keywords TARGETS) cmake_parse_arguments(qmlplugin "" "" "${multi_value_keywords}" ${ARGN}) # Only try to generate .qmltypes if not cross compiling if(NOT CMAKE_CROSSCOMPILING) # create the plugin.qmltypes file add_custom_target(${PLUGIN}-qmltypes ALL COMMAND UNITY_SCOPES_LIST_DELAY=10000 ${qmlplugindump_exe} -notrelocatable ${PLUGIN} ${VERSION} ${CMAKE_CURRENT_BINARY_DIR}/../ > ${CMAKE_CURRENT_BINARY_DIR}/plugin.qmltypes ) add_dependencies(${PLUGIN}-qmltypes ${PLUGIN}-qmlfiles ${qmlplugin_TARGETS}) # install the qmltypes file. install(FILES ${CMAKE_CURRENT_BINARY_DIR}/plugin.qmltypes DESTINATION ${SHELL_PLUGINDIR}/${PLUGIN_SUBPATH} ) endif() # install the additional targets install(TARGETS ${qmlplugin_TARGETS} DESTINATION ${SHELL_PLUGINDIR}/${PLUGIN_SUBPATH} ) endmacro(export_qmlplugin) unity-scopes-shell-0.4.0+14.04.20140408/tests/0000755000015301777760000000000012320777302021027 5ustar pbusernogroup00000000000000unity-scopes-shell-0.4.0+14.04.20140408/tests/data/0000755000015301777760000000000012320777302021740 5ustar pbusernogroup00000000000000unity-scopes-shell-0.4.0+14.04.20140408/tests/data/Zmq.ini.in0000644000015301777760000000014712320776744023630 0ustar pbusernogroup00000000000000[Zmq] EndpointDir.Public = /tmp/scopes-test-endpoints EndpointDir.Private = /tmp/scopes-test-endpoints unity-scopes-shell-0.4.0+14.04.20140408/tests/data/mock-scope/0000755000015301777760000000000012320777302024000 5ustar pbusernogroup00000000000000unity-scopes-shell-0.4.0+14.04.20140408/tests/data/mock-scope/mock-scope.cpp0000644000015301777760000003410412320776744026557 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: * Michal Hruby */ #include #include #define EXPORT __attribute__ ((visibility ("default"))) using namespace std; using namespace unity::scopes; // Example scope A: replies synchronously to a query. (Replies are returned before returning from the run() method.) class MyQuery : public SearchQueryBase { public: MyQuery(string const& query) : query_(query) { } ~MyQuery() noexcept { } virtual void cancelled() override { } virtual void run(SearchReplyProxy const& reply) override { if (query_ == "metadata") { CategoryRenderer meta_rndr(R"({"schema-version": 1, "components": {"title": "title", "art": "art", "subtitle": "subtitle", "emblem": "icon", "mascot": "mascot"}})"); auto cat = reply->register_category("cat1", "Category 1", "", meta_rndr); CategorisedResult res(cat); res.set_uri("test:uri"); res.set_title("result for: \"" + query_ + "\""); res.set_art("art"); res.set_dnd_uri("test:dnd_uri"); res["subtitle"] = "subtitle"; res["icon"] = "emblem"; reply->push(res); } else if (query_ == "rating") { CategoryRenderer rating_rndr(R"({"schema-version": 1, "components": {"title": "title", "attributes": "attributes"}})"); auto cat = reply->register_category("cat1", "Category 1", "", rating_rndr); CategorisedResult res(cat); res.set_uri("test:uri"); res.set_title("result for: \"" + query_ + "\""); res.set_art("art"); res.set_dnd_uri("test:dnd_uri"); VariantBuilder attribute_builder; attribute_builder.add_tuple({{"value", Variant("21 reviews")}}); res["attributes"] = attribute_builder.end(); reply->push(res); } else if (query_ == "attributes") { CategoryRenderer rating_rndr(R"({"schema-version": 1, "components": {"title": "title", "attributes": "attributes"}})"); auto cat = reply->register_category("cat1", "Category 1", "", rating_rndr); CategorisedResult res(cat); res.set_uri("test:uri"); res.set_title("result for: \"" + query_ + "\""); res.set_art("art"); res.set_dnd_uri("test:dnd_uri"); VariantBuilder attribute_builder; attribute_builder.add_tuple({{"value", Variant("21 reviews")}}); attribute_builder.add_tuple({{"value", Variant("4 comments")}}); attribute_builder.add_tuple({{"value", Variant("28 stars")}}); attribute_builder.add_tuple({{"value", Variant("foobar")}}); res["attributes"] = attribute_builder.end(); reply->push(res); } else if (query_ == "background") { CategoryRenderer bkgr_rndr(R"({"schema-version": 1, "template": {"card-background": "color:///black"}, "components": {"title": "title", "background": "background"}})"); auto cat = reply->register_category("cat1", "Category 1", "", bkgr_rndr); CategorisedResult res(cat); res.set_uri("test:uri"); res.set_title("result for: \"" + query_ + "\""); res.set_dnd_uri("test:dnd_uri"); res["background"] = "gradient:///green/#ff00aa33"; reply->push(res); } else if (query_ == "minimal") { CategoryRenderer minimal_rndr(R"({"schema-version": 1, "components": {"title": "title"}})"); auto cat = reply->register_category("cat1", "Category 1", "", minimal_rndr); CategorisedResult res(cat); res.set_uri("test:uri"); res.set_title("result for: \"" + query_ + "\""); res.set_art("art"); res.set_dnd_uri("test:dnd_uri"); reply->push(res); } else if (query_ == "music") { CategoryRenderer music_rndr(R"({"schema-version": 1, "components": {"title": "title", "art": "empty"}})"); auto cat = reply->register_category("cat1", "Category 1", "", music_rndr); CategorisedResult res(cat); res.set_uri("file:///tmp/foo.mp3"); res.set_title("result for: \"" + query_ + "\""); res.set_dnd_uri("file:///tmp/foo.mp3"); res["mimetype"] = "audio/mp3"; res["artist"] = "Foo"; res["album"] = "FooAlbum"; reply->push(res); } else if (query_ == "layout") { CategoryRenderer minimal_rndr(R"({"schema-version": 1, "components": {"title": "title"}})"); auto cat = reply->register_category("cat1", "Category 1", "", minimal_rndr); CategorisedResult res(cat); res.set_uri("test:layout"); res.set_title("result for: \"" + query_ + "\""); reply->push(res); } else if (query_ == "perform-query") { CategoryRenderer minimal_rndr(R"({"schema-version": 1, "components": {"title": "title"}})"); auto cat = reply->register_category("cat1", "Category 1", "", minimal_rndr); CategorisedResult res(cat); res.set_uri("test:perform-query"); res.set_title("result for: \"" + query_ + "\""); res["scope-id"] = "mock-scope"; res.set_intercept_activation(); reply->push(res); } else if (query_ == "perform-query2") { CategoryRenderer minimal_rndr(R"({"schema-version": 1, "components": {"title": "title"}})"); auto cat = reply->register_category("cat1", "Category 1", "", minimal_rndr); CategorisedResult res(cat); res.set_uri("test:perform-query"); res.set_title("result for: \"" + query_ + "\""); res["scope-id"] = "nonexisting-scope"; res.set_intercept_activation(); reply->push(res); } else if (query_ == "two-categories") { auto cat1 = reply->register_category("cat1", "Category 1", ""); auto cat2 = reply->register_category("cat2", "Category 2", ""); CategorisedResult res1(cat1); res1.set_uri("test:uri"); res1.set_title("result for: \"" + query_ + "\""); reply->push(res1); CategorisedResult res2(cat2); res2.set_uri("test:uri"); res2.set_title("result for: \"" + query_ + "\""); reply->push(res2); } else if (query_ == "two-categories-reversed") { auto cat2 = reply->register_category("cat2", "Category 2", ""); auto cat1 = reply->register_category("cat1", "Category 1", ""); CategorisedResult res2(cat2); res2.set_uri("test:uri"); res2.set_title("result for: \"" + query_ + "\""); reply->push(res2); CategorisedResult res1(cat1); res1.set_uri("test:uri"); res1.set_title("result for: \"" + query_ + "\""); reply->push(res1); } else if (query_ == "two-categories-one-result") { auto cat1 = reply->register_category("cat1", "Category 1", ""); auto cat2 = reply->register_category("cat2", "Category 2", ""); CategorisedResult res1(cat1); res1.set_uri("test:uri"); res1.set_title("result for: \"" + query_ + "\""); reply->push(res1); } else { auto cat = reply->register_category("cat1", "Category 1", ""); CategorisedResult res(cat); res.set_uri("test:uri"); res.set_title("result for: \"" + query_ + "\""); res.set_art("art"); res.set_dnd_uri("test:dnd_uri"); res.set_intercept_activation(); reply->push(res); } } private: string query_; }; class MyPreview : public PreviewQueryBase { public: MyPreview(Result const& result, Variant const& scope_data = Variant()) : result_(result), scope_data_(scope_data) { } ~MyPreview() noexcept { } virtual void cancelled() override { } virtual void run(PreviewReplyProxy const& reply) override { if (result_.uri().find("layout") != std::string::npos) { PreviewWidget w1("img", "image"); w1.add_attribute_value("source", Variant("foo.png")); PreviewWidget w2("hdr", "header"); w2.add_attribute_value("title", Variant("Preview title")); PreviewWidget w3("desc", "text"); w3.add_attribute_value("text", Variant("Lorum ipsum...")); PreviewWidget w4("actions", "actions"); VariantBuilder builder; builder.add_tuple({ {"id", Variant("open")}, {"label", Variant("Open")}, {"uri", Variant("application:///tmp/non-existent.desktop")} }); builder.add_tuple({ {"id", Variant("download")}, {"label", Variant("Download")} }); builder.add_tuple({ {"id", Variant("hide")}, {"label", Variant("Hide")} }); w4.add_attribute_value("actions", builder.end()); ColumnLayout l1(1); l1.add_column({"img", "hdr", "desc", "actions", "extra"}); ColumnLayout l2(2); l2.add_column({"img"}); l2.add_column({"hdr", "desc", "actions"}); reply->register_layout({l1, l2}); PreviewWidgetList widgets({w1, w2, w3, w4}); if (!scope_data_.is_null()) { PreviewWidget extra("extra", "text"); extra.add_attribute_value("text", Variant("got scope data")); widgets.push_back(extra); } reply->push(widgets); return; } PreviewWidgetList widgets; PreviewWidget w1(R"({"id": "hdr", "type": "header", "components": {"title": "title", "subtitle": "uri", "attribute-1": "extra-data"}})"); PreviewWidget w2(R"({"id": "img", "type": "image", "components": {"source": "art"}, "zoomable": false})"); widgets.push_back(w1); widgets.push_back(w2); reply->push(widgets); reply->push("extra-data", Variant("foo")); } private: Result result_; Variant scope_data_; }; class MyActivation : public ActivationQueryBase { public: MyActivation(Result const& result) : result_(result), status_(ActivationResponse::HideDash) { } MyActivation(Result const& result, ActivationResponse::Status status) : result_(result), status_(status) { } ~MyActivation() noexcept { } void setExtraData(Variant const& extra) { extra_data_ = extra; } virtual void cancelled() override { } virtual ActivationResponse activate() override { if (status_ == ActivationResponse::Status::PerformQuery) { auto resp = ActivationResponse(CannedQuery(result_["scope-id"].get_string())); return resp; } else { auto resp = ActivationResponse(status_); resp.set_scope_data(extra_data_); return resp; } } private: Variant extra_data_; Result result_; ActivationResponse::Status status_; }; class MyScope : public ScopeBase { public: virtual int start(string const&, RegistryProxy const&) override { return VERSION; } virtual void stop() override {} virtual SearchQueryBase::UPtr search(CannedQuery const& q, SearchMetadata const&) override { SearchQueryBase::UPtr query(new MyQuery(q.query_string())); cout << "scope-A: created query: \"" << q.query_string() << "\"" << endl; return query; } virtual PreviewQueryBase::UPtr preview(Result const& result, ActionMetadata const& metadata) override { PreviewQueryBase::UPtr query(new MyPreview(result, metadata.scope_data())); cout << "scope-A: created preview query: \"" << result.uri() << "\"" << endl; return query; } virtual ActivationQueryBase::UPtr perform_action(Result const& result, ActionMetadata const& meta, std::string const& widget_id, std::string const& action_id) { if (widget_id == "actions" && action_id == "hide") { return ActivationQueryBase::UPtr(new MyActivation(result)); } else if (widget_id == "actions" && action_id == "download") { MyActivation* response = new MyActivation(result, ActivationResponse::ShowPreview); response->setExtraData(meta.scope_data()); return ActivationQueryBase::UPtr(response); } return ActivationQueryBase::UPtr(new MyActivation(result, ActivationResponse::NotHandled)); } virtual ActivationQueryBase::UPtr activate(Result const& result, ActionMetadata const&) override { if (result.uri().find("perform-query") != std::string::npos) { return ActivationQueryBase::UPtr(new MyActivation(result, ActivationResponse::PerformQuery)); } return ActivationQueryBase::UPtr(new MyActivation(result)); } }; extern "C" { EXPORT unity::scopes::ScopeBase* // cppcheck-suppress unusedFunction UNITY_SCOPE_CREATE_FUNCTION() { return new MyScope; } EXPORT void // cppcheck-suppress unusedFunction UNITY_SCOPE_DESTROY_FUNCTION(unity::scopes::ScopeBase* scope_base) { delete scope_base; } } unity-scopes-shell-0.4.0+14.04.20140408/tests/data/mock-scope/mock-scope.ini.in0000644000015301777760000000026512320776744027162 0ustar pbusernogroup00000000000000[ScopeConfig] DisplayName = mock.DisplayName Description = mock.Description Art = /mock.Art Icon = /mock.Icon SearchHint = mock.SearchHint HotKey = mock.HotKey Author = mock.Author unity-scopes-shell-0.4.0+14.04.20140408/tests/data/mock-scope/CMakeLists.txt0000644000015301777760000000050512320776744026551 0ustar pbusernogroup00000000000000include(FindPkgConfig) pkg_check_modules(SCOPESLIB REQUIRED libunity-scopes>=0.4.0) set(SCOPES_BIN_DIR ${SCOPESLIB_LIBDIR}) include_directories(${SCOPESLIB_INCLUDE_DIRS}) add_library(mock-scope MODULE mock-scope.cpp) target_link_libraries(mock-scope ${SCOPESLIB_LDFLAGS}) configure_file(mock-scope.ini.in mock-scope.ini) unity-scopes-shell-0.4.0+14.04.20140408/tests/data/Registry.ini.in0000644000015301777760000000044012320776744024665 0ustar pbusernogroup00000000000000[Registry] Middleware = Zmq Zmq.Endpoint = ipc:///tmp/scopes-test-endpoints/Registry Zmq.EndpointDir = /tmp/scopes-test-endpoints Zmq.ConfigFile = @CMAKE_CURRENT_BINARY_DIR@/Zmq.ini Scope.InstallDir = @CMAKE_CURRENT_BINARY_DIR@ Scoperunner.Path = @SCOPES_BIN_DIR@/scoperunner/scoperunner unity-scopes-shell-0.4.0+14.04.20140408/tests/data/CMakeLists.txt0000644000015301777760000000041612320776744024512 0ustar pbusernogroup00000000000000add_subdirectory(mock-scope) configure_file(Runtime.ini.in Runtime.ini @ONLY) configure_file(Registry.ini.in Registry.ini @ONLY) configure_file(Zmq.ini.in Zmq.ini @ONLY) execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/endpoints) unity-scopes-shell-0.4.0+14.04.20140408/tests/data/Runtime.ini.in0000644000015301777760000000032312320776744024500 0ustar pbusernogroup00000000000000[Runtime] Registry.Identity = Registry Registry.ConfigFile = @CMAKE_CURRENT_BINARY_DIR@/Registry.ini Default.Middleware = Zmq Zmq.ConfigFile = @CMAKE_CURRENT_BINARY_DIR@/Zmq.ini Factory.ConfigFile = Factory.ini unity-scopes-shell-0.4.0+14.04.20140408/tests/resultstest-ng.cpp0000644000015301777760000007657412320776744024572 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013-2014 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: * Michal Hruby */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define SCOPES_TMP_ENDPOINT_DIR "/tmp/scopes-test-endpoints" using namespace scopes_ng; class CountObject : public QObject { Q_OBJECT Q_PROPERTY(int count READ count NOTIFY countChanged) public: explicit CountObject(QObject* parent = nullptr) : QObject(parent), m_count(0) { connect(&m_timer, &QTimer::timeout, this, &CountObject::asyncTimeout); } Q_SIGNALS: void countChanged(); private Q_SLOTS: void asyncTimeout() { setCount(m_waitingCount); } public: int count() const { return m_count; } void setCount(int newCount) { if (newCount != m_count) { m_count = newCount; Q_EMIT countChanged(); } } void setCountAsync(int newCount) { m_waitingCount = newCount; m_timer.setSingleShot(true); m_timer.start(1); } private: int m_count; int m_waitingCount; QTimer m_timer; }; class ResultsTestNg : public QObject { Q_OBJECT private: QScopedPointer m_scopes; Scope* m_scope; QScopedPointer m_registry; void checkedFirstResult(Scope* scope, unity::scopes::Result::SPtr& result, bool& success) { // ensure categories have > 0 rows auto categories = scope->categories(); QVERIFY(categories->rowCount() > 0); QVariant results_var = categories->data(categories->index(0), Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); // ensure results have some data auto results = results_var.value(); QVERIFY(results->rowCount() > 0); auto result_var = results->data(results->index(0), ResultsModel::RoleResult); QCOMPARE(result_var.isNull(), false); result = result_var.value>(); success = true; } bool getFirstResult(Scope* scope, unity::scopes::Result::SPtr& result) { bool success = false; checkedFirstResult(scope, result, success); return success; } void performSearch(Scope* scope, QString const& searchString) { QCOMPARE(scope->searchInProgress(), false); // perform a search scope->setSearchQuery(searchString); QCOMPARE(scope->searchInProgress(), true); // wait for the search to finish QSignalSpy spy(scope, SIGNAL(searchInProgressChanged())); QVERIFY(spy.wait()); QCOMPARE(scope->searchInProgress(), false); } private Q_SLOTS: void initTestCase() { QDir endpointdir(QFileInfo(TEST_RUNTIME_CONFIG).dir()); endpointdir.cd(QString("endpoints")); QFile::remove(SCOPES_TMP_ENDPOINT_DIR); // symlinking to workaround "File name too long" issue QVERIFY2(QFile::link(endpointdir.absolutePath(), SCOPES_TMP_ENDPOINT_DIR), "Unable to create symlink " SCOPES_TMP_ENDPOINT_DIR); // startup our private scope registry QString registryBin(TEST_SCOPEREGISTRY_BIN); QStringList arguments; arguments << TEST_RUNTIME_CONFIG; m_registry.reset(new QProcess(nullptr)); m_registry->start(registryBin, arguments); } void cleanupTestCase() { if (m_registry) { m_registry->terminate(); if (!m_registry->waitForFinished()) { m_registry->kill(); } } QFile::remove(SCOPES_TMP_ENDPOINT_DIR); } void init() { m_scopes.reset(new Scopes(nullptr)); // no scopes on startup QCOMPARE(m_scopes->rowCount(), 0); QCOMPARE(m_scopes->loaded(), false); QSignalSpy spy(m_scopes.data(), SIGNAL(loadedChanged(bool))); // wait till the registry spawns QVERIFY(spy.wait()); QCOMPARE(m_scopes->loaded(), true); // should have one scope now QCOMPARE(m_scopes->rowCount(), 1); QVariant scope_var = m_scopes->data(m_scopes->index(0), Scopes::Roles::RoleScope); QVERIFY(scope_var.canConvert()); // get scope proxy m_scope = scope_var.value(); } void cleanup() { m_scopes.reset(); m_scope = nullptr; } void testScopeCommunication() { performSearch(m_scope, QString("")); // ensure categories have > 0 rows auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); QVariant results_var = categories->data(categories->index(0), Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); QCOMPARE(categories->data(categories->index(0), Categories::Roles::RoleName), QVariant(QString("Category 1"))); QCOMPARE(categories->data(categories->index(0), Categories::Roles::RoleIcon), QVariant(QString(""))); // ensure results have some data auto results = results_var.value(); QVERIFY(results->rowCount() > 0); // test also the ResultsModel::get() method QVariantMap result_data(results->get(0).toMap()); QVERIFY(result_data.size() > 0); QVERIFY(result_data.contains("uri")); QVERIFY(result_data.contains("categoryId")); QVERIFY(result_data.contains("result")); QVERIFY(result_data.contains("title")); } void testScopesGet() { QVariant scope_var = m_scopes->get(0); QVERIFY(scope_var.canConvert()); // try incorrect index as well scope_var = m_scopes->get(65536); QVERIFY(scope_var.isNull()); scope_var = m_scopes->get(-1); QVERIFY(scope_var.isNull()); // try to get by scope id scope_var = m_scopes->get(QString("mock-scope")); QVERIFY(!scope_var.isNull()); QVERIFY(scope_var.canConvert()); scope_var = m_scopes->get(QString("non-existing")); QVERIFY(scope_var.isNull()); } void testScopeProperties() { QCOMPARE(m_scope->id(), QString("mock-scope")); QCOMPARE(m_scope->name(), QString("mock.DisplayName")); QCOMPARE(m_scope->iconHint(), QString("/mock.Icon")); QCOMPARE(m_scope->description(), QString("mock.Description")); QCOMPARE(m_scope->searchHint(), QString("mock.SearchHint")); QCOMPARE(m_scope->shortcut(), QString("mock.HotKey")); QCOMPARE(m_scope->visible(), true); QCOMPARE(m_scope->searchQuery(), QString()); QCOMPARE(m_scope->isActive(), false); m_scope->setActive(true); QCOMPARE(m_scope->isActive(), true); } void testTwoSearches() { performSearch(m_scope, QString("")); // ensure categories have > 0 rows auto categories = m_scope->categories(); auto categories_count = categories->rowCount(); QVERIFY(categories_count > 0); performSearch(m_scope, QString("foo")); // shouldn't create more nor fewer categories QVERIFY(categories->rowCount() == categories_count); } void testBasicResultData() { performSearch(m_scope, QString("")); // get ResultsModel instance auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); QVariant results_var = categories->data(categories->index(0), Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); auto results = results_var.value(); QVERIFY(results->rowCount() > 0); auto idx = results->index(0); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleUri).toString(), QString("test:uri")); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleDndUri).toString(), QString("test:dnd_uri")); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"\"")); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleArt).toString(), QString("art")); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleCategoryId), categories->data(categories->index(0), Categories::Roles::RoleCategoryId)); } void testResultMetadata() { performSearch(m_scope, QString("metadata")); // get ResultsModel instance auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); QVariant results_var = categories->data(categories->index(0), Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); auto results = results_var.value(); QVERIFY(results->rowCount() > 0); auto idx = results->index(0); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"metadata\"")); // mapped to the same field name QCOMPARE(results->data(idx, ResultsModel::Roles::RoleSubtitle).toString(), QString("subtitle")); // mapped to a different field name QCOMPARE(results->data(idx, ResultsModel::Roles::RoleEmblem).toString(), QString("emblem")); // mapped but not present in the result QCOMPARE(results->data(idx, ResultsModel::Roles::RoleMascot).toString(), QString()); // unmapped QVERIFY(results->data(idx, ResultsModel::Roles::RoleAttributes).isNull()); QVERIFY(results->data(idx, ResultsModel::Roles::RoleSummary).isNull()); } void testResultsInvalidation() { if (!QDBusConnection::sessionBus().isConnected()) { QSKIP("DBus unavailable, skipping test"); } performSearch(m_scope, QString("")); m_scope->setActive(true); QStringList args; args << "/com/canonical/unity/scopes"; args << "com.canonical.unity.scopes.InvalidateResults"; args << "string:mock-scope"; QProcess::execute("dbus-send", args); QSignalSpy spy(m_scope, SIGNAL(searchInProgressChanged())); QCOMPARE(m_scope->searchInProgress(), false); QVERIFY(spy.wait()); QCOMPARE(m_scope->searchInProgress(), true); QVERIFY(spy.wait()); QCOMPARE(m_scope->searchInProgress(), false); } void testAlbumArtResult() { performSearch(m_scope, QString("music")); // get ResultsModel instance auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); QVariant results_var = categories->data(categories->index(0), Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); auto results = results_var.value(); QVERIFY(results->rowCount() > 0); auto idx = results->index(0); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleUri).toString(), QString("file:///tmp/foo.mp3")); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"music\"")); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleArt).toString(), QString("image://albumart/artist=Foo&album=FooAlbum")); } void testCategoryOverride() { performSearch(m_scope, QString("metadata")); // get ResultsModel instance auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); QVariant results_var = categories->data(categories->index(0), Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); auto results = results_var.value(); QVERIFY(results->rowCount() > 0); auto idx = results->index(0); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"metadata\"")); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleEmblem).toString(), QString("emblem")); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleArt).toString(), QString("art")); // drop all components but title categories->overrideCategoryJson("cat1", R"({"schema-version": 1, "components": {"title": "title"}})"); // check that the model no longer has the components QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"metadata\"")); QVERIFY(results->data(idx, ResultsModel::Roles::RoleEmblem).isNull()); QVERIFY(results->data(idx, ResultsModel::Roles::RoleArt).isNull()); categories->overrideCategoryJson("cat1", R"({"schema-version": 1, "components": {"title": "title", "art": {"field": "art"}}})"); // check that the model has the art QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"metadata\"")); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleArt).toString(), QString("art")); } void testSpecialCategory() { QCOMPARE(m_scope->searchInProgress(), false); auto categories = m_scope->categories(); QString rawTemplate(R"({"schema-version": 1, "template": {"category-layout": "special"}})"); CountObject* countObject = new CountObject(m_scope); categories->addSpecialCategory("special", "Special", "", rawTemplate, countObject); // should have 1 category now QCOMPARE(categories->rowCount(), 1); QCOMPARE(categories->data(categories->index(0), Categories::Roles::RoleCount).toInt(), 0); countObject->setCount(1); QCOMPARE(categories->data(categories->index(0), Categories::Roles::RoleCount).toInt(), 1); qRegisterMetaType>(); QSignalSpy spy(categories, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&, const QVector&))); countObject->setCountAsync(13); QCOMPARE(categories->data(categories->index(0), Categories::Roles::RoleCount).toInt(), 1); QTRY_COMPARE(categories->data(categories->index(0), Categories::Roles::RoleCount).toInt(), 13); // expecting a few dataChanged signals, count should have changed bool countChanged = false; while (!spy.empty() && !countChanged) { QList arguments = spy.takeFirst(); auto roles = arguments.at(2).value>(); countChanged |= roles.contains(Categories::Roles::RoleCount); } QCOMPARE(countChanged, true); } void testCategoryWithRating() { performSearch(m_scope, QString("rating")); // get ResultsModel instance auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); QVariant results_var = categories->data(categories->index(0), Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); auto results = results_var.value(); QVERIFY(results->rowCount() > 0); auto idx = results->index(0); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"rating\"")); auto attributes = results->data(idx, ResultsModel::Roles::RoleAttributes).toList(); QVERIFY(attributes.size() >= 1); QCOMPARE(attributes[0].toMap().value("value").toString(), QString("21 reviews")); } void testCategoryAttributeLimit() { performSearch(m_scope, QString("attributes")); // get ResultsModel instance auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); QVariant results_var = categories->data(categories->index(0), Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); auto results = results_var.value(); QVERIFY(results->rowCount() > 0); auto idx = results->index(0); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"attributes\"")); auto attributes = results->data(idx, ResultsModel::Roles::RoleAttributes).toList(); QVERIFY(attributes.size() == 3); QCOMPARE(attributes[0].toMap().value("value").toString(), QString("21 reviews")); QCOMPARE(attributes[1].toMap().value("value").toString(), QString("4 comments")); QCOMPARE(attributes[2].toMap().value("value").toString(), QString("28 stars")); } void testCategoryWithBackground() { performSearch(m_scope, QString("background")); // get ResultsModel instance auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); QVariant renderer_var = categories->data(categories->index(0), Categories::Roles::RoleRenderer); QVariantMap renderer(renderer_var.toMap()); QVERIFY(renderer.contains("card-background")); QVERIFY(renderer["card-background"].canConvert()); QVariantMap cardBackground(renderer["card-background"].toMap()); QCOMPARE(cardBackground["type"], QVariant(QString("color"))); QCOMPARE(cardBackground["elements"], QVariant(QVariantList({QString("black")}))); QVariant results_var = categories->data(categories->index(0), Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); auto results = results_var.value(); QVERIFY(results->rowCount() > 0); auto idx = results->index(0); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"background\"")); QVariant background(results->data(idx, ResultsModel::Roles::RoleBackground)); QVERIFY(background.canConvert()); QVariantMap map(background.toMap()); QCOMPARE(map["type"], QVariant(QString("gradient"))); QCOMPARE(map["elements"], QVariant(QVariantList({QString("green"), QString("#ff00aa33")}))); } void testCategoryDefaults() { // this search return minimal category definition, defaults should kick in performSearch(m_scope, QString("minimal")); auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); // get renderer_template and components auto cidx = categories->index(0); QVariant components_var = categories->data(cidx, Categories::Roles::RoleComponents); QVERIFY(components_var.canConvert()); QJsonObject components = QJsonValue::fromVariant(components_var).toObject(); QVariant renderer_var = categories->data(cidx, Categories::Roles::RoleRenderer); QVERIFY(renderer_var.canConvert()); QJsonObject renderer = QJsonValue::fromVariant(renderer_var).toObject(); int num_active_components = 0; for (auto it = components.begin(); it != components.end(); ++it) { if (it.value().isObject() && it.value().toObject().value("field").isString()) { num_active_components++; } } QCOMPARE(num_active_components, 1); QVERIFY(renderer.contains("card-size")); QCOMPARE(renderer.value("card-size"), QJsonValue(QString("small"))); QVERIFY(renderer.contains("card-layout")); QCOMPARE(renderer.value("card-layout"), QJsonValue(QString("vertical"))); QVERIFY(renderer.contains("category-layout")); QCOMPARE(renderer.value("category-layout"), QJsonValue(QString("grid"))); // get ResultsModel instance QVariant results_var = categories->data(cidx, Categories::Roles::RoleResults); QVERIFY(results_var.canConvert()); auto results = results_var.value(); QVERIFY(results->rowCount() > 0); auto idx = results->index(0); QCOMPARE(results->data(idx, ResultsModel::Roles::RoleTitle).toString(), QString("result for: \"minimal\"")); // components json doesn't specify "art" QCOMPARE(results->data(idx, ResultsModel::Roles::RoleArt).toString(), QString()); } void testCategoryDefinitionChange() { performSearch(m_scope, QString("")); auto categories = m_scope->categories(); QVERIFY(categories->rowCount() > 0); qRegisterMetaType>(); QSignalSpy spy(categories, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&, const QVector&))); // should at least change components performSearch(m_scope, QString("metadata")); // expecting a few dataChanged signals, count and components changes // ensure we get the components one bool componentsChanged = false; while (!spy.empty() && !componentsChanged) { QList arguments = spy.takeFirst(); auto roles = arguments.at(2).value>(); componentsChanged |= roles.contains(Categories::Roles::RoleComponents); } QCOMPARE(componentsChanged, true); } void testCategoryOrderChange() { performSearch(m_scope, QString("two-categories")); auto categories = m_scope->categories(); QCOMPARE(categories->rowCount(), 2); QStringList order1; order1 << categories->data(categories->index(0), Categories::Roles::RoleCategoryId).toString(); order1 << categories->data(categories->index(1), Categories::Roles::RoleCategoryId).toString(); performSearch(m_scope, QString("two-categories-reversed")); QCOMPARE(categories->rowCount(), 2); QStringList order2; order2 << categories->data(categories->index(0), Categories::Roles::RoleCategoryId).toString(); order2 << categories->data(categories->index(1), Categories::Roles::RoleCategoryId).toString(); QCOMPARE(order1[0], QString("cat1")); QCOMPARE(order1[1], QString("cat2")); QCOMPARE(order2[0], QString("cat2")); QCOMPARE(order2[1], QString("cat1")); QCOMPARE(order1[0], order2[1]); QCOMPARE(order1[1], order2[0]); } void testCategoryOrderChange2() { performSearch(m_scope, QString("two-categories-one-result")); auto categories = m_scope->categories(); QCOMPARE(categories->rowCount(), 1); QStringList order1; order1 << categories->data(categories->index(0), Categories::Roles::RoleCategoryId).toString(); performSearch(m_scope, QString("two-categories-reversed")); QCOMPARE(categories->rowCount(), 2); QStringList order2; order2 << categories->data(categories->index(0), Categories::Roles::RoleCategoryId).toString(); order2 << categories->data(categories->index(1), Categories::Roles::RoleCategoryId).toString(); QCOMPARE(order1[0], QString("cat1")); QCOMPARE(order2[0], QString("cat2")); QCOMPARE(order2[1], QString("cat1")); QCOMPARE(order1[0], order2[1]); } void testScopePreview() { performSearch(m_scope, QString("")); unity::scopes::Result::SPtr result; QVERIFY(getFirstResult(m_scope, result)); QScopedPointer preview_stack(m_scope->preview(QVariant::fromValue(result))); QCOMPARE(preview_stack->rowCount(), 1); QCOMPARE(preview_stack->widgetColumnCount(), 1); auto preview_var = preview_stack->data(preview_stack->index(0), PreviewStack::RolePreviewModel); auto preview_model = preview_stack->get(0); QCOMPARE(preview_model, preview_var.value()); QCOMPARE(preview_model->widgetColumnCount(), 1); QTRY_COMPARE(preview_model->loaded(), true); auto preview_widgets = preview_model->data(preview_model->index(0), PreviewModel::RoleColumnModel).value(); QVERIFY(!preview_widgets->roleNames().isEmpty()); QCOMPARE(preview_widgets->rowCount(), 2); QVariantMap props; QModelIndex idx; idx = preview_widgets->index(0); QCOMPARE(preview_widgets->data(idx, PreviewWidgetModel::RoleWidgetId).toString(), QString("hdr")); QCOMPARE(preview_widgets->data(idx, PreviewWidgetModel::RoleType).toString(), QString("header")); props = preview_widgets->data(idx, PreviewWidgetModel::RoleProperties).toMap(); QCOMPARE(props[QString("title")].toString(), QString::fromStdString(result->title())); QCOMPARE(props[QString("subtitle")].toString(), QString::fromStdString(result->uri())); QCOMPARE(props[QString("attribute-1")].toString(), QString("foo")); idx = preview_widgets->index(1); QCOMPARE(preview_widgets->data(idx, PreviewWidgetModel::RoleWidgetId).toString(), QString("img")); QCOMPARE(preview_widgets->data(idx, PreviewWidgetModel::RoleType).toString(), QString("image")); props = preview_widgets->data(idx, PreviewWidgetModel::RoleProperties).toMap(); QVERIFY(props.contains("source")); QCOMPARE(props[QString("source")].toString(), QString::fromStdString(result->art())); QVERIFY(props.contains("zoomable")); QCOMPARE(props[QString("zoomable")].toBool(), false); } void testPreviewLayouts() { performSearch(m_scope, QString("layout")); unity::scopes::Result::SPtr result; QVERIFY(getFirstResult(m_scope, result)); QScopedPointer preview_stack(m_scope->preview(QVariant::fromValue(result))); QCOMPARE(preview_stack->rowCount(), 1); QCOMPARE(preview_stack->widgetColumnCount(), 1); auto preview = preview_stack->get(0); QTRY_COMPARE(preview->loaded(), true); QCOMPARE(preview->rowCount(), 1); auto col_model1 = preview->data(preview->index(0), PreviewModel::RoleColumnModel).value(); QCOMPARE(col_model1->rowCount(), 4); // switch the layout preview_stack->setWidgetColumnCount(2); QCOMPARE(preview->rowCount(), 2); QCOMPARE(col_model1->rowCount(), 1); auto col_model2 = preview->data(preview->index(1), PreviewModel::RoleColumnModel).value(); QCOMPARE(col_model2->rowCount(), 3); // switch back preview_stack->setWidgetColumnCount(1); QCOMPARE(preview->rowCount(), 1); QCOMPARE(col_model1->rowCount(), 4); } void testScopeActivation() { performSearch(m_scope, QString("")); unity::scopes::Result::SPtr result; QVERIFY(getFirstResult(m_scope, result)); QSignalSpy spy(m_scope, SIGNAL(hideDash())); m_scope->activate(QVariant::fromValue(result)); QVERIFY(spy.wait()); } void testPreviewAction() { performSearch(m_scope, QString("layout")); unity::scopes::Result::SPtr result; QVERIFY(getFirstResult(m_scope, result)); QScopedPointer preview_stack(m_scope->preview(QVariant::fromValue(result))); QCOMPARE(preview_stack->rowCount(), 1); QCOMPARE(preview_stack->widgetColumnCount(), 1); auto preview = preview_stack->get(0); QTRY_COMPARE(preview->loaded(), true); QCOMPARE(preview->rowCount(), 1); QSignalSpy spy(m_scope, SIGNAL(hideDash())); Q_EMIT preview->triggered(QString("actions"), QString("hide"), QVariantMap()); QCOMPARE(preview->processingAction(), true); QVERIFY(spy.wait()); QCOMPARE(preview->processingAction(), false); } void testPreviewUriAction() { performSearch(m_scope, QString("layout")); unity::scopes::Result::SPtr result; QVERIFY(getFirstResult(m_scope, result)); QScopedPointer preview_stack(m_scope->preview(QVariant::fromValue(result))); QCOMPARE(preview_stack->rowCount(), 1); QCOMPARE(preview_stack->widgetColumnCount(), 1); auto preview = preview_stack->get(0); QTRY_COMPARE(preview->loaded(), true); QCOMPARE(preview->rowCount(), 1); QSignalSpy spy(m_scope, SIGNAL(activateApplication(QString))); QVariantMap hints; hints["uri"] = QString("application:///tmp/non-existent.desktop"); Q_EMIT preview->triggered(QString("actions"), QString("open"), hints); // this is likely to be invoked synchronously if (spy.count() == 0) { QVERIFY(spy.wait()); } QList arguments = spy.takeFirst(); auto desktopFile = arguments.at(0).value(); QCOMPARE(desktopFile, QString("non-existent")); } void testPreviewReplacingPreview() { performSearch(m_scope, QString("layout")); unity::scopes::Result::SPtr result; QVERIFY(getFirstResult(m_scope, result)); QScopedPointer preview_stack(m_scope->preview(QVariant::fromValue(result))); QCOMPARE(preview_stack->rowCount(), 1); QCOMPARE(preview_stack->widgetColumnCount(), 1); auto preview = preview_stack->get(0); QTRY_COMPARE(preview->loaded(), true); QCOMPARE(preview->rowCount(), 1); auto preview_widgets = preview->data(preview->index(0), PreviewModel::RoleColumnModel).value(); QCOMPARE(preview_widgets->rowCount(), 4); QSignalSpy spy(preview, SIGNAL(loadedChanged())); QVariantMap hints; hints["session-id"] = QString("qoo"); Q_EMIT preview->triggered(QString("actions"), QString("download"), hints); QCOMPARE(preview->processingAction(), true); // wait for loaded to become false QVERIFY(spy.wait()); QCOMPARE(preview->loaded(), false); // a bit of gray area, preview was just marked as "about-to-be-replaced", so it kinda is processing the action? QCOMPARE(preview->processingAction(), true); QTRY_COMPARE(preview->loaded(), true); QCOMPARE(preview->processingAction(), false); // refresh widget model preview_widgets = preview->data(preview->index(0), PreviewModel::RoleColumnModel).value(); QCOMPARE(preview_widgets->rowCount(), 5); } void testScopeActivationWithQuery() { performSearch(m_scope, QString("perform-query")); unity::scopes::Result::SPtr result; QVERIFY(getFirstResult(m_scope, result)); QSignalSpy spy(m_scope, SIGNAL(gotoScope(QString))); m_scope->activate(QVariant::fromValue(result)); QVERIFY(spy.wait()); } void testScopeActivationWithQuery2() { performSearch(m_scope, QString("perform-query2")); unity::scopes::Result::SPtr result; QVERIFY(getFirstResult(m_scope, result)); QSignalSpy spy(m_scopes.data(), SIGNAL(metadataRefreshed())); QSignalSpy spy2(m_scope, SIGNAL(gotoScope(QString))); QSignalSpy spy3(m_scope, SIGNAL(openScope(scopes_ng::Scope*))); // this tries to activate non-existing scope m_scope->activate(QVariant::fromValue(result)); QVERIFY(spy.wait()); QCOMPARE(spy2.count(), 0); QCOMPARE(spy3.count(), 0); } }; QTEST_MAIN(ResultsTestNg) #include unity-scopes-shell-0.4.0+14.04.20140408/tests/CMakeLists.txt0000644000015301777760000000325712320776755023611 0ustar pbusernogroup00000000000000include(FindPkgConfig) pkg_check_modules(SCOPESLIB REQUIRED libunity-scopes>=0.4.0) pkg_check_modules(GSETTINGSQT REQUIRED gsettings-qt) set(SCOPES_BIN_DIR ${SCOPESLIB_LIBDIR}) set(SCOPES_TEST_RUNTIME ${CMAKE_CURRENT_BINARY_DIR}/data/Runtime.ini) add_subdirectory(data) include_directories( ${Unity-qml_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/../src/Unity ${CMAKE_CURRENT_BINARY_DIR} ${SCOPESLIB_INCLUDE_DIRS} ${GSETTINGSQT_INCLUDE_DIRS} ) macro(run_tests) set(_test_list "") foreach(_test ${ARGN}) set(testCommand ${CMAKE_CURRENT_BINARY_DIR}/${_test}Exec -o ${CMAKE_BINARY_DIR}/${_test}.xml,xunitxml -o -,txt) add_test(NAME test${CLASSNAME}${_test} COMMAND ${testCommand}) add_custom_target(${_test} ${testCommand}) add_executable(${_test}Exec ${_test}.cpp) qt5_use_modules(${_test}Exec Test Core Qml DBus) set_tests_properties(test${CLASSNAME}${_test} PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=minimal;LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}/plugins/Unity:${LIBUNITYPROTO_LIBRARY_DIRS};UNITY_SCOPES_RUNTIME_PATH=${SCOPES_TEST_RUNTIME};UNITY_SCOPES_LIST_DELAY=5") set_target_properties(${_test}Exec PROPERTIES COMPILE_FLAGS "-DTEST_SCOPEREGISTRY_BIN='\"${SCOPES_BIN_DIR}/scoperegistry/scoperegistry\"' -DTEST_RUNTIME_CONFIG='\"${SCOPES_TEST_RUNTIME}\"'") target_link_libraries(${_test}Exec Unity-qml ${SCOPESLIB_LDFLAGS} ${GSETTINGSQT_LDFLAGS} ) set(_test_list "${_test_list};${_test}") endforeach() endmacro(run_tests) run_tests( resultstest-ng utilstest-ng ) unity-scopes-shell-0.4.0+14.04.20140408/tests/utilstest-ng.cpp0000644000015301777760000000757412320776744024223 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: * Michal Hruby */ #include #include #include #include #include #include #include using namespace scopes_ng; using namespace unity; class UtilsTestNg : public QObject { Q_OBJECT private Q_SLOTS: void testVariantConversions() { scopes::Variant v1("foo"); QCOMPARE(scopeVariantToQVariant(v1).toString(), QString("foo")); scopes::Variant v2(7); QCOMPARE(scopeVariantToQVariant(v2).toInt(), 7); scopes::Variant v3(true); QCOMPARE(scopeVariantToQVariant(v3).toBool(), true); scopes::Variant v4(3.25); QCOMPARE(scopeVariantToQVariant(v4).toDouble(), 3.25); scopes::Variant v5; QCOMPARE(scopeVariantToQVariant(v5).isNull(), true); scopes::VariantArray arr; arr.push_back(v1); arr.push_back(v3); arr.push_back(v2); QVariantList list = scopeVariantToQVariant(scopes::Variant(arr)).toList(); QCOMPARE(list.size(), 3); QCOMPARE(list[0].toString(), QString("foo")); QCOMPARE(list[1].toBool(), true); QCOMPARE(list[2].toInt(), 7); scopes::VariantMap vm; vm["first"] = v1; vm["2"] = v2; vm["last"] = v3; QVariantMap dict = scopeVariantToQVariant(scopes::Variant(vm)).toMap(); QCOMPARE(dict.size(), 3); QCOMPARE(dict.value("first").toString(), QString("foo")); QCOMPARE(dict.value("2").toInt(), 7); QCOMPARE(dict.value("last").toBool(), true); } void testInvertedConversions() { scopes::Variant v1("foo"); QVariant qv1(scopeVariantToQVariant(v1)); QCOMPARE(qVariantToScopeVariant(qv1), v1); scopes::Variant v2(7); QVariant qv2(scopeVariantToQVariant(v2)); QCOMPARE(qVariantToScopeVariant(qv2), v2); scopes::Variant v3(true); QVariant qv3(scopeVariantToQVariant(v3)); QCOMPARE(qVariantToScopeVariant(qv3), v3); scopes::Variant v4(3.25); QVariant qv4(scopeVariantToQVariant(v4)); QCOMPARE(qVariantToScopeVariant(qv4), v4); scopes::Variant v5; QVariant qv5(scopeVariantToQVariant(v5)); QCOMPARE(qVariantToScopeVariant(qv5), v5); scopes::VariantArray arr; arr.push_back(v1); arr.push_back(v3); arr.push_back(v2); QVariantList list = scopeVariantToQVariant(scopes::Variant(arr)).toList(); QCOMPARE(list.size(), 3); QCOMPARE(qVariantToScopeVariant(list[0]), v1); QCOMPARE(qVariantToScopeVariant(list[1]), v3); QCOMPARE(qVariantToScopeVariant(list[2]), v2); QCOMPARE(qVariantToScopeVariant(list), scopes::Variant(arr)); scopes::VariantMap vm; vm["first"] = v1; vm["2"] = v2; vm["last"] = v3; QVariantMap dict = scopeVariantToQVariant(scopes::Variant(vm)).toMap(); QCOMPARE(dict.size(), 3); QCOMPARE(qVariantToScopeVariant(dict.value("first")), v1); QCOMPARE(qVariantToScopeVariant(dict.value("2")), v2); QCOMPARE(qVariantToScopeVariant(dict.value("last")), v3); QCOMPARE(qVariantToScopeVariant(dict), scopes::Variant(vm)); } }; QTEST_MAIN(UtilsTestNg) #include unity-scopes-shell-0.4.0+14.04.20140408/data/0000755000015301777760000000000012320777302020576 5ustar pbusernogroup00000000000000unity-scopes-shell-0.4.0+14.04.20140408/data/unity-plugin-scopes.pc.in0000644000015301777760000000160612320776744025501 0ustar pbusernogroup00000000000000# # Copyright (C) 2013 Canonical Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authored by: Michal Hruby # prefix=@CMAKE_INSTALL_PREFIX@ includedir=${prefix}/include libdir=${prefix}/@SHELL_PLUGINDIR@/Unity Name: unity-scopes-qml Description: Unity Scopes QML plugin Version: 1.0 Libs: -L${libdir} -lUnity-qml Cflags: -I${includedir} unity-scopes-shell-0.4.0+14.04.20140408/data/CMakeLists.txt0000644000015301777760000000032012320776744023342 0ustar pbusernogroup00000000000000# Set up package config. configure_file(unity-plugin-scopes.pc.in unity-plugin-scopes.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/unity-plugin-scopes.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) unity-scopes-shell-0.4.0+14.04.20140408/CMakeLists.txt0000644000015301777760000000644512320776744022447 0ustar pbusernogroup00000000000000cmake_minimum_required(VERSION 2.8.9) # Default install location. Must be set here, before setting the project. if (NOT DEFINED CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/install CACHE PATH "" FORCE) endif() project(unity-scopes-shell C CXX) if(${PROJECT_BINARY_DIR} STREQUAL ${PROJECT_SOURCE_DIR}) message(FATAL_ERROR "In-tree build attempt detected, aborting. Set your build dir outside your source dir, delete CMakeCache.txt from source root and try again.") endif() set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules) # Instruct CMake to run moc automatically when needed. set(CMAKE_AUTOMOC ON) string(TOLOWER "${CMAKE_BUILD_TYPE}" cmake_build_type_lower) # Build types should always be lowercase but sometimes they are not. include(EnableCoverageReport) ##################################################################### # Enable code coverage calculation with gcov/gcovr/lcov # Usage: # * Switch build type to coverage (use ccmake or cmake-gui) # * Invoke make, make test, make coverage (or ninja if you use that backend) # * Find html report in subdir coveragereport # * Find xml report feasible for jenkins in coverage.xml ##################################################################### if(cmake_build_type_lower MATCHES coverage) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --coverage" ) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --coverage" ) set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} --coverage" ) set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} --coverage" ) ENABLE_COVERAGE_REPORT(TARGETS ${SHELL_APP} FILTER /usr/include ${CMAKE_SOURCE_DIR}/tests/* ${CMAKE_BINARY_DIR}/*) endif() # Make sure we have all the needed symbols set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,defs") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-z,defs") # Static C++ checks add_custom_target(cppcheck COMMAND cppcheck --enable=all -q --error-exitcode=2 ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/tests) include(FindPkgConfig) find_package(Qt5Core) find_package(Qt5Qml) find_package(Qt5Quick) find_package(Qt5Gui) # Standard install paths include(GNUInstallDirs) execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --variable=plugindir_suffix unity-shell-api OUTPUT_VARIABLE SHELL_PLUGINDIR OUTPUT_STRIP_TRAILING_WHITESPACE) if(SHELL_PLUGINDIR STREQUAL "") set(SHELL_PLUGINDIR ${CMAKE_INSTALL_LIBDIR}/unity8/qml) endif() include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fno-permissive -pedantic -Wall -Wextra") if ("${CMAKE_BUILD_TYPE}" STREQUAL "release" OR "${CMAKE_BUILD_TYPE}" STREQUAL "relwithdebinfo") option(Werror "Treat warnings as errors" ON) else() option(Werror "Treat warnings as errors" OFF) endif() if (Werror) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror") endif() # gtk and unity-core (actually sigc++) do not like Qt defining macros named # "signals" and "slots" add_definitions(-DQT_NO_KEYWORDS) # Tests include(CTest) enable_testing() # add subdirectories to build add_subdirectory(src) add_subdirectory(tests) add_subdirectory(data) # # Translation # #add_subdirectory(po) unity-scopes-shell-0.4.0+14.04.20140408/COPYING0000644000015301777760000010451312320776744020735 0ustar pbusernogroup00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . unity-scopes-shell-0.4.0+14.04.20140408/src/0000755000015301777760000000000012320777302020454 5ustar pbusernogroup00000000000000unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/0000755000015301777760000000000012320777302021564 5ustar pbusernogroup00000000000000unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/plugin.h0000644000015301777760000000204412320776744023244 0ustar pbusernogroup00000000000000/* * Copyright (C) 2012 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Author: Michał Sawicz */ #ifndef UNITY_PLUGIN_H #define UNITY_PLUGIN_H #include #include class UnityPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") public: void registerTypes(const char *uri); void initializeEngine(QQmlEngine *engine, const char *uri); }; #endif unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/scopes.h0000644000015301777760000000552512320776744023251 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NG_SCOPES_H #define NG_SCOPES_H // Qt #include #include #include #include #include #include #include #include namespace scopes_ng { class Scope; class Q_DECL_EXPORT Scopes : public QAbstractListModel { Q_OBJECT Q_ENUMS(Roles) Q_PROPERTY(bool loaded READ loaded NOTIFY loadedChanged) public: explicit Scopes(QObject *parent = 0); ~Scopes(); enum Roles { RoleScope, RoleId, RoleVisible, RoleTitle }; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; Q_INVOKABLE int rowCount(const QModelIndex& parent = QModelIndex()) const; Q_INVOKABLE QVariant get(int row) const; Q_INVOKABLE QVariant get(QString const& scopeId) const; Scope* getScopeById(QString const& scopeId) const; unity::scopes::ScopeMetadata::SPtr getCachedMetadata(QString const& scopeId) const; void refreshScopeMetadata(); QHash roleNames() const; bool loaded() const; Q_SIGNALS: void loadedChanged(bool loaded); void metadataRefreshed(); private Q_SLOTS: void populateScopes(); void discoveryFinished(); void refreshFinished(); void invalidateScopeResults(QString const&); private: static int LIST_DELAY; QHash m_roles; QList m_scopes; QMap m_cachedMetadata; QThread* m_listThread; bool m_loaded; unity::scopes::Runtime::SPtr m_scopesRuntime; }; class ScopeListWorker: public QThread { Q_OBJECT public: void setRuntime(unity::scopes::Runtime::SPtr const& runtime); void setRuntimeConfig(QString const& config); void run() override; unity::scopes::Runtime::SPtr getRuntime() const; unity::scopes::MetadataMap metadataMap() const; Q_SIGNALS: void discoveryFinished(); private: QString m_runtimeConfig; unity::scopes::Runtime::SPtr m_scopesRuntime; unity::scopes::MetadataMap m_metadataMap; }; } // namespace scopes_ng #endif // NG_SCOPES_H unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/previewmodel.cpp0000644000015301777760000002577412320776744025022 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michał Sawicz * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // self #include "previewmodel.h" // local #include "collectors.h" #include "scope.h" #include "previewwidgetmodel.h" #include "resultsmodel.h" #include "utils.h" // Qt #include #include #include namespace scopes_ng { using namespace unity; PreviewModel::PreviewModel(QObject* parent) : QAbstractListModel(parent), m_loaded(false), m_processingAction(false), m_delayedClear(false), m_widgetColumnCount(1) { // we have one column by default PreviewWidgetModel* columnModel = new PreviewWidgetModel(this); m_previewWidgetModels.append(columnModel); } QHash PreviewModel::roleNames() const { QHash roles; roles[Roles::RoleColumnModel] = "columnModel"; return roles; } void PreviewModel::setResult(std::shared_ptr const& result) { m_previewedResult = result; } bool PreviewModel::event(QEvent* ev) { if (ev->type() == PushEvent::eventType) { PushEvent* pushEvent = static_cast(ev); switch (pushEvent->type()) { case PushEvent::PREVIEW: processPreviewChunk(pushEvent); return true; default: qWarning("PreviewModel: Unhandled PushEvent type"); break; } } return false; } void PreviewModel::processPreviewChunk(PushEvent* pushEvent) { CollectorBase::Status status; scopes::ColumnLayoutList columns; scopes::PreviewWidgetList widgets; QHash preview_data; status = pushEvent->collectPreviewData(columns, widgets, preview_data); if (status == CollectorBase::Status::CANCELLED) { return; } if (m_delayedClear) { clearAll(); m_delayedClear = false; setProcessingAction(false); } if (!columns.empty()) { setColumnLayouts(columns); } addWidgetDefinitions(widgets); updatePreviewData(preview_data); // status in [FINISHED, ERROR] if (status != CollectorBase::Status::INCOMPLETE) { // FIXME: do something special when preview finishes with error? m_loaded = true; Q_EMIT loadedChanged(); } } void PreviewModel::setDelayedClear() { m_delayedClear = true; // signal right away that the preview is "dirty" if (m_loaded) { m_loaded = false; Q_EMIT loadedChanged(); } } void PreviewModel::clearAll() { // clear column models for (int i = 0; i < m_previewWidgetModels.size(); i++) { m_previewWidgetModels[i]->clearWidgets(); } m_allData.clear(); m_columnLayouts.clear(); m_previewWidgets.clear(); m_dataToWidgetMap.clear(); if (m_loaded) { m_loaded = false; Q_EMIT loadedChanged(); } } void PreviewModel::setWidgetColumnCount(int count) { if (count != m_widgetColumnCount && count > 0) { int oldCount = m_widgetColumnCount; m_widgetColumnCount = count; // clear the existing columns for (int i = 0; i < std::min(count, oldCount); i++) { m_previewWidgetModels[i]->clearWidgets(); } if (oldCount < count) { // create new PreviewWidgetModel(s) beginInsertRows(QModelIndex(), oldCount, count - 1); for (int i = oldCount; i < count; i++) { PreviewWidgetModel* columnModel = new PreviewWidgetModel(this); m_previewWidgetModels.append(columnModel); } endInsertRows(); } else { // remove extra columns beginRemoveRows(QModelIndex(), count, oldCount - 1); for (int i = oldCount - 1; i >= count; i--) { delete m_previewWidgetModels.takeLast(); } endRemoveRows(); } // recalculate which columns do the widgets belong to for (int i = 0; i < m_previewWidgets.size(); i++) { addWidgetToColumnModel(m_previewWidgets[i]); } Q_EMIT widgetColumnCountChanged(); } } int PreviewModel::widgetColumnCount() const { return m_widgetColumnCount; } bool PreviewModel::loaded() const { return m_loaded; } bool PreviewModel::processingAction() const { return m_processingAction; } void PreviewModel::setProcessingAction(bool processing) { if (processing != m_processingAction) { m_processingAction = processing; Q_EMIT processingActionChanged(); } } void PreviewModel::setColumnLayouts(scopes::ColumnLayoutList const& layouts) { if (layouts.empty()) return; for (auto it = layouts.begin(); it != layouts.end(); ++it) { scopes::ColumnLayout const& layout = *it; int numColumns = layout.number_of_columns(); // build the list QList widgetsPerColumn; for (int i = 0; i < numColumns; i++) { std::vector widgetArr(layout.column(i)); QStringList widgets; for (unsigned int j = 0; j < widgetArr.size(); j++) { widgets.append(QString::fromStdString(widgetArr[j])); } widgetsPerColumn.append(widgets); } m_columnLayouts[numColumns] = widgetsPerColumn; } } void PreviewModel::addWidgetDefinitions(scopes::PreviewWidgetList const& widgets) { if (widgets.empty()) return; for (auto it = widgets.begin(); it != widgets.end(); ++it) { scopes::PreviewWidget const& widget = *it; QString id(QString::fromStdString(widget.id())); QString widget_type(QString::fromStdString(widget.widget_type())); QHash components; QVariantMap attributes; // collect all components and map their values if present in result for (auto const& kv_pair : widget.attribute_mappings()) { components[QString::fromStdString(kv_pair.first)] = QString::fromStdString(kv_pair.second); } processComponents(components, attributes); // collect all attributes and their values for (auto const& attr_pair : widget.attribute_values()) { attributes[QString::fromStdString(attr_pair.first)] = scopeVariantToQVariant(attr_pair.second); } if (!widget_type.isEmpty()) { auto preview_data = new PreviewWidgetData(id, widget_type, components, attributes); for (auto attr_it = components.begin(); attr_it != components.end(); ++attr_it) { m_dataToWidgetMap.insert(attr_it.value(), preview_data); } QSharedPointer widgetData(preview_data); m_previewWidgets.append(widgetData); addWidgetToColumnModel(widgetData); } } } void PreviewModel::processComponents(QHash const& components, QVariantMap& out_attributes) { if (components.empty()) return; // map from preview data and fallback to result data for (auto it = components.begin(); it != components.end(); ++it) { QString component_name(it.key()); QString field_name(it.value()); // check preview data if (m_allData.contains(field_name)) { out_attributes[component_name] = m_allData.value(field_name); } else if (m_previewedResult && m_previewedResult->contains(field_name.toStdString())) { out_attributes[component_name] = scopeVariantToQVariant(m_previewedResult->value(field_name.toStdString())); } else { // FIXME: should we do this? out_attributes[component_name] = QVariant(); } } } void PreviewModel::addWidgetToColumnModel(QSharedPointer const& widgetData) { int destinationColumnIndex = -1; int destinationRowIndex = -1; if (m_widgetColumnCount == 1 && !m_columnLayouts.contains(1)) { // no need to ask shell in this case, just put all in first column destinationColumnIndex = 0; destinationRowIndex = -1; } else if (m_columnLayouts.contains(m_widgetColumnCount)) { QList const& columnLayout = m_columnLayouts.value(m_widgetColumnCount); // find the row & col for (int i = 0; i < columnLayout.size(); i++) { destinationRowIndex = columnLayout[i].indexOf(widgetData->id); if (destinationRowIndex >= 0) { destinationColumnIndex = i; break; } } } else { // TODO: ask the shell destinationColumnIndex = 0; } if (destinationColumnIndex >= 0 && destinationColumnIndex < m_previewWidgetModels.size()) { PreviewWidgetModel* widgetModel = m_previewWidgetModels.at(destinationColumnIndex); widgetModel->insertWidget(widgetData, destinationRowIndex); } } void PreviewModel::updatePreviewData(QHash const& data) { QSet changedWidgets; for (auto it = data.begin(); it != data.end(); ++it) { m_allData.insert(it.key(), it.value()); auto map_it = m_dataToWidgetMap.constFind(it.key()); while (map_it != m_dataToWidgetMap.constEnd() && map_it.key() == it.key()) { changedWidgets.insert(map_it.value()); ++map_it; } } for (int i = 0; i < m_previewWidgets.size(); i++) { PreviewWidgetData* widget = m_previewWidgets.at(i).data(); if (changedWidgets.contains(widget)) { // re-process attributes and emit dataChanged processComponents(widget->component_map, widget->data); for (int j = 0; j < m_previewWidgetModels.size(); j++) { // returns true if the notification was emitted if (m_previewWidgetModels[j]->widgetChanged(widget)) { break; } } } } } PreviewWidgetData* PreviewModel::getWidgetData(QString const& widgetId) const { for (int i = 0; i < m_previewWidgets.size(); i++) { PreviewWidgetData* widgetData = m_previewWidgets[i].data(); if (widgetData->id == widgetId) { return widgetData; } } return nullptr; } int PreviewModel::rowCount(const QModelIndex&) const { return m_previewWidgetModels.size(); } QVariant PreviewModel::data(const QModelIndex& index, int role) const { switch (role) { case RoleColumnModel: return QVariant::fromValue(m_previewWidgetModels.at(index.row())); default: return QVariant(); } } } // namespace scopes_ng unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/categories.cpp0000644000015301777760000004073112320776744024433 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Canonical, Ltd. * * Authors: * Michał Sawicz * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // self #include "categories.h" // local #include "utils.h" #include #include #include #include #include #include #include #include using namespace unity; namespace scopes_ng { // FIXME: this should be in a common place #define CATEGORY_JSON_DEFAULTS R"({"schema-version":1,"template": {"category-layout":"grid","card-layout":"vertical","card-size":"small","overlay-mode":null,"collapsed-rows":2}, "components": { "title":null, "art": { "aspect-ratio":1.0, "fill-mode":"crop" }, "subtitle":null, "mascot":null, "emblem":null, "summary":null, "attributes":null, "background":null }, "resources":{}})" class CategoryData { public: CategoryData(scopes::Category::SCPtr const& category): m_resultsModel(nullptr), m_isSpecial(false) { setCategory(category); } // constructor for special (shell-overriden) categories CategoryData(QString const& id, QString const& title, QString const& icon, QString rawTemplate, QObject* countObject): m_catId(id), m_catTitle(title), m_catIcon(icon), m_rawTemplate(rawTemplate.toStdString()), m_resultsModel(nullptr), m_countObject(countObject), m_isSpecial(true) { parseTemplate(m_rawTemplate, &m_rendererTemplate, &m_components); } ~CategoryData() { if (m_resultsModel) { delete m_resultsModel; } } void setCategory(scopes::Category::SCPtr const& category) { m_category = category; m_rawTemplate = category->renderer_template().data(); parseTemplate(m_rawTemplate, &m_rendererTemplate, &m_components); } QString categoryId() const { return m_category ? QString::fromStdString(m_category->id()) : m_catId; } QString title() const { return m_category ? QString::fromStdString(m_category->title()) : m_catTitle; } QString icon() const { return m_category ? QString::fromStdString(m_category->icon()) : m_catIcon; } std::string rawTemplate() const { return m_rawTemplate; } bool overrideTemplate(std::string const& raw_template) { QJsonValue components; QJsonValue renderer; if (parseTemplate(raw_template, &renderer, &components)) { m_rawTemplate = raw_template; m_rendererTemplate = renderer; m_components = components; return true; } return false; } QJsonValue rendererTemplate() const { return m_rendererTemplate; } QJsonValue components() const { return m_components; } QHash getComponentsMapping() const { QHash result; QJsonObject components_dict = m_components.toObject(); for (auto it = components_dict.begin(); it != components_dict.end(); ++it) { if (it.value().isObject() == false) continue; QJsonObject component_dict(it.value().toObject()); QString fieldName(component_dict.value("field").toString()); if (fieldName.isEmpty()) continue; result[it.key()] = fieldName; } return result; } QVector updateAttributes(scopes::Category::SCPtr category) { QVector roles; if (category->title() != m_category->title()) { roles.append(Categories::RoleName); } if (category->icon() != m_category->icon()) { roles.append(Categories::RoleIcon); } if (category->renderer_template().data() != m_rawTemplate) { roles.append(Categories::RoleRawRendererTemplate); QJsonValue old_renderer(m_rendererTemplate); QJsonValue old_components(m_components); setCategory(category); if (m_rendererTemplate != old_renderer) { roles.append(Categories::RoleRenderer); } if (m_components != old_components) { roles.append(Categories::RoleComponents); } } else { setCategory(category); } return roles; } void setResultsModel(ResultsModel* model) { m_resultsModel = model; } ResultsModel* resultsModel() const { return m_resultsModel; } int resultsModelCount() const { if (m_resultsModel) { return m_resultsModel->rowCount(QModelIndex()); } if (m_countObject) { QVariant count(m_countObject->property("count")); return count.toInt(); } return 0; } bool isSpecial() const { return m_isSpecial; } private: static QJsonValue* DEFAULTS; scopes::Category::SCPtr m_category; QString m_catId; QString m_catTitle; QString m_catIcon; std::string m_rawTemplate; QJsonValue m_rendererTemplate; QJsonValue m_components; ResultsModel* m_resultsModel; QPointer m_countObject; bool m_isSpecial; static bool parseTemplate(std::string const& raw_template, QJsonValue* renderer, QJsonValue* components) { // lazy init of the defaults if (DEFAULTS == nullptr) { DEFAULTS = new QJsonValue(QJsonDocument::fromJson(QByteArray(CATEGORY_JSON_DEFAULTS)).object()); } QJsonParseError parseError; QJsonDocument category_doc = QJsonDocument::fromJson(QByteArray(raw_template.c_str()), &parseError); if (parseError.error != QJsonParseError::NoError || !category_doc.isObject()) { qWarning() << "Unable to parse category JSON: " << parseError.errorString(); return false; } QJsonObject category_root = mergeOverrides(*DEFAULTS, category_doc.object()).toObject(); // fixup parts we mangle QJsonValueRef templateRef = category_root["template"]; QJsonObject templateObj(templateRef.toObject()); if (templateObj.contains("card-background")) { QJsonValueRef cardBackgroundRef = templateObj["card-background"]; if (cardBackgroundRef.isString()) { QString background(cardBackgroundRef.toString()); cardBackgroundRef = QJsonValue::fromVariant(backgroundUriToVariant(background)); templateRef = templateObj; } } // FIXME: validate the merged json *renderer = category_root.value(QString("template")); *components = category_root.value(QString("components")); return true; } static QJsonValue mergeOverrides(QJsonValue const& defaultVal, QJsonValue const& overrideVal) { if (overrideVal.isObject() && defaultVal.isObject()) { QJsonObject obj(defaultVal.toObject()); QJsonObject overrideObj(overrideVal.toObject()); QJsonObject resultObj; // iterate over the default object keys and merge the values with the overrides for (auto it = obj.begin(); it != obj.end(); ++it) { if (overrideObj.contains(it.key())) { resultObj.insert(it.key(), mergeOverrides(it.value(), overrideObj[it.key()])); } else { resultObj.insert(it.key(), it.value()); } } // iterate over overrides keys and add everything that wasn't specified in default object for (auto it = overrideObj.begin(); it != overrideObj.end(); ++it) { if (!resultObj.contains(it.key())) { resultObj.insert(it.key(), it.value()); } } return resultObj; } else if (overrideVal.isString() && (defaultVal.isNull() || defaultVal.isObject())) { // special case the expansion of "art": "icon" -> "art": {"field": "icon"} QJsonObject resultObj(defaultVal.toObject()); resultObj.insert("field", overrideVal); return resultObj; } else if (defaultVal.isNull() && overrideVal.isObject()) { return overrideVal; } else { return overrideVal; } } }; QJsonValue* CategoryData::DEFAULTS = nullptr; Categories::Categories(QObject* parent) : QAbstractListModel(parent) { m_roles[Categories::RoleCategoryId] = "categoryId"; m_roles[Categories::RoleName] = "name"; m_roles[Categories::RoleIcon] = "icon"; m_roles[Categories::RoleRawRendererTemplate] = "rawRendererTemplate"; m_roles[Categories::RoleRenderer] = "renderer"; m_roles[Categories::RoleComponents] = "components"; m_roles[Categories::RoleProgressSource] = "progressSource"; m_roles[Categories::RoleResults] = "results"; m_roles[Categories::RoleCount] = "count"; } QHash Categories::roleNames() const { return m_roles; } int Categories::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return m_categories.size(); } ResultsModel* Categories::lookupCategory(std::string const& category_id) { return m_categoryResults[category_id]; } int Categories::getCategoryIndex(QString const& categoryId) const { // there shouldn't be too many categories, linear search should be fine for (int i = 0; i < m_categories.size(); i++) { if (m_categories[i]->categoryId() == categoryId) { return i; } } return -1; } int Categories::getFirstEmptyCategoryIndex() const { for (int i = 0; i < m_categories.size(); i++) { if (m_categories[i]->isSpecial()) { continue; } if (m_categories[i]->resultsModelCount() == 0) { return i; } } return m_categories.size(); } void Categories::registerCategory(scopes::Category::SCPtr category, ResultsModel* resultsModel) { // do we already have a category with this id? int index = getCategoryIndex(QString::fromStdString(category->id())); int emptyIndex = getFirstEmptyCategoryIndex(); if (index >= 0) { // re-registering an existing category will move it after the first non-empty category if (emptyIndex < index) { QSharedPointer catData; // we could do real move, but the view doesn't like it much beginRemoveRows(QModelIndex(), index, index); catData = m_categories.takeAt(index); endRemoveRows(); // check if any attributes of the category changed QVector changedRoles(catData->updateAttributes(category)); if (changedRoles.size() > 0) { resultsModel = catData->resultsModel(); if (resultsModel) { resultsModel->setComponentsMapping(catData->getComponentsMapping()); } } beginInsertRows(QModelIndex(), emptyIndex, emptyIndex); m_categories.insert(emptyIndex, catData); endInsertRows(); } else { CategoryData* catData = m_categories[index].data(); // check if any attributes of the category changed QVector changedRoles(catData->updateAttributes(category)); if (changedRoles.size() > 0) { resultsModel = catData->resultsModel(); if (resultsModel) { resultsModel->setComponentsMapping(catData->getComponentsMapping()); } QModelIndex changedIndex(this->index(index)); dataChanged(changedIndex, changedIndex, changedRoles); } } } else { CategoryData* catData = new CategoryData(category); if (resultsModel == nullptr) { resultsModel = new ResultsModel(this); } catData->setResultsModel(resultsModel); beginInsertRows(QModelIndex(), emptyIndex, emptyIndex); m_categories.insert(emptyIndex, QSharedPointer(catData)); resultsModel->setCategoryId(QString::fromStdString(category->id())); resultsModel->setComponentsMapping(catData->getComponentsMapping()); m_categoryResults[category->id()] = resultsModel; endInsertRows(); } } void Categories::updateResultCount(ResultsModel* resultsModel) { int idx = -1; for (int i = 0; i < m_categories.count(); i++) { if (m_categories[i]->resultsModel() == resultsModel) { idx = i; break; } } if (idx < 0) { qWarning("unable to update results counts"); return; } QVector roles; roles.append(RoleCount); QModelIndex changedIndex(index(idx)); dataChanged(changedIndex, changedIndex, roles); } void Categories::clearAll() { if (m_categories.count() == 0) return; Q_FOREACH(ResultsModel* model, m_categoryResults) { model->clearResults(); } QModelIndex changeStart(index(0)); QModelIndex changeEnd(index(m_categories.count() - 1)); QVector roles; roles.append(RoleCount); dataChanged(changeStart, changeEnd, roles); } bool Categories::overrideCategoryJson(QString const& categoryId, QString const& json) { int idx = getCategoryIndex(categoryId); if (idx >= 0) { CategoryData* catData = m_categories.at(idx).data(); if (!catData->overrideTemplate(json.toStdString())) { return false; } if (catData->resultsModel()) { catData->resultsModel()->setComponentsMapping(catData->getComponentsMapping()); } QModelIndex changeIndex(index(idx)); QVector roles; roles.append(RoleRawRendererTemplate); roles.append(RoleRenderer); roles.append(RoleComponents); dataChanged(changeIndex, changeIndex, roles); return true; } return false; } void Categories::addSpecialCategory(QString const& categoryId, QString const& name, QString const& icon, QString const& rawTemplate, QObject* countObject) { int index = getCategoryIndex(categoryId); if (index >= 0) { qWarning("ERROR! Category with id \"%s\" already exists!", categoryId.toStdString().c_str()); } else { CategoryData* catData = new CategoryData(categoryId, name, icon, rawTemplate, countObject); // prepend the category beginInsertRows(QModelIndex(), 0, 0); m_categories.prepend(QSharedPointer(catData)); endInsertRows(); if (countObject) { m_countObjects[countObject] = categoryId; QObject::connect(countObject, SIGNAL(countChanged()), this, SLOT(countChanged())); } } } void Categories::countChanged() { QObject* countObject = sender(); if (countObject != nullptr) { QString catId(m_countObjects[countObject]); if (catId.isEmpty()) return; int idx = getCategoryIndex(catId); if (idx < 0) return; QVector roles; roles.append(RoleCount); QModelIndex changedIndex(index(idx)); dataChanged(changedIndex, changedIndex, roles); } } QVariant Categories::data(const QModelIndex& index, int role) const { CategoryData* catData = m_categories.at(index.row()).data(); ResultsModel* resultsModel = catData->resultsModel(); switch (role) { case RoleCategoryId: return catData->categoryId(); case RoleName: return catData->title(); case RoleIcon: return catData->icon(); case RoleRawRendererTemplate: return QString::fromStdString(catData->rawTemplate()); case RoleRenderer: return catData->rendererTemplate().toVariant(); case RoleComponents: return catData->components().toVariant(); case RoleProgressSource: return QVariant(); case RoleResults: return QVariant::fromValue(resultsModel); case RoleCount: return catData->resultsModelCount(); default: return QVariant(); } } } // namespace scopes_ng unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/previewwidgetmodel.cpp0000644000015301777760000000636512320776744026221 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michał Sawicz * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // self #include "previewwidgetmodel.h" // local #include "utils.h" // Qt #include #include #include namespace scopes_ng { using namespace unity; PreviewWidgetModel::PreviewWidgetModel(QObject* parent) : QAbstractListModel(parent) { } QHash PreviewWidgetModel::roleNames() const { QHash roles; roles[Roles::RoleWidgetId] = "widgetId"; roles[Roles::RoleType] = "type"; roles[Roles::RoleProperties] = "properties"; return roles; } void PreviewWidgetModel::insertWidget(QSharedPointer const& widget, int position) { int insertPos = position >= 0 && position <= m_previewWidgets.count() ? position : m_previewWidgets.count(); beginInsertRows(QModelIndex(), insertPos, insertPos); m_previewWidgets.insert(insertPos, widget); endInsertRows(); } void PreviewWidgetModel::addWidgets(QList> const& widgetList) { if (widgetList.size() == 0) return; beginInsertRows(QModelIndex(), m_previewWidgets.count(), m_previewWidgets.size() + widgetList.size() - 1); m_previewWidgets.append(widgetList); endInsertRows(); } void PreviewWidgetModel::adoptWidgets(QList> const& widgetList) { beginResetModel(); m_previewWidgets.clear(); m_previewWidgets.append(widgetList); endResetModel(); } void PreviewWidgetModel::clearWidgets() { beginRemoveRows(QModelIndex(), 0, m_previewWidgets.count() - 1); m_previewWidgets.clear(); endRemoveRows(); } bool PreviewWidgetModel::widgetChanged(PreviewWidgetData* widget) { for (int i = 0; i < m_previewWidgets.size(); i++) { if (m_previewWidgets[i].data() == widget) { QModelIndex changedIndex(index(i)); QVector changedRoles; changedRoles.append(PreviewWidgetModel::RoleProperties); dataChanged(changedIndex, changedIndex, changedRoles); return true; } } return false; } int PreviewWidgetModel::rowCount(const QModelIndex&) const { return m_previewWidgets.size(); } QVariant PreviewWidgetModel::data(const QModelIndex& index, int role) const { auto widget_data = m_previewWidgets.at(index.row()); switch (role) { case RoleWidgetId: return widget_data->id; case RoleType: return widget_data->type; case RoleProperties: return widget_data->data; default: return QVariant(); } } } // namespace scopes_ng unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/previewmodel.h0000644000015301777760000000723312320776744024455 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michał Sawicz * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NG_PREVIEW_MODEL_H #define NG_PREVIEW_MODEL_H #include #include #include #include #include #include #include #include #include namespace scopes_ng { struct PreviewWidgetData { QString id; QString type; QHash component_map; QVariantMap data; PreviewWidgetData(QString const& id_, QString const& type_, QHash const& components, QVariantMap const& data_): id(id_), type(type_), component_map(components), data(data_) { } }; class PreviewWidgetModel; class PushEvent; class Scope; class Q_DECL_EXPORT PreviewModel : public QAbstractListModel { Q_OBJECT Q_ENUMS(Roles) Q_PROPERTY(int widgetColumnCount READ widgetColumnCount WRITE setWidgetColumnCount NOTIFY widgetColumnCountChanged) Q_PROPERTY(bool loaded READ loaded NOTIFY loadedChanged) Q_PROPERTY(bool processingAction READ processingAction NOTIFY processingActionChanged) public: explicit PreviewModel(QObject* parent = 0); enum Roles { RoleColumnModel }; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; QHash roleNames() const override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; virtual bool event(QEvent* ev) override; void setResult(std::shared_ptr const&); void setWidgetColumnCount(int count); int widgetColumnCount() const; bool loaded() const; bool processingAction() const; void setProcessingAction(bool processing); void setDelayedClear(); void clearAll(); PreviewWidgetData* getWidgetData(QString const& widgetId) const; Q_SIGNALS: void widgetColumnCountChanged(); void loadedChanged(); void processingActionChanged(); void triggered(QString const&, QString const&, QVariantMap const&); private: void processPreviewChunk(PushEvent* pushEvent); void setColumnLayouts(unity::scopes::ColumnLayoutList const&); void addWidgetDefinitions(unity::scopes::PreviewWidgetList const&); void updatePreviewData(QHash const&); void addWidgetToColumnModel(QSharedPointer const&); void processComponents(QHash const& components, QVariantMap& out_attributes); bool m_loaded; bool m_processingAction; bool m_delayedClear; int m_widgetColumnCount; QMap m_allData; QHash> m_columnLayouts; QList m_previewWidgetModels; QList> m_previewWidgets; QMultiMap m_dataToWidgetMap; std::shared_ptr m_previewedResult; }; } // namespace scopes_ng Q_DECLARE_METATYPE(scopes_ng::PreviewModel*) #endif // NG_PREVIEW_MODEL_H unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/scopes.cpp0000644000015301777760000001767712320776744023617 0ustar pbusernogroup00000000000000/* * Copyright (C) 2011 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // Self #include "scopes.h" // Local #include "scope.h" // Qt #include #include #include #include #include #include #include namespace scopes_ng { using namespace unity; void ScopeListWorker::run() { try { // m_runtimeConfig should be null in most cases, and empty string is for system-wide fallback if (!m_scopesRuntime) { scopes::Runtime::UPtr runtime_uptr = scopes::Runtime::create(m_runtimeConfig.toStdString()); m_scopesRuntime = std::move(runtime_uptr); } auto registry = m_scopesRuntime->registry(); m_metadataMap = registry->list(); } catch (unity::Exception const& err) { qWarning("ERROR! Caught %s", err.to_string().c_str()); } Q_EMIT discoveryFinished(); } void ScopeListWorker::setRuntimeConfig(QString const& config) { m_runtimeConfig = config; } void ScopeListWorker::setRuntime(scopes::Runtime::SPtr const& runtime) { m_scopesRuntime = runtime; } scopes::Runtime::SPtr ScopeListWorker::getRuntime() const { return m_scopesRuntime; } scopes::MetadataMap ScopeListWorker::metadataMap() const { return m_metadataMap; } int Scopes::LIST_DELAY = -1; Scopes::Scopes(QObject *parent) : QAbstractListModel(parent) , m_listThread(nullptr) , m_loaded(false) { m_roles[Scopes::RoleScope] = "scope"; m_roles[Scopes::RoleId] = "id"; m_roles[Scopes::RoleVisible] = "visible"; m_roles[Scopes::RoleTitle] = "title"; // delaying spawning the worker thread, causes problems with qmlplugindump // without it if (LIST_DELAY < 0) { QByteArray listDelay = qgetenv("UNITY_SCOPES_LIST_DELAY"); LIST_DELAY = listDelay.isNull() ? 100 : listDelay.toInt(); } QTimer::singleShot(LIST_DELAY, this, SLOT(populateScopes())); QDBusConnection::sessionBus().connect(QString(), QString("/com/canonical/unity/scopes"), QString("com.canonical.unity.scopes"), QString("InvalidateResults"), this, SLOT(invalidateScopeResults(QString))); } Scopes::~Scopes() { if (m_listThread && !m_listThread->isFinished()) { // libunity-scopes supports timeouts, so this shouldn't block forever m_listThread->wait(); } } QHash Scopes::roleNames() const { return m_roles; } int Scopes::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent) return m_scopes.count(); } void Scopes::populateScopes() { auto thread = new ScopeListWorker; QByteArray runtimeConfig = qgetenv("UNITY_SCOPES_RUNTIME_PATH"); thread->setRuntimeConfig(QString::fromLocal8Bit(runtimeConfig)); QObject::connect(thread, &ScopeListWorker::discoveryFinished, this, &Scopes::discoveryFinished); QObject::connect(thread, &ScopeListWorker::finished, thread, &QObject::deleteLater); m_listThread = thread; m_listThread->start(); } void Scopes::discoveryFinished() { ScopeListWorker* thread = qobject_cast(sender()); m_scopesRuntime = thread->getRuntime(); auto scopes = thread->metadataMap(); // FIXME: use a dconf setting for this QByteArray enabledScopes = qgetenv("UNITY_SCOPES_LIST"); beginResetModel(); if (!enabledScopes.isNull()) { QList scopeList = enabledScopes.split(';'); for (int i = 0; i < scopeList.size(); i++) { std::string scope_name(scopeList[i].constData()); auto it = scopes.find(scope_name); if (it != scopes.end()) { auto scope = new Scope(this); scope->setScopeData(it->second); m_scopes.append(scope); } } } else { // add all the scopes for (auto it = scopes.begin(); it != scopes.end(); ++it) { auto scope = new Scope(this); scope->setScopeData(it->second); m_scopes.append(scope); } } // cache all the metadata for (auto it = scopes.begin(); it != scopes.end(); ++it) { m_cachedMetadata[QString::fromStdString(it->first)] = std::make_shared(it->second); } endResetModel(); m_loaded = true; Q_EMIT loadedChanged(m_loaded); Q_EMIT metadataRefreshed(); m_listThread = nullptr; } void Scopes::refreshFinished() { ScopeListWorker* thread = qobject_cast(sender()); auto scopes = thread->metadataMap(); // cache all the metadata for (auto it = scopes.begin(); it != scopes.end(); ++it) { m_cachedMetadata[QString::fromStdString(it->first)] = std::make_shared(it->second); } Q_EMIT metadataRefreshed(); m_listThread = nullptr; } void Scopes::invalidateScopeResults(QString const& scopeName) { // HACK! mediascanner invalidates local media scopes, but those are aggregated, so let's "forward" the call if (scopeName == "mediascanner-music") { invalidateScopeResults("musicaggregator"); } else if (scopeName == "mediascanner-video") { invalidateScopeResults("videoaggregator"); } else if (scopeName == "smart-scopes") { // emitted when smart scopes proxy discovers new scopes Q_FOREACH(Scope* scope, m_scopes) { scope->invalidateResults(); } } Scope* scope = getScopeById(scopeName); if (scope == nullptr) return; scope->invalidateResults(); } QVariant Scopes::data(const QModelIndex& index, int role) const { Scope* scope = m_scopes.at(index.row()); switch (role) { case Scopes::RoleScope: return QVariant::fromValue(scope); case Scopes::RoleId: return QString(scope->id()); case Scopes::RoleVisible: return QVariant::fromValue(scope->visible()); case Scopes::RoleTitle: return QString(scope->name()); default: return QVariant(); } } QVariant Scopes::get(int row) const { if (row >= m_scopes.size() || row < 0) { return QVariant(); } return data(QAbstractListModel::index(row), RoleScope); } QVariant Scopes::get(const QString& scopeId) const { Scope* scope = getScopeById(scopeId); return scope != nullptr ? QVariant::fromValue(scope) : QVariant(); } Scope* Scopes::getScopeById(QString const& scopeId) const { Q_FOREACH(Scope* scope, m_scopes) { if (scope->id() == scopeId) { return scope; } } return nullptr; } scopes::ScopeMetadata::SPtr Scopes::getCachedMetadata(QString const& scopeId) const { auto it = m_cachedMetadata.constFind(scopeId); if (it != m_cachedMetadata.constEnd()) { return it.value(); } return scopes::ScopeMetadata::SPtr(); } void Scopes::refreshScopeMetadata() { // make sure there's just one listing in-progress at any given time if (m_listThread == nullptr && m_scopesRuntime) { auto thread = new ScopeListWorker; thread->setRuntime(m_scopesRuntime); QObject::connect(thread, &ScopeListWorker::discoveryFinished, this, &Scopes::refreshFinished); QObject::connect(thread, &ScopeListWorker::finished, thread, &QObject::deleteLater); m_listThread = thread; m_listThread->start(); } } bool Scopes::loaded() const { return m_loaded; } } // namespace scopes_ng unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/previewwidgetmodel.h0000644000015301777760000000401112320776744025650 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michał Sawicz * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NG_PREVIEW_WIDGET_MODEL_H #define NG_PREVIEW_WIDGET_MODEL_H #include #include #include #include #include #include #include "previewmodel.h" namespace scopes_ng { class Q_DECL_EXPORT PreviewWidgetModel : public QAbstractListModel { Q_OBJECT Q_ENUMS(Roles) public: explicit PreviewWidgetModel(QObject* parent = 0); enum Roles { RoleWidgetId, RoleType, RoleProperties }; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; QHash roleNames() const override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; void insertWidget(QSharedPointer const&, int); void addWidgets(QList> const&); void adoptWidgets(QList> const&); bool widgetChanged(PreviewWidgetData*); void clearWidgets(); private Q_SLOTS: private: QList> m_previewWidgets; std::shared_ptr m_previewedResult; }; } // namespace scopes_ng Q_DECLARE_METATYPE(scopes_ng::PreviewWidgetModel*) #endif // NG_PREVIEW_WIDGET_MODEL_H unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/utils.h0000644000015301777760000000212012320776744023101 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NG_UTILS_H #define NG_UTILS_H // Qt #include #include namespace scopes_ng { Q_DECL_EXPORT QVariant scopeVariantToQVariant(unity::scopes::Variant const& variant); Q_DECL_EXPORT unity::scopes::Variant qVariantToScopeVariant(QVariant const& variant); Q_DECL_EXPORT QVariant backgroundUriToVariant(QString const& uri); } // namespace scopes_ng #endif // NG_SCOPES_H unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/iconutils.h0000644000015301777760000000154712320776744023766 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: * Michal Hruby */ #ifndef ICONUTILS_H #define ICONUTILS_H #include #include QString uriToThumbnailerProviderString(QString const &uri, QVariantHash const &metadata); #endif unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/previewstack.h0000644000015301777760000000527412320776744024465 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michał Sawicz * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NG_PREVIEW_STACK_H #define NG_PREVIEW_STACK_H #include #include #include #include #include #include #include #include "collectors.h" namespace scopes_ng { class PreviewModel; class Scope; class Q_DECL_EXPORT PreviewStack : public QAbstractListModel { Q_OBJECT Q_ENUMS(Roles) Q_PROPERTY(int widgetColumnCount READ widgetColumnCount WRITE setWidgetColumnCount NOTIFY widgetColumnCountChanged) public: explicit PreviewStack(QObject* parent = 0); virtual ~PreviewStack(); enum Roles { RolePreviewModel }; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; QHash roleNames() const override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; virtual bool event(QEvent* ev) override; Q_INVOKABLE scopes_ng::PreviewModel* get(int index) const; void loadForResult(unity::scopes::Result::SPtr const&); void setWidgetColumnCount(int columnCount); int widgetColumnCount() const; void setAssociatedScope(scopes_ng::Scope*); Q_SIGNALS: void widgetColumnCountChanged(); private Q_SLOTS: void widgetTriggered(QString const&, QString const&, QVariantMap const&); private: void processActionResponse(PushEvent* pushEvent); void dispatchPreview(unity::scopes::Variant const& extra_data = unity::scopes::Variant()); int m_widgetColumnCount; QList m_previews; PreviewModel* m_activePreview; QPointer m_associatedScope; unity::scopes::QueryCtrlProxy m_lastPreviewQuery; QMap> m_listeners; std::shared_ptr m_lastActivation; unity::scopes::Result::SPtr m_previewedResult; }; } // namespace scopes_ng Q_DECLARE_METATYPE(scopes_ng::PreviewStack*) #endif // NG_PREVIEW_STACK_H unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/scope.h0000644000015301777760000001321312320776755023061 0ustar pbusernogroup00000000000000/* * Copyright (C) 2011 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NG_SCOPE_H #define NG_SCOPE_H // Qt #include #include #include #include #include #include #include // scopes #include #include #include #include namespace scopes_ng { class Categories; class PushEvent; class PreviewStack; class Q_DECL_EXPORT Scope : public QObject { Q_OBJECT Q_PROPERTY(QString id READ id NOTIFY idChanged) Q_PROPERTY(QString name READ name NOTIFY nameChanged) Q_PROPERTY(QString iconHint READ iconHint NOTIFY iconHintChanged) Q_PROPERTY(QString description READ description NOTIFY descriptionChanged) Q_PROPERTY(QString searchHint READ searchHint NOTIFY searchHintChanged) Q_PROPERTY(bool searchInProgress READ searchInProgress NOTIFY searchInProgressChanged) Q_PROPERTY(bool visible READ visible NOTIFY visibleChanged) Q_PROPERTY(QString shortcut READ shortcut NOTIFY shortcutChanged) Q_PROPERTY(scopes_ng::Categories* categories READ categories NOTIFY categoriesChanged) //Q_PROPERTY(Filters* filters READ filters NOTIFY filtersChanged) Q_PROPERTY(QString searchQuery READ searchQuery WRITE setSearchQuery NOTIFY searchQueryChanged) Q_PROPERTY(QString noResultsHint READ noResultsHint WRITE setNoResultsHint NOTIFY noResultsHintChanged) Q_PROPERTY(QString formFactor READ formFactor WRITE setFormFactor NOTIFY formFactorChanged) Q_PROPERTY(bool isActive READ isActive WRITE setActive NOTIFY isActiveChanged) public: explicit Scope(QObject *parent = 0); virtual ~Scope(); virtual bool event(QEvent* ev) override; /* getters */ QString id() const; QString name() const; QString iconHint() const; QString description() const; QString searchHint() const; bool visible() const; QString shortcut() const; bool searchInProgress() const; Categories* categories() const; //Filters* filters() const; QString searchQuery() const; QString noResultsHint() const; QString formFactor() const; bool isActive() const; /* setters */ void setSearchQuery(const QString& search_query); void setNoResultsHint(const QString& hint); void setFormFactor(const QString& form_factor); void setActive(const bool); Q_INVOKABLE void activate(QVariant const& result); Q_INVOKABLE scopes_ng::PreviewStack* preview(QVariant const& result); Q_INVOKABLE void cancelActivation(); Q_INVOKABLE void closeScope(scopes_ng::Scope* scope); void setScopeData(unity::scopes::ScopeMetadata const& data); void handleActivation(std::shared_ptr const&, unity::scopes::Result::SPtr const&); void activateUri(QString const& uri); void invalidateResults(); Q_SIGNALS: void idChanged(); void nameChanged(const std::string&); void iconHintChanged(const std::string&); void descriptionChanged(const std::string&); void searchHintChanged(const std::string&); void searchInProgressChanged(); void visibleChanged(bool); void shortcutChanged(const std::string&); void categoriesChanged(); //void filtersChanged(); void searchQueryChanged(); void noResultsHintChanged(); void formFactorChanged(); void isActiveChanged(bool); // signals triggered by activate(..) or preview(..) requests. void showDash(); void hideDash(); void gotoUri(QString const& uri); void activated(); void previewRequested(QVariant const& result); void gotoScope(QString const& scopeId); void openScope(scopes_ng::Scope* scope); void activateApplication(QString const& desktop); private Q_SLOTS: void flushUpdates(); void metadataRefreshed(); void internetFlagChanged(QString const& key); private: void processSearchChunk(PushEvent* pushEvent); void processPerformQuery(std::shared_ptr const& response, bool allowDelayedActivation); void processResultSet(QList>& result_set); void dispatchSearch(); void invalidateLastSearch(); QString m_scopeId; QString m_searchQuery; QString m_noResultsHint; QString m_formFactor; bool m_isActive; bool m_searchInProgress; bool m_resultsDirty; bool m_delayedClear; unity::scopes::ScopeProxy m_proxy; unity::scopes::ScopeMetadata::SPtr m_scopeMetadata; unity::scopes::SearchListenerBase::SPtr m_lastSearch; unity::scopes::QueryCtrlProxy m_lastSearchQuery; unity::scopes::ActivationListenerBase::SPtr m_lastActivation; std::shared_ptr m_delayedActivation; QGSettings* m_settings; Categories* m_categories; QTimer m_aggregatorTimer; QTimer m_clearTimer; QList> m_cachedResults; QSet m_tempScopes; }; } // namespace scopes_ng Q_DECLARE_METATYPE(scopes_ng::Scope*) #endif // NG_SCOPE_H unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/utils.cpp0000644000015301777760000001013012320776744023434 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // self #include "utils.h" #include namespace scopes_ng { using namespace unity; QVariant scopeVariantToQVariant(scopes::Variant const& variant) { switch (variant.which()) { case scopes::Variant::Type::Null: return QVariant(); case scopes::Variant::Type::Int: return QVariant(variant.get_int()); case scopes::Variant::Type::Bool: return QVariant(variant.get_bool()); case scopes::Variant::Type::String: return QVariant(QString::fromStdString(variant.get_string())); case scopes::Variant::Type::Double: return QVariant(variant.get_double()); case scopes::Variant::Type::Dict: { scopes::VariantMap dict(variant.get_dict()); QVariantMap result_dict; for (auto it = dict.begin(); it != dict.end(); ++it) { result_dict.insert(QString::fromStdString(it->first), scopeVariantToQVariant(it->second)); } return result_dict; } case scopes::Variant::Type::Array: { scopes::VariantArray arr(variant.get_array()); QVariantList result_list; for (unsigned i = 0; i < arr.size(); i++) { result_list.append(scopeVariantToQVariant(arr[i])); } return result_list; } default: qWarning("Unhandled Variant type"); return QVariant(); } } scopes::Variant qVariantToScopeVariant(QVariant const& variant) { if (variant.isNull()) { return scopes::Variant(); } switch (variant.type()) { case QMetaType::Bool: return scopes::Variant(variant.toBool()); case QMetaType::Int: return scopes::Variant(variant.toInt()); case QMetaType::Double: return scopes::Variant(variant.toDouble()); case QMetaType::QString: return scopes::Variant(variant.toString().toStdString()); case QMetaType::QVariantMap: { scopes::VariantMap vm; QVariantMap m(variant.toMap()); for (auto it = m.begin(); it != m.end(); ++it) { vm[it.key().toStdString()] = qVariantToScopeVariant(it.value()); } return scopes::Variant(vm); } case QMetaType::QVariantList: { QVariantList l(variant.toList()); scopes::VariantArray arr; for (int i = 0; i < l.size(); i++) { arr.push_back(qVariantToScopeVariant(l[i])); } return scopes::Variant(arr); } default: qWarning("Unhandled QVariant type: %s", variant.typeName()); return scopes::Variant(); } } QVariant backgroundUriToVariant(QString const& uri) { if (uri.startsWith(QLatin1String("color:///"))) { QVariantList elements; elements.append(uri.mid(9)); QVariantMap m; m["type"] = QString("color"); m["elements"] = elements; return m; } else if (uri.startsWith(QLatin1String("gradient:///"))) { QStringList parts = uri.mid(12).split("/", QString::SkipEmptyParts); QVariantList elements; for (int i = 0; i < parts.size(); i++) { elements.append(parts[i]); } QVariantMap m; m["type"] = QString("gradient"); m["elements"] = elements; return m; } else { return QVariant(uri); } } } // namespace scopes_ng unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/iconutils.cpp0000644000015301777760000000332312320776744024313 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: * Michal Hruby */ #include "iconutils.h" #include #include #include #define BASE_THEME_ICON_URI "image://theme/" #define BASE_THUMBNAILER_URI "image://thumbnailer/" #define BASE_ALBUMART_URI "image://albumart/" QString uriToThumbnailerProviderString(QString const &uri, QVariantHash const &metadata) { if (uri.startsWith(QLatin1String("file:///")) || uri.startsWith(QLatin1String("album://"))) { bool isAlbum = metadata.contains("album") && metadata.contains("artist"); QString thumbnailerUri; if (isAlbum) { thumbnailerUri = BASE_ALBUMART_URI; QUrlQuery query; query.addQueryItem(QStringLiteral("artist"), metadata["artist"].toString()); query.addQueryItem(QStringLiteral("album"), metadata["album"].toString()); thumbnailerUri.append(query.toString()); } else { thumbnailerUri = BASE_THUMBNAILER_URI; thumbnailerUri.append(uri.midRef(7)); } return thumbnailerUri; } return QString::null; } unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/scope.cpp0000644000015301777760000004302712320776755023422 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // Self #include "scope.h" // local #include "categories.h" #include "collectors.h" #include "previewstack.h" #include "utils.h" #include "scopes.h" // Qt #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace scopes_ng { using namespace unity; const int AGGREGATION_TIMEOUT = 110; const int CLEAR_TIMEOUT = 240; Scope::Scope(QObject *parent) : QObject(parent) , m_formFactor("phone") , m_isActive(false) , m_searchInProgress(false) , m_resultsDirty(false) , m_delayedClear(false) { m_categories = new Categories(this); m_settings = QGSettings::isSchemaInstalled("com.canonical.Unity.Lenses") ? new QGSettings("com.canonical.Unity.Lenses", QByteArray(), this) : nullptr; QObject::connect(m_settings, &QGSettings::changed, this, &Scope::internetFlagChanged); m_aggregatorTimer.setSingleShot(true); QObject::connect(&m_aggregatorTimer, &QTimer::timeout, this, &Scope::flushUpdates); m_clearTimer.setSingleShot(true); QObject::connect(&m_clearTimer, &QTimer::timeout, this, &Scope::flushUpdates); } Scope::~Scope() { if (m_lastSearch) { std::dynamic_pointer_cast(m_lastSearch)->invalidate(); } if (m_lastActivation) { std::dynamic_pointer_cast(m_lastActivation)->invalidate(); } } void Scope::processSearchChunk(PushEvent* pushEvent) { CollectorBase::Status status; QList> results; status = pushEvent->collectSearchResults(results); if (status == CollectorBase::Status::CANCELLED) { return; } if (m_cachedResults.empty()) { m_cachedResults.swap(results); } else { m_cachedResults.append(results); } if (status == CollectorBase::Status::INCOMPLETE) { if (!m_aggregatorTimer.isActive()) { // the longer we've been waiting for the results, the shorter the timeout qint64 inProgressMs = pushEvent->msecsSinceStart(); double mult = 1.0 / std::max(1, static_cast((inProgressMs / 150) + 1)); m_aggregatorTimer.start(AGGREGATION_TIMEOUT * mult); } } else { // status in [FINISHED, ERROR] m_aggregatorTimer.stop(); flushUpdates(); if (m_searchInProgress) { m_searchInProgress = false; Q_EMIT searchInProgressChanged(); } } } bool Scope::event(QEvent* ev) { if (ev->type() == PushEvent::eventType) { PushEvent* pushEvent = static_cast(ev); switch (pushEvent->type()) { case PushEvent::SEARCH: processSearchChunk(pushEvent); return true; case PushEvent::ACTIVATION: { std::shared_ptr response; std::shared_ptr result; pushEvent->collectActivationResponse(response, result); if (response) { handleActivation(response, result); } return true; } default: qWarning("Unknown PushEvent type!"); return false; } } return QObject::event(ev); } void Scope::handleActivation(std::shared_ptr const& response, scopes::Result::SPtr const& result) { switch (response->status()) { case scopes::ActivationResponse::NotHandled: activateUri(QString::fromStdString(result->uri())); break; case scopes::ActivationResponse::HideDash: Q_EMIT hideDash(); break; case scopes::ActivationResponse::ShowDash: Q_EMIT showDash(); break; case scopes::ActivationResponse::ShowPreview: Q_EMIT previewRequested(QVariant::fromValue(result)); break; case scopes::ActivationResponse::PerformQuery: processPerformQuery(response, true); break; default: break; } } void Scope::metadataRefreshed() { std::shared_ptr response; response.swap(m_delayedActivation); processPerformQuery(response, false); } void Scope::internetFlagChanged(QString const& key) { if (key != "remoteContentSearch") { return; } invalidateResults(); } void Scope::processPerformQuery(std::shared_ptr const& response, bool allowDelayedActivation) { scopes_ng::Scopes* scopes = qobject_cast(parent()); if (scopes == nullptr) { qWarning("Scope instance %p doesn't have Scopes as a parent", static_cast(this)); return; } if (!response) { return; } if (response->status() == scopes::ActivationResponse::PerformQuery) { scopes::CannedQuery q(response->query()); QString scopeId(QString::fromStdString(q.scope_id())); QString searchString(QString::fromStdString(q.query_string())); // figure out if this scope is already favourited Scope* scope = scopes->getScopeById(scopeId); if (scope != nullptr) { // TODO: change department, filters, query_string? scope->setSearchQuery(searchString); Q_EMIT gotoScope(scopeId); } else { // create temp dash page auto meta_sptr = scopes->getCachedMetadata(scopeId); if (meta_sptr) { scope = new scopes_ng::Scope(this); scope->setScopeData(*meta_sptr); scope->setSearchQuery(searchString); m_tempScopes.insert(scope); Q_EMIT openScope(scope); } else if (allowDelayedActivation) { // request registry refresh to get the missing metadata m_delayedActivation = response; QObject::connect(scopes, &Scopes::metadataRefreshed, this, &Scope::metadataRefreshed); scopes->refreshScopeMetadata(); } else { qWarning("Unable to find scope \"%s\" after metadata refresh", q.scope_id().c_str()); } } } } void Scope::flushUpdates() { if (m_delayedClear) { // TODO: here we could do resultset diffs m_categories->clearAll(); m_delayedClear = false; } if (m_clearTimer.isActive()) { m_clearTimer.stop(); } processResultSet(m_cachedResults); // clears the result list } void Scope::processResultSet(QList>& result_set) { if (result_set.count() == 0) return; // this will keep the list of categories in order QList categories; // split the result_set by category_id QMap>> category_results; while (!result_set.empty()) { auto result = result_set.takeFirst(); if (!category_results.contains(result->category()->id())) { categories.append(result->category()); } category_results[result->category()->id()].append(std::move(result)); } Q_FOREACH(scopes::Category::SCPtr const& category, categories) { ResultsModel* category_model = m_categories->lookupCategory(category->id()); if (category_model == nullptr) { category_model = new ResultsModel(m_categories); category_model->setCategoryId(QString::fromStdString(category->id())); category_model->addResults(category_results[category->id()]); m_categories->registerCategory(category, category_model); } else { // FIXME: only update when we know it's necessary m_categories->registerCategory(category, nullptr); category_model->addResults(category_results[category->id()]); m_categories->updateResultCount(category_model); } } } void Scope::invalidateLastSearch() { if (m_lastSearch) { std::dynamic_pointer_cast(m_lastSearch)->invalidate(); m_lastSearch.reset(); } if (m_lastSearchQuery) { m_lastSearchQuery->cancel(); m_lastSearchQuery.reset(); } if (m_aggregatorTimer.isActive()) { m_aggregatorTimer.stop(); } m_cachedResults.clear(); } void Scope::dispatchSearch() { invalidateLastSearch(); m_delayedClear = true; m_clearTimer.start(CLEAR_TIMEOUT); /* There are a few objects associated with searches: * 1) SearchResultReceiver 2) ResultCollector 3) PushEvent * * SearchResultReceiver is associated with the search and has methods that get called * by the scopes framework when results / categories / annotations are received. * Since the notification methods (push(...)) of SearchResultReceiver are called * from different thread(s), it uses ResultCollector to collect multiple results * in a thread-safe manner. * Once a couple of results are collected, the collector is sent via a PushEvent * to the UI thread, where it is processed. When the results are collected by the UI thread, * the collector continues to collect more results, and uses another PushEvent to post them. * * If a new query is submitted the previous one is marked as cancelled by invoking * SearchResultReceiver::invalidate() and any PushEvent that is waiting to be processed * will be discarded as the collector will also be marked as invalid. * The new query will have new instances of SearchResultReceiver and ResultCollector. */ m_resultsDirty = false; if (!m_searchInProgress) { m_searchInProgress = true; Q_EMIT searchInProgressChanged(); } if (m_proxy) { scopes::SearchMetadata meta("C", m_formFactor.toStdString()); //FIXME if (m_settings) { QVariant remoteSearch(m_settings->get("remote-content-search")); if (remoteSearch.toString() == QString("none")) { meta["no-internet"] = true; } } m_lastSearch.reset(new SearchResultReceiver(this)); try { m_lastSearchQuery = m_proxy->search(m_searchQuery.toStdString(), meta, m_lastSearch); } catch (std::exception& e) { qWarning("Caught an error from create_query(): %s", e.what()); } catch (...) { qWarning("Caught an error from create_query()"); } } if (!m_lastSearchQuery) { // something went wrong, reset search state m_searchInProgress = false; Q_EMIT searchInProgressChanged(); } } void Scope::setScopeData(scopes::ScopeMetadata const& data) { m_scopeMetadata = std::make_shared(data); m_proxy = data.proxy(); } QString Scope::id() const { return QString::fromStdString(m_scopeMetadata ? m_scopeMetadata->scope_id() : ""); } QString Scope::name() const { return QString::fromStdString(m_scopeMetadata ? m_scopeMetadata->display_name() : ""); } QString Scope::iconHint() const { std::string icon; try { if (m_scopeMetadata) { icon = m_scopeMetadata->icon(); } } catch (...) { // throws if the value isn't set, safe to ignore } return QString::fromStdString(icon); } QString Scope::description() const { return QString::fromStdString(m_scopeMetadata ? m_scopeMetadata->description() : ""); } QString Scope::searchHint() const { return QString::fromStdString(m_scopeMetadata ? m_scopeMetadata->search_hint() : ""); } bool Scope::searchInProgress() const { return m_searchInProgress; } bool Scope::visible() const { // FIXME: get from scope config return true; } QString Scope::shortcut() const { std::string hotkey; try { if (m_scopeMetadata) { hotkey = m_scopeMetadata->hot_key(); } } catch (...) { // throws if the value isn't set, safe to ignore } return QString::fromStdString(hotkey); } Categories* Scope::categories() const { return m_categories; } /* Filters* Scope::filters() const { return m_filters.get(); } */ QString Scope::searchQuery() const { return m_searchQuery; } QString Scope::noResultsHint() const { return m_noResultsHint; } QString Scope::formFactor() const { return m_formFactor; } bool Scope::isActive() const { return m_isActive; } void Scope::setSearchQuery(const QString& search_query) { /* Checking for m_searchQuery.isNull() which returns true only when the string has never been set is necessary because when search_query is the empty string ("") and m_searchQuery is the null string, search_query != m_searchQuery is still true. */ if (m_searchQuery.isNull() || search_query != m_searchQuery) { m_searchQuery = search_query; // FIXME: use a timeout dispatchSearch(); Q_EMIT searchQueryChanged(); } } void Scope::setNoResultsHint(const QString& hint) { if (hint != m_noResultsHint) { m_noResultsHint = hint; Q_EMIT noResultsHintChanged(); } } void Scope::setFormFactor(const QString& form_factor) { if (form_factor != m_formFactor) { m_formFactor = form_factor; // FIXME: force new search Q_EMIT formFactorChanged(); } } void Scope::setActive(const bool active) { if (active != m_isActive) { m_isActive = active; Q_EMIT isActiveChanged(m_isActive); if (active && m_resultsDirty) { dispatchSearch(); } } } void Scope::activate(QVariant const& result_var) { if (!result_var.canConvert>()) { qWarning("Cannot activate, unable to convert %s to Result", result_var.typeName()); return; } std::shared_ptr result = result_var.value>(); if (!result) { qWarning("activate(): received null result"); return; } if (result->direct_activation()) { activateUri(QString::fromStdString(result->uri())); } else { try { auto proxy = result->target_scope_proxy(); // FIXME: don't block unity::scopes::ActionMetadata metadata("C", m_formFactor.toStdString()); //FIXME m_lastActivation.reset(new ActivationReceiver(this, result)); proxy->activate(*(result.get()), metadata, m_lastActivation); } catch (std::exception& e) { qWarning("Caught an error from activate(): %s", e.what()); } catch (...) { qWarning("Caught an error from activate()"); } } } PreviewStack* Scope::preview(QVariant const& result_var) { if (!result_var.canConvert>()) { qWarning("Cannot preview, unable to convert %s to Result", result_var.typeName()); return nullptr; } scopes::Result::SPtr result = result_var.value>(); if (!result) { qWarning("preview(): received null result"); return nullptr; } PreviewStack* stack = new PreviewStack(nullptr); stack->setAssociatedScope(this); stack->loadForResult(result); return stack; } void Scope::cancelActivation() { if (m_lastActivation) { std::dynamic_pointer_cast(m_lastActivation)->invalidate(); m_lastActivation.reset(); } } void Scope::invalidateResults() { if (m_isActive) { dispatchSearch(); } else { // mark the results as dirty, so next setActive() re-sends the query m_resultsDirty = true; } } void Scope::closeScope(scopes_ng::Scope* scope) { if (m_tempScopes.remove(scope)) { delete scope; } } void Scope::activateUri(QString const& uri) { /* Tries various methods to trigger a sensible action for the given 'uri'. If it has no understanding of the given scheme it falls back on asking Qt to open the uri. */ QUrl url(uri); if (url.scheme() == "application") { QString path(url.path().isEmpty() ? url.authority() : url.path()); if (path.startsWith("/")) { Q_FOREACH(const QString &dir, QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation)) { if (path.startsWith(dir)) { path.remove(0, dir.length()); path.replace('/', '-'); break; } } } Q_EMIT activateApplication(QFileInfo(path).completeBaseName()); } else { qDebug() << "Trying to open" << uri; /* Try our luck */ QDesktopServices::openUrl(url); } } } // namespace scopes_ng unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/plugin.cpp0000644000015301777760000000400612320776744023577 0ustar pbusernogroup00000000000000/* * Copyright (C) 2012 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Author: Michał Sawicz */ // Qt #include #include // self #include "plugin.h" // local #include "scopes.h" #include "scope.h" #include "categories.h" #include "resultsmodel.h" #include "previewstack.h" #include "previewmodel.h" #include "previewwidgetmodel.h" void UnityPlugin::registerTypes(const char *uri) { Q_ASSERT(uri == QLatin1String("Unity")); // new Scopes classes qmlRegisterType(uri, 0, 2, "Scope"); qmlRegisterType(uri, 0, 2, "Scopes"); qmlRegisterType(uri, 0, 2, "Categories"); qmlRegisterUncreatableType(uri, 0, 2, "ResultsModel", "Can't create new ResultsModel in QML. Get them from Categories instance."); qmlRegisterUncreatableType(uri, 0, 2, "PreviewModel", "Can't create new PreviewModel in QML. Get them from PreviewStack instance."); qmlRegisterUncreatableType(uri, 0, 2, "PreviewWidgetModel", "Can't create new PreviewWidgetModel in QML. Get them from PreviewModel instance."); qmlRegisterUncreatableType(uri, 0, 2, "PreviewStack", "Can't create new PreviewStack in QML. Get them from Scope instance."); } void UnityPlugin::initializeEngine(QQmlEngine *engine, const char *uri) { QQmlExtensionPlugin::initializeEngine(engine, uri); } unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/collectors.cpp0000644000015301777760000002376512320776744024467 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // Self #include "collectors.h" // local #include "utils.h" // Qt #include #include #include #include #include #include #include namespace scopes_ng { using namespace unity; const QEvent::Type PushEvent::eventType = static_cast(QEvent::registerEventType()); CollectorBase::CollectorBase(): m_status(Status::INCOMPLETE), m_posted(false) { m_timer.start(); } CollectorBase::~CollectorBase() { } /* Returns bool indicating whether the collector should be sent to the UI thread */ bool CollectorBase::submit(Status status) { QMutexLocker locker(&m_mutex); if (m_status == Status::INCOMPLETE) m_status = status; if (m_posted) return false; m_posted = true; return true; } void CollectorBase::invalidate() { QMutexLocker locker(&m_mutex); m_status = Status::CANCELLED; } qint64 CollectorBase::msecsSinceStart() const { return m_timer.elapsed(); } class ResultCollector: public CollectorBase { public: ResultCollector(): CollectorBase() { } // Returns bool indicating whether this resultset was already posted bool addResult(std::shared_ptr const& result) { QMutexLocker locker(&m_mutex); m_results.append(result); return m_posted; } Status collect(QList>& out_results) { Status status; QMutexLocker locker(&m_mutex); if (m_status == Status::INCOMPLETE) { // allow re-posting this collector if !resultset.finished() m_posted = false; } status = m_status; m_results.swap(out_results); return status; } private: QList> m_results; }; class PreviewDataCollector: public CollectorBase { public: PreviewDataCollector(): CollectorBase() { } // Returns bool indicating whether this resultset was already posted bool addWidgets(scopes::PreviewWidgetList const& widgets) { QMutexLocker locker(&m_mutex); m_widgets.insert(m_widgets.end(), widgets.begin(), widgets.end()); return m_posted; } bool addData(std::string const& key, scopes::Variant const& value) { QMutexLocker locker(&m_mutex); m_previewData.insert(QString::fromStdString(key), scopeVariantToQVariant(value)); return m_posted; } bool setColumnLayoutList(scopes::ColumnLayoutList const& columns) { QMutexLocker locker(&m_mutex); m_columnLayouts = columns; return m_posted; } Status collect(scopes::ColumnLayoutList& out_columns, scopes::PreviewWidgetList& out_widgets, QHash& out_data) { Status status; QMutexLocker locker(&m_mutex); if (m_status == Status::INCOMPLETE) { // allow re-posting this collector if !resultset.finished() m_posted = false; } status = m_status; m_columnLayouts.swap(out_columns); m_widgets.swap(out_widgets); m_previewData.swap(out_data); return status; } private: scopes::ColumnLayoutList m_columnLayouts; scopes::PreviewWidgetList m_widgets; QHash m_previewData; }; class ActivationCollector: public CollectorBase { public: ActivationCollector(std::shared_ptr const& result): CollectorBase(), m_result(result) { } // Returns bool indicating whether this resultset was already posted void setResponse(scopes::ActivationResponse const& response) { QMutexLocker locker(&m_mutex); m_response.reset(new scopes::ActivationResponse(response)); } Status collect(std::shared_ptr& out_response, std::shared_ptr& out_result) { Status status; QMutexLocker locker(&m_mutex); if (m_status == Status::INCOMPLETE) { // allow re-posting this collector if !resultset.finished() m_posted = false; } status = m_status; out_response = m_response; out_result = m_result; return status; } private: std::shared_ptr m_response; std::shared_ptr m_result; }; PushEvent::PushEvent(Type event_type, std::shared_ptr collector): QEvent(PushEvent::eventType), m_eventType(event_type), m_collector(collector) { } PushEvent::Type PushEvent::type() { return m_eventType; } qint64 PushEvent::msecsSinceStart() const { return m_collector->msecsSinceStart(); } CollectorBase::Status PushEvent::collectSearchResults(QList>& out_results) { auto collector = std::dynamic_pointer_cast(m_collector); return collector->collect(out_results); } CollectorBase::Status PushEvent::collectPreviewData(scopes::ColumnLayoutList& out_columns, scopes::PreviewWidgetList& out_widgets, QHash& out_data) { auto collector = std::dynamic_pointer_cast(m_collector); return collector->collect(out_columns, out_widgets, out_data); } CollectorBase::Status PushEvent::collectActivationResponse(std::shared_ptr& out_response, std::shared_ptr& out_result) { auto collector = std::dynamic_pointer_cast(m_collector); return collector->collect(out_response, out_result); } ScopeDataReceiverBase::ScopeDataReceiverBase(QObject* receiver, PushEvent::Type push_type, std::shared_ptr const& collector): m_receiver(receiver), m_eventType(push_type), m_collector(collector) { } void ScopeDataReceiverBase::postCollectedResults(CollectorBase::Status status) { if (m_collector->submit(status)) { QScopedPointer pushEvent(new PushEvent(m_eventType, m_collector)); QMutexLocker locker(&m_mutex); // posting the event steals the ownership if (m_receiver == nullptr) return; QCoreApplication::postEvent(m_receiver, pushEvent.take()); } } void ScopeDataReceiverBase::invalidate() { m_collector->invalidate(); QMutexLocker locker(&m_mutex); m_receiver = nullptr; } SearchResultReceiver::SearchResultReceiver(QObject* receiver): ScopeDataReceiverBase(receiver, PushEvent::SEARCH, std::shared_ptr(new ResultCollector)) { m_collector = collectorAs(); } // this will be called from non-main thread, (might even be multiple different threads) void SearchResultReceiver::push(scopes::CategorisedResult result) { auto res = std::make_shared(std::move(result)); bool posted = m_collector->addResult(res); // posting as soon as possible means we minimize delay if (!posted) { postCollectedResults(); } } // this might be called from any thread (might be main, might be any other thread) void SearchResultReceiver::finished(scopes::ListenerBase::Reason reason, std::string const& error_msg) { Q_UNUSED(error_msg); CollectorBase::Status status = reason == scopes::ListenerBase::Reason::Cancelled ? CollectorBase::Status::CANCELLED : CollectorBase::Status::FINISHED; postCollectedResults(status); } PreviewDataReceiver::PreviewDataReceiver(QObject* receiver): ScopeDataReceiverBase(receiver, PushEvent::PREVIEW, std::shared_ptr(new PreviewDataCollector)) { m_collector = collectorAs(); } // this will be called from non-main thread, (might even be multiple different threads) void PreviewDataReceiver::push(unity::scopes::ColumnLayoutList const& layouts) { bool posted = m_collector->setColumnLayoutList(layouts); if (!posted) { postCollectedResults(); } } void PreviewDataReceiver::push(scopes::PreviewWidgetList const& widgets) { bool posted = m_collector->addWidgets(widgets); if (!posted) { postCollectedResults(); } } void PreviewDataReceiver::push(std::string const& key, scopes::Variant const& value) { bool posted = m_collector->addData(key, value); if (!posted) { postCollectedResults(); } } // this might be called from any thread (might be main, might be any other thread) void PreviewDataReceiver::finished(scopes::ListenerBase::Reason reason, std::string const& error_msg) { Q_UNUSED(error_msg); CollectorBase::Status status = reason == scopes::ListenerBase::Reason::Cancelled ? CollectorBase::Status::CANCELLED : CollectorBase::Status::FINISHED; postCollectedResults(status); } void ActivationReceiver::activated(scopes::ActivationResponse const& response) { m_collector->setResponse(response); } void ActivationReceiver::finished(scopes::ListenerBase::Reason reason, std::string const& error_msg) { Q_UNUSED(error_msg); CollectorBase::Status status = reason == scopes::ListenerBase::Reason::Cancelled ? CollectorBase::Status::CANCELLED : CollectorBase::Status::FINISHED; postCollectedResults(status); } ActivationReceiver::ActivationReceiver(QObject* receiver, std::shared_ptr const& result): ScopeDataReceiverBase(receiver, PushEvent::ACTIVATION, std::shared_ptr(new ActivationCollector(result))) { m_collector = collectorAs(); } } // namespace scopes_ng unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/qmldir0000644000015301777760000000006712320776744023013 0ustar pbusernogroup00000000000000module Unity plugin Unity-qml typeinfo plugin.qmltypes unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/categories.h0000644000015301777760000000474312320776744024103 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Canonical, Ltd. * * Authors: * Michał Sawicz * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NG_CATEGORIES_H #define NG_CATEGORIES_H #include #include #include #include #include #include "resultsmodel.h" namespace scopes_ng { struct CategoryData; class Q_DECL_EXPORT Categories : public QAbstractListModel { Q_OBJECT Q_ENUMS(Roles) public: explicit Categories(QObject* parent = 0); enum Roles { RoleCategoryId, RoleName, RoleIcon, RoleRawRendererTemplate, RoleRenderer, RoleComponents, RoleProgressSource, // maybe RoleResults, RoleCount }; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; QHash roleNames() const override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; Q_INVOKABLE bool overrideCategoryJson(QString const& categoryId, QString const& json); Q_INVOKABLE void addSpecialCategory(QString const& categoryId, QString const& name, QString const& icon, QString const& rawTemplate, QObject* countObject); ResultsModel* lookupCategory(std::string const& category_id); void registerCategory(unity::scopes::Category::SCPtr category, ResultsModel* model); void updateResultCount(ResultsModel* resultsModel); void clearAll(); private Q_SLOTS: void countChanged(); private: int getCategoryIndex(QString const& categoryId) const; int getFirstEmptyCategoryIndex() const; QHash m_roles; QList> m_categories; QMap m_categoryResults; QMap m_countObjects; }; } // namespace scopes_ng Q_DECLARE_METATYPE(scopes_ng::Categories*) #endif // NG_CATEGORIES_H unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/CMakeLists.txt0000644000015301777760000000155612320776755024346 0ustar pbusernogroup00000000000000# export_qmlplugin macro include(Plugins) # Dependencies include(FindPkgConfig) pkg_check_modules(SCOPESLIB REQUIRED libunity-scopes>=0.4.0) pkg_check_modules(GSETTINGSQT REQUIRED gsettings-qt) include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${SCOPESLIB_INCLUDE_DIRS} ${GSETTINGSQT_INCLUDE_DIRS} ) set(QMLPLUGIN_SRC categories.cpp collectors.cpp previewmodel.cpp previewstack.cpp previewwidgetmodel.cpp resultsmodel.cpp scope.cpp scopes.cpp utils.cpp plugin.cpp iconutils.cpp ) add_library(Unity-qml SHARED ${QMLPLUGIN_SRC}) target_link_libraries(Unity-qml ${SCOPESLIB_LDFLAGS} ${GSETTINGSQT_LDFLAGS} ) qt5_use_modules(Unity-qml Qml Gui DBus) # export the qmldir qmltypes and plugin files export_qmlfiles(Unity Unity) export_qmlplugin(Unity 0.2 Unity TARGETS Unity-qml) unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/resultsmodel.cpp0000644000015301777760000001720212320776744025025 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // self #include "resultsmodel.h" // local #include "utils.h" #include "iconutils.h" namespace scopes_ng { using namespace unity; const int MAX_ATTRIBUTES = 3; ResultsModel::ResultsModel(QObject* parent) : QAbstractListModel(parent) { m_roles[ResultsModel::RoleUri] = "uri"; m_roles[ResultsModel::RoleCategoryId] = "categoryId"; m_roles[ResultsModel::RoleDndUri] = "dndUri"; m_roles[ResultsModel::RoleResult] = "result"; m_roles[ResultsModel::RoleTitle] = "title"; m_roles[ResultsModel::RoleArt] = "art"; m_roles[ResultsModel::RoleSubtitle] = "subtitle"; m_roles[ResultsModel::RoleMascot] = "mascot"; m_roles[ResultsModel::RoleEmblem] = "emblem"; m_roles[ResultsModel::RoleSummary] = "summary"; m_roles[ResultsModel::RoleAttributes] = "attributes"; m_roles[ResultsModel::RoleBackground] = "background"; } QString ResultsModel::categoryId() const { return m_categoryId; } void ResultsModel::setCategoryId(QString const& id) { if (m_categoryId != id) { m_categoryId = id; Q_EMIT categoryIdChanged(); } } void ResultsModel::setComponentsMapping(QHash const& mapping) { std::unordered_map newMapping; for (auto it = mapping.begin(); it != mapping.end(); ++it) { newMapping[it.key().toStdString()] = it.value().toStdString(); } if (rowCount() > 0) { beginResetModel(); m_componentMapping.swap(newMapping); endResetModel(); } else { m_componentMapping.swap(newMapping); } } void ResultsModel::addResults(QList> const& results) { if (results.count() == 0) return; beginInsertRows(QModelIndex(), m_results.count(), m_results.count() + results.count() - 1); Q_FOREACH(std::shared_ptr const& result, results) { m_results.append(result); } endInsertRows(); Q_EMIT countChanged(); } void ResultsModel::clearResults() { if (m_results.count() == 0) return; beginRemoveRows(QModelIndex(), 0, m_results.count() - 1); m_results.clear(); endRemoveRows(); Q_EMIT countChanged(); } QHash ResultsModel::roleNames() const { return m_roles; } int ResultsModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return m_results.count(); } int ResultsModel::count() const { return m_results.count(); } QVariant ResultsModel::componentValue(scopes::CategorisedResult const* result, std::string const& fieldName) const { auto mappingIt = m_componentMapping.find(fieldName); if (mappingIt == m_componentMapping.end()) { return QVariant(); } std::string const& realFieldName = mappingIt->second; if (!result->contains(realFieldName)) { return QVariant(); } scopes::Variant const& v = result->value(realFieldName); if (v.which() != scopes::Variant::Type::String) { return QVariant(); } return QString::fromStdString(v.get_string()); } QVariant ResultsModel::attributesValue(scopes::CategorisedResult const* result) const { auto mappingIt = m_componentMapping.find("attributes"); if (mappingIt == m_componentMapping.end()) { return QVariant(); } std::string const& realFieldName = mappingIt->second; if (!result->contains(realFieldName)) { return QVariant(); } scopes::Variant const& v = result->value(realFieldName); if (v.which() != scopes::Variant::Type::Array) { return QVariant(); } QVariantList attributes; scopes::VariantArray arr(v.get_array()); for (unsigned i = 0; i < arr.size(); i++) { if (arr[i].which() != scopes::Variant::Type::Dict) { continue; } QVariantMap attribute(scopeVariantToQVariant(arr[i]).toMap()); if (!attribute.contains("value")) { continue; } QVariant valueVar(attribute.value("value")); if (valueVar.type() == QVariant::String && valueVar.toString().trimmed().isEmpty()) { continue; } if (!attribute.contains("style")) { attribute["style"] = QString("default"); } attributes << QVariant(attribute); // we'll limit the number of attributes if (attributes.size() >= MAX_ATTRIBUTES) { break; } } return attributes; } QVariant ResultsModel::get(int row) const { if (row >= m_results.size() || row < 0) return QVariantMap(); QVariantMap result; QModelIndex modelIndex(index(row)); QHashIterator it(roleNames()); while (it.hasNext()) { it.next(); QVariant val(data(modelIndex, it.key())); if (val.isNull()) continue; result[it.value()] = val; } return result; } QVariant ResultsModel::data(const QModelIndex& index, int role) const { scopes::CategorisedResult* result = m_results.at(index.row()).get(); switch (role) { case RoleUri: return QString::fromStdString(result->uri()); case RoleCategoryId: return QString::fromStdString(result->category()->id()); case RoleDndUri: return QString::fromStdString(result->dnd_uri()); case RoleResult: return QVariant::fromValue(std::static_pointer_cast(m_results.at(index.row()))); case RoleTitle: return componentValue(result, "title"); case RoleArt: { QString image(componentValue(result, "art").toString()); if (image.isEmpty()) { QString uri(QString::fromStdString(result->uri())); // FIXME: figure out a better way and get rid of this, it's an awful hack QVariantHash result_meta; if (result->contains("artist") && result->contains("album")) { result_meta["artist"] = scopeVariantToQVariant(result->value("artist")); result_meta["album"] = scopeVariantToQVariant(result->value("album")); } QString thumbnailerUri(uriToThumbnailerProviderString(uri, result_meta)); if (!thumbnailerUri.isNull()) { return thumbnailerUri; } } return image; } case RoleSubtitle: return componentValue(result, "subtitle"); case RoleMascot: return componentValue(result, "mascot"); case RoleEmblem: return componentValue(result, "emblem"); case RoleAttributes: return attributesValue(result); case RoleSummary: return componentValue(result, "summary"); case RoleBackground: { QVariant backgroundVariant(componentValue(result, "background")); if (backgroundVariant.isNull()) { return backgroundVariant; } return backgroundUriToVariant(backgroundVariant.toString()); } default: return QVariant(); } } } // namespace scopes_ng unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/collectors.h0000644000015301777760000001057112320776744024123 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NG_COLLECTORS_H #define NG_COLLECTORS_H // Qt #include #include #include #include #include #include #include #include #include #include #include namespace scopes_ng { class ResultCollector; class PreviewDataCollector; class ActivationCollector; class CollectorBase { public: enum Status { INCOMPLETE, FINISHED, CANCELLED }; CollectorBase(); virtual ~CollectorBase(); bool submit(Status status = Status::INCOMPLETE); void invalidate(); qint64 msecsSinceStart() const; protected: QMutex m_mutex; Status m_status; bool m_posted; private: // not locked QElapsedTimer m_timer; }; class PushEvent: public QEvent { public: static const QEvent::Type eventType; enum Type { SEARCH, PREVIEW, ACTIVATION }; PushEvent(Type event_type, std::shared_ptr collector); Type type(); CollectorBase::Status collectSearchResults(QList>& out_results); CollectorBase::Status collectPreviewData(unity::scopes::ColumnLayoutList& out_columns, unity::scopes::PreviewWidgetList& out_widgets, QHash& out_data); CollectorBase::Status collectActivationResponse(std::shared_ptr& out_response, std::shared_ptr& out_result); qint64 msecsSinceStart() const; private: Type m_eventType; std::shared_ptr m_collector; }; class ScopeDataReceiverBase { public: ScopeDataReceiverBase(QObject* receiver, PushEvent::Type push_type, std::shared_ptr const& collector); void invalidate(); template std::shared_ptr collectorAs() { return std::dynamic_pointer_cast(m_collector); } protected: void postCollectedResults(CollectorBase::Status status = CollectorBase::Status::INCOMPLETE); private: QMutex m_mutex; QObject* m_receiver; PushEvent::Type m_eventType; std::shared_ptr m_collector; }; class SearchResultReceiver: public unity::scopes::SearchListenerBase, public ScopeDataReceiverBase { public: virtual void push(unity::scopes::CategorisedResult result) override; virtual void finished(unity::scopes::ListenerBase::Reason reason, std::string const& error_msg) override; SearchResultReceiver(QObject* receiver); private: std::shared_ptr m_collector; }; class PreviewDataReceiver: public unity::scopes::PreviewListenerBase, public ScopeDataReceiverBase { public: virtual void push(unity::scopes::ColumnLayoutList const& layouts) override; virtual void push(unity::scopes::PreviewWidgetList const& widgets) override; virtual void push(std::string const& key, unity::scopes::Variant const& value) override; virtual void finished(unity::scopes::ListenerBase::Reason reason, std::string const& error_msg) override; PreviewDataReceiver(QObject* receiver); private: std::shared_ptr m_collector; }; class ActivationReceiver: public unity::scopes::ActivationListenerBase, public ScopeDataReceiverBase { public: virtual void activated(unity::scopes::ActivationResponse const&) override; virtual void finished(unity::scopes::ListenerBase::Reason reason, std::string const& error_msg) override; ActivationReceiver(QObject* receiver, std::shared_ptr const& result); private: std::shared_ptr m_collector; }; } // namespace scopes_ng #endif // NG_COLLECTORS_H unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/previewstack.cpp0000644000015301777760000001702112320776744025011 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical, Ltd. * * Authors: * Michał Sawicz * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // self #include "previewstack.h" // local #include "previewmodel.h" #include "scope.h" #include "utils.h" // Qt #include #include #include #include #include namespace scopes_ng { using namespace unity; PreviewStack::PreviewStack(QObject* parent) : QAbstractListModel(parent), m_widgetColumnCount(1) { } PreviewStack::~PreviewStack() { for (auto it = m_listeners.begin(); it != m_listeners.end(); ++it) { auto listener = it.value().lock(); if (listener) listener->invalidate(); } if (m_lastActivation) { m_lastActivation->invalidate(); } } QHash PreviewStack::roleNames() const { QHash roles; roles[Roles::RolePreviewModel] = "previewModel"; return roles; } bool PreviewStack::event(QEvent* ev) { if (ev->type() == PushEvent::eventType) { PushEvent* pushEvent = static_cast(ev); switch (pushEvent->type()) { case PushEvent::ACTIVATION: processActionResponse(pushEvent); return true; default: qWarning("PreviewStack: Unhandled PushEvent type"); break; } } return false; } void PreviewStack::setAssociatedScope(scopes_ng::Scope* scope) { m_associatedScope = scope; } void PreviewStack::loadForResult(scopes::Result::SPtr const& result) { m_previewedResult = result; beginResetModel(); // invalidate all listeners for (auto it = m_listeners.begin(); it != m_listeners.end(); ++it) { auto listener = it.value().lock(); if (listener) listener->invalidate(); } // clear any previews while (!m_previews.empty()) { delete m_previews.takeFirst(); } // create active preview m_activePreview = new PreviewModel(this); m_activePreview->setResult(m_previewedResult); connect(m_activePreview, &PreviewModel::triggered, this, &PreviewStack::widgetTriggered); m_previews.append(m_activePreview); endResetModel(); dispatchPreview(); } void PreviewStack::dispatchPreview(scopes::Variant const& extra_data) { // TODO: figure out if the result can produce a preview without sending a request to the scope // if (m_previewedResult->has_early_preview()) { ... } try { auto proxy = m_previewedResult->target_scope_proxy(); scopes::ActionMetadata metadata("C", "phone"); //FIXME if (!extra_data.is_null()) { metadata.set_scope_data(extra_data); } std::shared_ptr listener(new PreviewDataReceiver(m_activePreview)); std::weak_ptr wl(listener); // invalidate previous listener (if any) auto prev_listener = m_listeners.take(m_activePreview).lock(); if (prev_listener) prev_listener->invalidate(); m_listeners[m_activePreview] = wl; // FIXME: don't block m_lastPreviewQuery = proxy->preview(*(m_previewedResult.get()), metadata, listener); } catch (std::exception& e) { qWarning("Caught an error from preview(): %s", e.what()); } catch (...) { qWarning("Caught an error from preview()"); } } void PreviewStack::widgetTriggered(QString const& widgetId, QString const& actionId, QVariantMap const& data) { PreviewModel* previewModel = qobject_cast(sender()); if (previewModel != nullptr) { PreviewWidgetData* widgetData = previewModel->getWidgetData(widgetId); if (widgetData != nullptr) { if (widgetData->type == QLatin1String("actions") && data.contains("uri")) { if (m_associatedScope) { m_associatedScope->activateUri(data.value("uri").toString()); return; } } } else { qWarning("Action triggered for unknown widget \"%s\"", widgetId.toStdString().c_str()); } } try { auto proxy = m_previewedResult->target_scope_proxy(); scopes::ActionMetadata metadata("C", "phone"); //FIXME metadata.set_scope_data(qVariantToScopeVariant(data)); if (m_lastActivation) { m_lastActivation->invalidate(); } std::shared_ptr listener(new ActivationReceiver(this, m_previewedResult)); m_lastActivation = listener; // should be always coming from active preview if (m_activePreview) { m_activePreview->setProcessingAction(true); } // FIXME: don't block proxy->perform_action(*(m_previewedResult.get()), metadata, widgetId.toStdString(), actionId.toStdString(), listener); } catch (std::exception& e) { qWarning("Caught an error from perform_action(%s, %s): %s", widgetId.toStdString().c_str(), actionId.toStdString().c_str(), e.what()); } catch (...) { qWarning("Caught an error from perform_action()"); } } void PreviewStack::processActionResponse(PushEvent* pushEvent) { std::shared_ptr response; scopes::Result::SPtr result; pushEvent->collectActivationResponse(response, result); if (!response) return; switch (response->status()) { case scopes::ActivationResponse::ShowPreview: // replace current preview m_activePreview->setDelayedClear(); // the preview is marked as processing action, leave the flag on until the preview is updated dispatchPreview(scopes::Variant(response->scope_data())); break; // TODO: case to nest preview (once such API is available) default: if (m_associatedScope) { m_associatedScope->handleActivation(response, result); } if (m_activePreview) { m_activePreview->setProcessingAction(false); } break; } } void PreviewStack::setWidgetColumnCount(int columnCount) { if (m_widgetColumnCount != columnCount) { m_widgetColumnCount = columnCount; // set on all previews for (int i = 0; i < m_previews.size(); i++) { m_previews[i]->setWidgetColumnCount(columnCount); } Q_EMIT widgetColumnCountChanged(); } } int PreviewStack::widgetColumnCount() const { return m_widgetColumnCount; } int PreviewStack::rowCount(const QModelIndex&) const { return m_previews.size(); } PreviewModel* PreviewStack::get(int index) const { if (index >= m_previews.size()) { return nullptr; } return m_previews.at(index); } QVariant PreviewStack::data(const QModelIndex& index, int role) const { switch (role) { case RolePreviewModel: return QVariant::fromValue(m_previews.at(index.row())); default: return QVariant(); } } } // namespace scopes_ng unity-scopes-shell-0.4.0+14.04.20140408/src/Unity/resultsmodel.h0000644000015301777760000000517612320776744024501 0ustar pbusernogroup00000000000000/* * Copyright (C) 2013 Canonical, Ltd. * * Authors: * Michal Hruby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NG_CATEGORY_RESULTS_H #define NG_CATEGORY_RESULTS_H #include #include #include #include namespace scopes_ng { class Q_DECL_EXPORT ResultsModel : public QAbstractListModel { Q_OBJECT Q_ENUMS(Roles) Q_PROPERTY(QString categoryId READ categoryId WRITE setCategoryId NOTIFY categoryIdChanged) Q_PROPERTY(int count READ count NOTIFY countChanged) public: explicit ResultsModel(QObject* parent = 0); enum Roles { RoleUri, RoleCategoryId, RoleDndUri, RoleResult, // card components RoleTitle, RoleArt, RoleSubtitle, RoleMascot, RoleEmblem, RoleSummary, RoleAttributes, RoleBackground }; int rowCount(const QModelIndex& parent = QModelIndex()) const override; QHash roleNames() const override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; Q_INVOKABLE QVariant get(int row) const; void addResults(QList> const&); void clearResults(); /* getters */ QString categoryId() const; int count() const; /* setters */ void setCategoryId(QString const& id); void setComponentsMapping(QHash const& mapping); Q_SIGNALS: void categoryIdChanged(); void countChanged(); private: QVariant componentValue(unity::scopes::CategorisedResult const* result, std::string const& fieldName) const; QVariant attributesValue(unity::scopes::CategorisedResult const* result) const; QHash m_roles; std::unordered_map m_componentMapping; QList> m_results; QString m_categoryId; }; } // namespace scopes_ng Q_DECLARE_METATYPE(std::shared_ptr) #endif // NG_CATEGORY_RESULTS_H unity-scopes-shell-0.4.0+14.04.20140408/src/CMakeLists.txt0000644000015301777760000000003112320776744023217 0ustar pbusernogroup00000000000000add_subdirectory(Unity)