From: Aurélien COUDERC Date: Sat, 15 Feb 2025 16:23:11 +0000 (+0100) Subject: Import kf6-krunner_6.11.0.orig.tar.xz X-Git-Tag: archive/raspbian/6.11.0-1+rpi1^2~2 X-Git-Url: https://dgit.raspbian.org/?a=commitdiff_plain;h=75c31f4600834211eae904a7b281d1872d1a7b9b;p=kf6-krunner.git Import kf6-krunner_6.11.0.orig.tar.xz [dgit import orig kf6-krunner_6.11.0.orig.tar.xz] --- 75c31f4600834211eae904a7b281d1872d1a7b9b diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..090937e --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: none +# SPDX-License-Identifier: CC0-1.0 + +# clang-format +4c453cecbed22d9947c3ec58fb2d5eaff8bc6a8d diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c6227a3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: none +# SPDX-License-Identifier: CC0-1.0 + +# Ignore the following files +*~ +*.[oa] +*.diff +*.kate-swp +*.kdev4 +.kdev_include_paths +*.kdevelop.pcs +*.moc +*.moc.cpp +*.orig +*.user +.*.swp +.swp.* +Doxyfile +Makefile +avail +random_seed +/build*/ +CMakeLists.txt.user* +*.unc-backup* +.cmake/ +.clang-format +cmake-build-debug* +.idea +.vscode +/compile_commands.json +.clangd +.cache diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..e2f6d75 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2020 Volker Krause +# SPDX-License-Identifier: CC0-1.0 + +include: + - project: sysadmin/ci-utilities + file: + - /gitlab-templates/linux-qt6.yml + - /gitlab-templates/linux-qt6-next.yml + - /gitlab-templates/reuse-lint.yml + - /gitlab-templates/freebsd-qt6.yml + - /gitlab-templates/xml-lint.yml + - /gitlab-templates/yaml-lint.yml diff --git a/.kde-ci.yml b/.kde-ci.yml new file mode 100644 index 0000000..6b9f326 --- /dev/null +++ b/.kde-ci.yml @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: none +# SPDX-License-Identifier: CC0-1.0 + +Dependencies: + - 'on': ['Linux', 'FreeBSD', 'Windows', 'macOS'] + 'require': + 'frameworks/extra-cmake-modules': '@same' + 'frameworks/kconfig': '@same' + 'frameworks/kcoreaddons': '@same' + 'frameworks/threadweaver': '@same' + 'frameworks/ki18n': '@same' + 'frameworks/kitemmodels': '@same' + +Options: + test-before-installing: True + require-passing-tests-on: ['Linux', 'FreeBSD'] + cppcheck-ignore-files: ['templates/'] diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..60fad76 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,106 @@ +# SPDX-FileCopyrightText: KDE Contributors +# SPDX-License-Identifier: BSD-2-Clause + +cmake_minimum_required(VERSION 3.16) + +set(KF_VERSION "6.11.0") # handled by release scripts +set(KF_DEP_VERSION "6.11.0") # handled by release scripts +project(KRunner VERSION ${KF_VERSION}) + +# ECM setup +include(FeatureSummary) +find_package(ECM 6.11.0 NO_MODULE) +set_package_properties(ECM PROPERTIES TYPE REQUIRED DESCRIPTION "Extra CMake Modules." URL "https://commits.kde.org/extra-cmake-modules") +feature_summary(WHAT REQUIRED_PACKAGES_NOT_FOUND FATAL_ON_MISSING_REQUIRED_PACKAGES) + +set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH}) + +include(KDEInstallDirs) +include(KDECMakeSettings) +include(KDEFrameworkCompilerSettings NO_POLICY_SCOPE) + +include(ECMGenerateExportHeader) +include(ECMSetupVersion) +include(ECMGenerateHeaders) +include(ECMAddQch) +include(CMakePackageConfigHelpers) +include(KDEPackageAppTemplates) +include(ECMQtDeclareLoggingCategory) +include(ECMSetupQtPluginMacroNames) +include(ECMDeprecationSettings) +include(KDEGitCommitHooks) + +set(EXCLUDE_DEPRECATED_BEFORE_AND_AT 0 CACHE STRING "Control the range of deprecated API excluded from the build [default=0].") + +option(BUILD_QCH "Build API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)" OFF) +add_feature_info(QCH ${BUILD_QCH} "API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)") + +set(krunner_version_header "${CMAKE_CURRENT_BINARY_DIR}/src/krunner_version.h") +ecm_setup_version(PROJECT + VARIABLE_PREFIX KRUNNER + VERSION_HEADER "${krunner_version_header}" + PACKAGE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/KF6RunnerConfigVersion.cmake" + SOVERSION 6 +) + +# Dependencies +set(REQUIRED_QT_VERSION 6.6.0) + +find_package(Qt6 ${REQUIRED_QT_VERSION} NO_MODULE REQUIRED Gui) + +ecm_set_disabled_deprecation_versions( + QT 6.8.0 + KF 6.10.0 +) + +find_package(KF6Config ${KF_DEP_VERSION} REQUIRED) +find_package(KF6CoreAddons ${KF_DEP_VERSION} REQUIRED) +find_package(KF6I18n ${KF_DEP_VERSION} REQUIRED) +find_package(KF6ItemModels ${KF_DEP_VERSION}) + +# Subdirectories +add_subdirectory(src) +if (BUILD_TESTING) + add_subdirectory(autotests) +endif() +add_subdirectory(templates) + +# Create a Config.cmake and a ConfigVersion.cmake file and install them +set(CMAKECONFIG_INSTALL_DIR "${KDE_INSTALL_CMAKEPACKAGEDIR}/KF6Runner") + +if (BUILD_QCH) + ecm_install_qch_export( + TARGETS KF6Runner_QCH + FILE KF6RunnerQchTargets.cmake + DESTINATION "${CMAKECONFIG_INSTALL_DIR}" + COMPONENT Devel + ) + set(PACKAGE_INCLUDE_QCHTARGETS "include(\"\${CMAKE_CURRENT_LIST_DIR}/KF6RunnerQchTargets.cmake\")") +endif() + +configure_package_config_file( + "${CMAKE_CURRENT_SOURCE_DIR}/KF6RunnerConfig.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/KF6RunnerConfig.cmake" + INSTALL_DESTINATION "${CMAKECONFIG_INSTALL_DIR}" +) + +install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/KF6RunnerConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/KF6RunnerConfigVersion.cmake" + "${CMAKE_CURRENT_SOURCE_DIR}/KF6KRunnerMacros.cmake" + DESTINATION "${CMAKECONFIG_INSTALL_DIR}" + COMPONENT Devel) + +install(EXPORT KF6RunnerTargets + DESTINATION "${CMAKECONFIG_INSTALL_DIR}" + FILE KF6RunnerTargets.cmake + NAMESPACE KF6::) + +install(FILES "${krunner_version_header}" + DESTINATION "${KDE_INSTALL_INCLUDEDIR_KF}/KRunner" + COMPONENT Devel) + +include(ECMFeatureSummary) +ecm_feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) + +kde_configure_git_pre_commit_hook(CHECKS CLANG_FORMAT) diff --git a/ExtraDesktop.sh b/ExtraDesktop.sh new file mode 100644 index 0000000..c0b49e2 --- /dev/null +++ b/ExtraDesktop.sh @@ -0,0 +1,8 @@ +#! /bin/sh + +# SPDX-FileCopyrightText: none +# SPDX-License-Identifier: CC0-1.0 + +#This file outputs in a separate line each file with a .desktop syntax +#that needs to be translated but has a non .desktop extension +find -name \*.kdevtemplate -print diff --git a/KF6KRunnerMacros.cmake b/KF6KRunnerMacros.cmake new file mode 100644 index 0000000..2fd796f --- /dev/null +++ b/KF6KRunnerMacros.cmake @@ -0,0 +1,38 @@ +#.rst: +# KF6KRunnerMacros +# --------------------------- +# +# This module provides the ``krunner_configure_test`` function which takes the test- and runner target as a parameter. +# This will add the compile definitions for the AbstractRunnerTest header. +# In case of DBus runners the DESKTOP_FILE parameter must be set. This is required for loading the runner from the +# metadata file. +# SPDX-FileCopyrightText: 2020 Alexander Lohnau +# SPDX-License-Identifier: BSD-2-Clause + +function(krunner_configure_test TEST_TARGET RUNNER_TARGET) + include(CMakeParseArguments) + set(options) + set(oneValueArgs DESKTOP_FILE) + set(multiValueArgs) + cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + get_target_property(target_type ${RUNNER_TARGET} TYPE) + if(target_type STREQUAL "EXECUTABLE") + if(NOT ARGS_DESKTOP_FILE) + message(FATAL_ERROR "In case of a dbus runner the DESKTOP_FILE must be provided") + endif() + target_compile_definitions(${TEST_TARGET} + PRIVATE + KRUNNER_DBUS_RUNNER_TESTING=1 + KRUNNER_TEST_DBUS_EXECUTABLE="$" + KRUNNER_TEST_DESKTOP_FILE="${ARGS_DESKTOP_FILE}" + ) + else() + target_compile_definitions(${TEST_TARGET} + PRIVATE + KRUNNER_DBUS_RUNNER_TESTING=0 + KRUNNER_TEST_RUNNER_PLUGIN_DIR="$" + KRUNNER_TEST_RUNNER_PLUGIN_NAME="$" + ) + endif() + add_dependencies(${TEST_TARGET} ${RUNNER_TARGET}) +endfunction() diff --git a/KF6RunnerConfig.cmake.in b/KF6RunnerConfig.cmake.in new file mode 100644 index 0000000..83aa915 --- /dev/null +++ b/KF6RunnerConfig.cmake.in @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: Friedrich W. H. Kossebau +# SPDX-FileCopyrightText: Aleix Pol +# SPDX-License-Identifier: BSD-2-Clause + +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) +find_dependency(Qt6 @REQUIRED_QT_VERSION@ CONFIG REQUIRED Core) +find_dependency(KF6CoreAddons "@KF_DEP_VERSION@") # KPluginFactory + +@PACKAGE_SETUP_AUTOMOC_VARIABLES@ + +include("${CMAKE_CURRENT_LIST_DIR}/KF6RunnerTargets.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/KF6KRunnerMacros.cmake") +@PACKAGE_INCLUDE_QCHTARGETS@ diff --git a/LICENSES/BSD-2-Clause.txt b/LICENSES/BSD-2-Clause.txt new file mode 100644 index 0000000..b0e20f5 --- /dev/null +++ b/LICENSES/BSD-2-Clause.txt @@ -0,0 +1,9 @@ +Copyright (c) All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/LGPL-2.0-or-later.txt b/LICENSES/LGPL-2.0-or-later.txt new file mode 100644 index 0000000..5c96471 --- /dev/null +++ b/LICENSES/LGPL-2.0-or-later.txt @@ -0,0 +1,446 @@ +GNU LIBRARY GENERAL PUBLIC LICENSE + +Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. + +51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +[This is the first released version of the library GPL. It is numbered 2 because +it goes with version 2 of the ordinary GPL.] + +Preamble + +The licenses for most software are designed to take away your freedom to share +and change it. By contrast, the GNU General Public Licenses are intended to +guarantee your freedom to share and change free software--to make sure the +software is free for all its users. + +This license, the Library General Public License, applies to some specially +designated Free Software Foundation software, and to any other libraries whose +authors decide to use it. You can use it for your libraries, 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 this service 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 make restrictions that forbid anyone to +deny you these rights or to ask you to surrender the rights. These restrictions +translate to certain responsibilities for you if you distribute copies of +the library, or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for +a fee, you must give the recipients all the rights that we gave you. You must +make sure that they, too, receive or can get the source code. If you link +a program with the library, you must provide complete object files to the +recipients so that they can relink them with the library, after making changes +to the library and recompiling it. And you must show them these terms so they +know their rights. + +Our method of protecting your rights has two steps: (1) copyright the library, +and (2) offer you this license which gives you legal permission to copy, distribute +and/or modify the library. + +Also, for each distributor's protection, we want to make certain that everyone +understands that there is no warranty for this free library. If the library +is modified by someone else and passed on, we want its recipients to know +that what they have is not the original version, so that any problems introduced +by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We +wish to avoid the danger that companies distributing free software will individually +obtain patent licenses, thus in effect transforming the program into proprietary +software. To prevent this, we have made it clear that any patent must be licensed +for everyone's free use or not licensed at all. + +Most GNU software, including some libraries, is covered by the ordinary GNU +General Public License, which was designed for utility programs. This license, +the GNU Library General Public License, applies to certain designated libraries. +This license is quite different from the ordinary one; be sure to read it +in full, and don't assume that anything in it is the same as in the ordinary +license. + +The reason we have a separate public license for some libraries is that they +blur the distinction we usually make between modifying or adding to a program +and simply using it. Linking a program with a library, without changing the +library, is in some sense simply using the library, and is analogous to running +a utility program or application program. However, in a textual and legal +sense, the linked executable is a combined work, a derivative of the original +library, and the ordinary General Public License treats it as such. + +Because of this blurred distinction, using the ordinary General Public License +for libraries did not effectively promote software sharing, because most developers +did not use the libraries. We concluded that weaker conditions might promote +sharing better. + +However, unrestricted linking of non-free programs would deprive the users +of those programs of all benefit from the free status of the libraries themselves. +This Library General Public License is intended to permit developers of non-free +programs to use free libraries, while preserving your freedom as a user of +such programs to change the free libraries that are incorporated in them. +(We have not seen how to achieve this as regards changes in header files, +but we have achieved it as regards changes in the actual functions of the +Library.) The hope is that this will lead to faster development of free libraries. + +The precise terms and conditions for copying, distribution and modification +follow. Pay close attention to the difference between a "work based on the +library" and a "work that uses the library". The former contains code derived +from the library, while the latter only works together with the library. + +Note that it is possible for a library to be covered by the ordinary General +Public License rather than by this special one. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library which contains a +notice placed by the copyright holder or other authorized party saying it +may be distributed under the terms of this Library General Public License +(also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared +so as to be conveniently linked with application programs (which use some +of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has +been distributed under these terms. A "work based on the Library" means either +the Library or any derivative work under copyright law: that is to say, a +work containing the Library or a portion of it, either verbatim or with modifications +and/or translated straightforwardly into another language. (Hereinafter, translation +is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications +to it. For a library, complete source code means all the source code for all +modules it contains, plus any associated interface definition files, plus +the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered +by this License; they are outside its scope. The act of running a program +using the Library is not restricted, and output from such a program is covered +only if its contents constitute a work based on the Library (independent of +the use of the Library in a tool for writing it). Whether that is true depends +on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source +code as you receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice and disclaimer +of warranty; keep intact all the notices that refer to this License and to +the absence of any warranty; and distribute a copy of this License along with +the Library. + +You may charge a fee for the physical act of transferring a copy, and you +may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, +thus forming a work based on the Library, and copy and distribute such modifications +or work under the terms of Section 1 above, provided that you also meet all +of these conditions: + + a) The modified work must itself be a software library. + +b) You must cause the files modified to carry prominent notices stating that +you changed the files and the date of any change. + +c) You must cause the whole of the work to be licensed at no charge to all +third parties under the terms of this License. + +d) If a facility in the modified Library refers to a function or a table of +data to be supplied by an application program that uses the facility, other +than as an argument passed when the facility is invoked, then you must make +a good faith effort to ensure that, in the event an application does not supply +such function or table, the facility still operates, and performs whatever +part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose +that is entirely well-defined independent of the application. Therefore, Subsection +2d requires that any application-supplied function or table used by this function +must be optional: if the application does not supply it, the square root function +must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable +sections of that work are not derived from the Library, and can be reasonably +considered independent and separate works in themselves, then this License, +and its terms, do not apply to those sections when you distribute them as +separate works. But when you distribute the same sections as part of a whole +which is a work based on the Library, the distribution of the whole must be +on the terms of this License, whose permissions for other licensees extend +to the entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest your +rights to work written entirely by you; rather, the intent is to exercise +the right to control the distribution of derivative or collective works based +on the Library. + +In addition, mere aggregation of another work not based on the Library with +the Library (or with a work based on the Library) on a volume of a storage +or distribution medium does not bring the other work under the scope of this +License. + +3. You may opt to apply the terms of the ordinary GNU General Public License +instead of this License to a given copy of the Library. To do this, you must +alter all the notices that refer to this License, so that they refer to the +ordinary GNU General Public License, version 2, instead of to this License. +(If a newer version than version 2 of the ordinary GNU General Public License +has appeared, then you can specify that version instead if you wish.) Do not +make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, +so the ordinary GNU General Public License applies to all subsequent copies +and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library +into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of +it, under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you accompany it with the complete corresponding +machine-readable source code, which must be distributed under the terms of +Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated +place, then offering equivalent access to copy the source code from the same +place satisfies the requirement to distribute the source code, even though +third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but +is designed to work with the Library by being compiled or linked with it, +is called a "work that uses the Library". Such a work, in isolation, is not +a derivative work of the Library, and therefore falls outside the scope of +this License. + +However, linking a "work that uses the Library" with the Library creates an +executable that is a derivative of the Library (because it contains portions +of the Library), rather than a "work that uses the library". The executable +is therefore covered by this License. Section 6 states terms for distribution +of such executables. + +When a "work that uses the Library" uses material from a header file that +is part of the Library, the object code for the work may be a derivative work +of the Library even though the source code is not. Whether this is true is +especially significant if the work can be linked without the Library, or if +the work is itself a library. The threshold for this to be true is not precisely +defined by law. + +If such an object file uses only numerical parameters, data structure layouts +and accessors, and small macros and small inline functions (ten lines or less +in length), then the use of the object file is unrestricted, regardless of +whether it is legally a derivative work. (Executables containing this object +code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute +the object code for the work under the terms of Section 6. Any executables +containing that work also fall under Section 6, whether or not they are linked +directly with the Library itself. + +6. As an exception to the Sections above, you may also compile or link a "work +that uses the Library" with the Library to produce a work containing portions +of the Library, and distribute that work under terms of your choice, provided +that the terms permit modification of the work for the customer's own use +and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library +is used in it and that the Library and its use are covered by this License. +You must supply a copy of this License. If the work during execution displays +copyright notices, you must include the copyright notice for the Library among +them, as well as a reference directing the user to the copy of this License. +Also, you must do one of these things: + +a) Accompany the work with the complete corresponding machine-readable source +code for the Library including whatever changes were used in the work (which +must be distributed under Sections 1 and 2 above); and, if the work is an +executable linked with the Library, with the complete machine-readable "work +that uses the Library", as object code and/or source code, so that the user +can modify the Library and then relink to produce a modified executable containing +the modified Library. (It is understood that the user who changes the contents +of definitions files in the Library will not necessarily be able to recompile +the application to use the modified definitions.) + +b) Accompany the work with a written offer, valid for at least three years, +to give the same user the materials specified in Subsection 6a, above, for +a charge no more than the cost of performing this distribution. + +c) If distribution of the work is made by offering access to copy from a designated +place, offer equivalent access to copy the above specified materials from +the same place. + +d) Verify that the user has already received a copy of these materials or +that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must +include any data and utility programs needed for reproducing the executable +from it. However, as a special exception, the source code distributed need +not include anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the operating +system on which the executable runs, unless that component itself accompanies +the executable. + +It may happen that this requirement contradicts the license restrictions of +other proprietary libraries that do not normally accompany the operating system. +Such a contradiction means you cannot use both them and the Library together +in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side +in a single library together with other library facilities not covered by +this License, and distribute such a combined library, provided that the separate +distribution of the work based on the Library and of the other library facilities +is otherwise permitted, and provided that you do these two things: + +a) Accompany the combined library with a copy of the same work based on the +Library, uncombined with any other library facilities. This must be distributed +under the terms of the Sections above. + +b) Give prominent notice with the combined library of the fact that part of +it is a work based on the Library, and explaining where to find the accompanying +uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library +except as expressly provided under this License. Any attempt otherwise to +copy, modify, sublicense, link with, or distribute the Library is void, and +will automatically terminate your rights under this License. However, parties +who have received copies, or rights, from you under this License will not +have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed +it. However, nothing else grants you permission to modify or distribute the +Library or its derivative works. These actions are prohibited by law if you +do not accept this License. Therefore, by modifying or distributing the Library +(or any work based on the Library), you indicate your acceptance of this License +to do so, and all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), +the recipient automatically receives a license from the original licensor +to copy, distribute, link with or modify the Library subject to these terms +and conditions. You may not impose any further restrictions on the recipients' +exercise of the rights granted herein. You are not responsible for enforcing +compliance by third parties to this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement +or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your +obligations under this License and any other pertinent obligations, then as +a consequence you may not distribute the Library at all. For example, if a +patent license would not permit royalty-free redistribution of the Library +by all those who receive copies directly or indirectly through you, then the +only way you could satisfy both it and this License would be to refrain entirely +from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents +or other property right claims or to contest validity of any such claims; +this section has the sole purpose of protecting the integrity of the free +software distribution system which is implemented by public license practices. +Many people have made generous contributions to the wide range of software +distributed through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing to +distribute software through any other system and a licensee cannot impose +that choice. + +This section is intended to make thoroughly clear what is believed to be a +consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain +countries either by patents or by copyrighted interfaces, the original copyright +holder who places the Library under this License may add an explicit geographical +distribution limitation excluding those countries, so that distribution is +permitted only in or among countries not thus excluded. In such case, this +License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of +the Library 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 Library specifies +a version number of this License which applies to it and "any later version", +you have the option of following the terms and conditions either of that version +or of any later version published by the Free Software Foundation. If the +Library does not specify a license version number, you may choose any version +ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs +whose distribution conditions are incompatible with these, write to the author +to ask for permission. For software which is copyrighted by the Free Software +Foundation, write to the Free Software Foundation; we sometimes make exceptions +for this. Our decision will be guided by the two goals of preserving the free +status of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR +THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE +STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY +"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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE +THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH +HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible +use to the public, we recommend making it free software that everyone can +redistribute and change. You can do so by permitting redistribution under +these terms (or, alternatively, under the terms of the ordinary General Public +License). + +To apply these terms, attach the following notices to the library. It is safest +to attach them to the start of each source file to most effectively convey +the exclusion of warranty; and each file should have at least the "copyright" +line and a pointer to where the full notice is found. + +one line to give the library's name and an idea of what it does. + +Copyright (C) year name of author + +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Library General Public License as published by the Free +Software Foundation; either version 2 of the License, or (at your option) +any later version. + +This library is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more +details. + +You should have received a copy of the GNU Library General Public License +along with this library; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, +if any, to sign a "copyright disclaimer" for the library, if necessary. Here +is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in + +the library `Frob' (a library for tweaking knobs) written + +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 + +Ty Coon, President of Vice + +That's all there is to it! diff --git a/LICENSES/LGPL-2.1-only.txt b/LICENSES/LGPL-2.1-only.txt new file mode 100644 index 0000000..c9aa530 --- /dev/null +++ b/LICENSES/LGPL-2.1-only.txt @@ -0,0 +1,175 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/LICENSES/LGPL-2.1-or-later.txt b/LICENSES/LGPL-2.1-or-later.txt new file mode 100644 index 0000000..04bb156 --- /dev/null +++ b/LICENSES/LGPL-2.1-or-later.txt @@ -0,0 +1,468 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. + +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the +successor of the GNU Library Public License, version 2, hence the version +number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share +and change it. By contrast, the GNU General Public Licenses are intended to +guarantee your freedom to share and change free software--to make sure the +software is free for all its users. + +This license, the Lesser General Public License, applies to some specially +designated software packages--typically libraries--of the Free Software Foundation +and other authors who decide to use it. You can use it too, but we suggest +you first think carefully about whether this license or the ordinary General +Public License is the better strategy to use in any particular case, based +on the explanations below. + +When we speak of free software, we are referring to freedom of use, 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 this service if you +wish); that you receive source code or can get it if you want it; that you +can change the software and use pieces of it in new free programs; and that +you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors +to deny you these rights or to ask you to surrender these rights. These restrictions +translate to certain responsibilities for you if you distribute copies of +the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for +a fee, you must give the recipients all the rights that we gave you. You must +make sure that they, too, receive or can get the source code. If you link +other code with the library, you must provide complete object files to the +recipients, so that they can relink them with the library after making changes +to the library and recompiling it. And you must show them these terms so they +know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, +and (2) we offer you this license, which gives you legal permission to copy, +distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no +warranty for the free library. Also, if the library is modified by someone +else and passed on, the recipients should know that what they have is not +the original version, so that the original author's reputation will not be +affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free +program. We wish to make sure that a company cannot effectively restrict the +users of a free program by obtaining a restrictive license from a patent holder. +Therefore, we insist that any patent license obtained for a version of the +library must be consistent with the full freedom of use specified in this +license. + +Most GNU software, including some libraries, is covered by the ordinary GNU +General Public License. This license, the GNU Lesser General Public License, +applies to certain designated libraries, and is quite different from the ordinary +General Public License. We use this license for certain libraries in order +to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared +library, the combination of the two is legally speaking a combined work, a +derivative of the original library. The ordinary General Public License therefore +permits such linking only if the entire combination fits its criteria of freedom. +The Lesser General Public License permits more lax criteria for linking other +code with the library. + +We call this license the "Lesser" General Public License because it does Less +to protect the user's freedom than the ordinary General Public License. It +also provides other free software developers Less of an advantage over competing +non-free programs. These disadvantages are the reason we use the ordinary +General Public License for many libraries. However, the Lesser license provides +advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the +widest possible use of a certain library, so that it becomes a de-facto standard. +To achieve this, non-free programs must be allowed to use the library. A more +frequent case is that a free library does the same job as widely used non-free +libraries. In this case, there is little to gain by limiting the free library +to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs +enables a greater number of people to use a large body of free software. For +example, permission to use the GNU C Library in non-free programs enables +many more people to use the whole GNU operating system, as well as its variant, +the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' +freedom, it does ensure that the user of a program that is linked with the +Library has the freedom and the wherewithal to run that program using a modified +version of the Library. + +The precise terms and conditions for copying, distribution and modification +follow. Pay close attention to the difference between a "work based on the +library" and a "work that uses the library". The former contains code derived +from the library, whereas the latter must be combined with the library in +order to run. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program +which contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Lesser General +Public License (also called "this License"). Each licensee is addressed as +"you". + +A "library" means a collection of software functions and/or data prepared +so as to be conveniently linked with application programs (which use some +of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has +been distributed under these terms. A "work based on the Library" means either +the Library or any derivative work under copyright law: that is to say, a +work containing the Library or a portion of it, either verbatim or with modifications +and/or translated straightforwardly into another language. (Hereinafter, translation +is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications +to it. For a library, complete source code means all the source code for all +modules it contains, plus any associated interface definition files, plus +the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered +by this License; they are outside its scope. The act of running a program +using the Library is not restricted, and output from such a program is covered +only if its contents constitute a work based on the Library (independent of +the use of the Library in a tool for writing it). Whether that is true depends +on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source +code as you receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice and disclaimer +of warranty; keep intact all the notices that refer to this License and to +the absence of any warranty; and distribute a copy of this License along with +the Library. + +You may charge a fee for the physical act of transferring a copy, and you +may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, +thus forming a work based on the Library, and copy and distribute such modifications +or work under the terms of Section 1 above, provided that you also meet all +of these conditions: + + a) The modified work must itself be a software library. + +b) You must cause the files modified to carry prominent notices stating that +you changed the files and the date of any change. + +c) You must cause the whole of the work to be licensed at no charge to all +third parties under the terms of this License. + +d) If a facility in the modified Library refers to a function or a table of +data to be supplied by an application program that uses the facility, other +than as an argument passed when the facility is invoked, then you must make +a good faith effort to ensure that, in the event an application does not supply +such function or table, the facility still operates, and performs whatever +part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose +that is entirely well-defined independent of the application. Therefore, Subsection +2d requires that any application-supplied function or table used by this function +must be optional: if the application does not supply it, the square root function +must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable +sections of that work are not derived from the Library, and can be reasonably +considered independent and separate works in themselves, then this License, +and its terms, do not apply to those sections when you distribute them as +separate works. But when you distribute the same sections as part of a whole +which is a work based on the Library, the distribution of the whole must be +on the terms of this License, whose permissions for other licensees extend +to the entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest your +rights to work written entirely by you; rather, the intent is to exercise +the right to control the distribution of derivative or collective works based +on the Library. + +In addition, mere aggregation of another work not based on the Library with +the Library (or with a work based on the Library) on a volume of a storage +or distribution medium does not bring the other work under the scope of this +License. + +3. You may opt to apply the terms of the ordinary GNU General Public License +instead of this License to a given copy of the Library. To do this, you must +alter all the notices that refer to this License, so that they refer to the +ordinary GNU General Public License, version 2, instead of to this License. +(If a newer version than version 2 of the ordinary GNU General Public License +has appeared, then you can specify that version instead if you wish.) Do not +make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, +so the ordinary GNU General Public License applies to all subsequent copies +and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library +into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of +it, under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you accompany it with the complete corresponding +machine-readable source code, which must be distributed under the terms of +Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated +place, then offering equivalent access to copy the source code from the same +place satisfies the requirement to distribute the source code, even though +third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but +is designed to work with the Library by being compiled or linked with it, +is called a "work that uses the Library". Such a work, in isolation, is not +a derivative work of the Library, and therefore falls outside the scope of +this License. + +However, linking a "work that uses the Library" with the Library creates an +executable that is a derivative of the Library (because it contains portions +of the Library), rather than a "work that uses the library". The executable +is therefore covered by this License. Section 6 states terms for distribution +of such executables. + +When a "work that uses the Library" uses material from a header file that +is part of the Library, the object code for the work may be a derivative work +of the Library even though the source code is not. Whether this is true is +especially significant if the work can be linked without the Library, or if +the work is itself a library. The threshold for this to be true is not precisely +defined by law. + +If such an object file uses only numerical parameters, data structure layouts +and accessors, and small macros and small inline functions (ten lines or less +in length), then the use of the object file is unrestricted, regardless of +whether it is legally a derivative work. (Executables containing this object +code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute +the object code for the work under the terms of Section 6. Any executables +containing that work also fall under Section 6, whether or not they are linked +directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work +that uses the Library" with the Library to produce a work containing portions +of the Library, and distribute that work under terms of your choice, provided +that the terms permit modification of the work for the customer's own use +and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library +is used in it and that the Library and its use are covered by this License. +You must supply a copy of this License. If the work during execution displays +copyright notices, you must include the copyright notice for the Library among +them, as well as a reference directing the user to the copy of this License. +Also, you must do one of these things: + +a) Accompany the work with the complete corresponding machine-readable source +code for the Library including whatever changes were used in the work (which +must be distributed under Sections 1 and 2 above); and, if the work is an +executable linked with the Library, with the complete machine-readable "work +that uses the Library", as object code and/or source code, so that the user +can modify the Library and then relink to produce a modified executable containing +the modified Library. (It is understood that the user who changes the contents +of definitions files in the Library will not necessarily be able to recompile +the application to use the modified definitions.) + +b) Use a suitable shared library mechanism for linking with the Library. A +suitable mechanism is one that (1) uses at run time a copy of the library +already present on the user's computer system, rather than copying library +functions into the executable, and (2) will operate properly with a modified +version of the library, if the user installs one, as long as the modified +version is interface-compatible with the version that the work was made with. + +c) Accompany the work with a written offer, valid for at least three years, +to give the same user the materials specified in Subsection 6a, above, for +a charge no more than the cost of performing this distribution. + +d) If distribution of the work is made by offering access to copy from a designated +place, offer equivalent access to copy the above specified materials from +the same place. + +e) Verify that the user has already received a copy of these materials or +that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must +include any data and utility programs needed for reproducing the executable +from it. However, as a special exception, the materials to be distributed +need not include anything that is normally distributed (in either source or +binary form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component itself +accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of +other proprietary libraries that do not normally accompany the operating system. +Such a contradiction means you cannot use both them and the Library together +in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side +in a single library together with other library facilities not covered by +this License, and distribute such a combined library, provided that the separate +distribution of the work based on the Library and of the other library facilities +is otherwise permitted, and provided that you do these two things: + +a) Accompany the combined library with a copy of the same work based on the +Library, uncombined with any other library facilities. This must be distributed +under the terms of the Sections above. + +b) Give prominent notice with the combined library of the fact that part of +it is a work based on the Library, and explaining where to find the accompanying +uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library +except as expressly provided under this License. Any attempt otherwise to +copy, modify, sublicense, link with, or distribute the Library is void, and +will automatically terminate your rights under this License. However, parties +who have received copies, or rights, from you under this License will not +have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed +it. However, nothing else grants you permission to modify or distribute the +Library or its derivative works. These actions are prohibited by law if you +do not accept this License. Therefore, by modifying or distributing the Library +(or any work based on the Library), you indicate your acceptance of this License +to do so, and all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), +the recipient automatically receives a license from the original licensor +to copy, distribute, link with or modify the Library subject to these terms +and conditions. You may not impose any further restrictions on the recipients' +exercise of the rights granted herein. You are not responsible for enforcing +compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement +or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your +obligations under this License and any other pertinent obligations, then as +a consequence you may not distribute the Library at all. For example, if a +patent license would not permit royalty-free redistribution of the Library +by all those who receive copies directly or indirectly through you, then the +only way you could satisfy both it and this License would be to refrain entirely +from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents +or other property right claims or to contest validity of any such claims; +this section has the sole purpose of protecting the integrity of the free +software distribution system which is implemented by public license practices. +Many people have made generous contributions to the wide range of software +distributed through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing to +distribute software through any other system and a licensee cannot impose +that choice. + +This section is intended to make thoroughly clear what is believed to be a +consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain +countries either by patents or by copyrighted interfaces, the original copyright +holder who places the Library under this License may add an explicit geographical +distribution limitation excluding those countries, so that distribution is +permitted only in or among countries not thus excluded. In such case, this +License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of +the Lesser 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 Library specifies +a version number of this License which applies to it and "any later version", +you have the option of following the terms and conditions either of that version +or of any later version published by the Free Software Foundation. If the +Library does not specify a license version number, you may choose any version +ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs +whose distribution conditions are incompatible with these, write to the author +to ask for permission. For software which is copyrighted by the Free Software +Foundation, write to the Free Software Foundation; we sometimes make exceptions +for this. Our decision will be guided by the two goals of preserving the free +status of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR +THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE +STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY +"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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE +THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH +HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible +use to the public, we recommend making it free software that everyone can +redistribute and change. You can do so by permitting redistribution under +these terms (or, alternatively, under the terms of the ordinary General Public +License). + +To apply these terms, attach the following notices to the library. It is safest +to attach them to the start of each source file to most effectively convey +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 library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2.1 of the License, or (at your option) +any later version. + +This library is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., 51 +Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, +if any, to sign a "copyright disclaimer" for the library, if necessary. Here +is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in + +the library `Frob' (a library for tweaking knobs) written + +by James Random Hacker. + +< signature of Ty Coon > , 1 April 1990 + +Ty Coon, President of Vice + +That's all there is to it! diff --git a/LICENSES/LGPL-3.0-only.txt b/LICENSES/LGPL-3.0-only.txt new file mode 100644 index 0000000..513d1c0 --- /dev/null +++ b/LICENSES/LGPL-3.0-only.txt @@ -0,0 +1,304 @@ +GNU LESSER 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. + +This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. + +0. Additional Definitions. + +As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. + +"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. + +An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. + +A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". + +The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. + +The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. + +1. Exception to Section 3 of the GNU GPL. +You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. + +2. Conveying Modified Versions. +If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: + + a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. + +3. Object Code Incorporating Material from Library Header Files. +The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license document. + +4. Combined Works. +You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: + + a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license document. + + c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. + + e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) + +5. Combined Libraries. +You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +6. Revised Versions of the GNU Lesser General Public License. +The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. + +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 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 . diff --git a/LICENSES/LicenseRef-KDE-Accepted-LGPL.txt b/LICENSES/LicenseRef-KDE-Accepted-LGPL.txt new file mode 100644 index 0000000..232b3c5 --- /dev/null +++ b/LICENSES/LicenseRef-KDE-Accepted-LGPL.txt @@ -0,0 +1,12 @@ +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 3 of the license or (at your option) any later version +that is accepted by the membership of KDE e.V. (or its successor +approved by the membership of KDE e.V.), which shall act as a +proxy as defined in Section 6 of version 3 of the license. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a6c46e6 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# KRunner + +Framework for Plasma runners + +## Introduction + +The Plasma workspace provides an application called KRunner which, among other +things, allows one to type into a text area which causes various actions and +information that match the text appear as the text is being typed. + +One application for this is the universal runner you can launch with ALT-F2. + +This functionality is provided via plugins loaded at runtime called "Runners". +These plugins can be used by any application using the Plasma library. The +KRunner framework is used to write these plugins, as explained in +[this tutorial](https://develop.kde.org/docs/plasma/krunner/) + diff --git a/README.md.license b/README.md.license new file mode 100644 index 0000000..f1ce577 --- /dev/null +++ b/README.md.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: Alexander Lohnau +SPDX-License-Identifier: CC0-1.0 + diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 0000000..884c65a --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: Alexander Lohnau +# SPDX-License-Identifier: CC0-1.0 + +version = 1 +SPDX-PackageName = "krunner" +SPDX-PackageSupplier = "Alexander Lohnau " +SPDX-PackageDownloadLocation = "https://invent.kde.org/frameworks/krunner" + +[[annotations]] +path = "autotests/**.desktop" +precedence = "aggregate" +SPDX-FileCopyrightText = "KRunner contributors" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "templates/runner6python/**" +precedence = "aggregate" +SPDX-FileCopyrightText = "Alexander Lohnau" +SPDX-License-Identifier = "LGPL-2.1-or-later" + +[[annotations]] +path = "templates/runner6/**" +precedence = "aggregate" +SPDX-FileCopyrightText = "KDE Contributors" +SPDX-License-Identifier = "LGPL-2.1-or-later" diff --git a/autotests/CMakeLists.txt b/autotests/CMakeLists.txt new file mode 100644 index 0000000..f541401 --- /dev/null +++ b/autotests/CMakeLists.txt @@ -0,0 +1,54 @@ +# SPDX-FileCopyrightText: 2021 Alexander Lohnau +# SPDX-License-Identifier: BSD-2-Clause +find_package(Qt6 ${REQUIRED_QT_VERSION} CONFIG REQUIRED Test) + +include(ECMAddTests) + +remove_definitions(-DQT_NO_CAST_FROM_ASCII) + +ecm_add_tests( + dbusrunnertest.cpp + runnermatchmethodstest.cpp + runnermanagerhistorytest.cpp + runnermanagersinglerunnermodetest.cpp + runnermanagertest.cpp + testmetadataconversion.cpp + threadingtest.cpp + LINK_LIBRARIES Qt6::Gui Qt6::DBus Qt6::Test KF6::Runner KF6::ConfigCore +) + +kcoreaddons_add_plugin(fakerunnerplugin SOURCES plugins/fakerunnerplugin.cpp INSTALL_NAMESPACE "krunnertest" STATIC) +target_link_libraries(fakerunnerplugin KF6Runner Qt6::Gui) + +kcoreaddons_add_plugin(suspendedrunnerplugin SOURCES plugins/suspendedrunner.cpp INSTALL_NAMESPACE "krunnertest2" STATIC) +target_link_libraries(suspendedrunnerplugin KF6Runner) + +kcoreaddons_target_static_plugins(runnermanagerhistorytest NAMESPACE krunnertest) +kcoreaddons_target_static_plugins(runnermanagertest NAMESPACE krunnertest) +kcoreaddons_target_static_plugins(runnermanagertest NAMESPACE krunnertest2) +kcoreaddons_target_static_plugins(threadingtest NAMESPACE krunnertest) + +add_executable(testremoterunner) +qt_add_dbus_adaptor(demoapp_dbus_adaptor_SRCS "../src/data/org.kde.krunner1.xml" plugins/testremoterunner.h TestRemoteRunner) +target_sources(testremoterunner PRIVATE plugins/testremoterunner.cpp ${demoapp_dbus_adaptor_SRCS}) +target_link_libraries(testremoterunner + Qt6::DBus + Qt6::Gui + KF6::Runner +) + +include(../KF6KRunnerMacros.cmake) +krunner_configure_test(dbusrunnertest testremoterunner DESKTOP_FILE "${CMAKE_CURRENT_SOURCE_DIR}/plugins/dbusrunnertest.desktop") +krunner_configure_test(runnermanagersinglerunnermodetest testremoterunner DESKTOP_FILE "${CMAKE_CURRENT_SOURCE_DIR}/plugins/dbusrunnertest.desktop") +krunner_configure_test(runnermanagertest testremoterunner DESKTOP_FILE "${CMAKE_CURRENT_SOURCE_DIR}/plugins/dbusrunnertest.desktop") +krunner_configure_test(threadingtest testremoterunner DESKTOP_FILE "${CMAKE_CURRENT_SOURCE_DIR}/plugins/dbusrunnertest.desktop") + +find_package(Qt6 ${QT_MIN_VERSION} OPTIONAL_COMPONENTS Widgets) +if (TARGET Qt6::Widgets) + add_executable(modelwidgettest modelwidgettest.cpp) + target_link_libraries(modelwidgettest KF6::Runner Qt6::Widgets) + kcoreaddons_target_static_plugins(modelwidgettest NAMESPACE krunnertest) + +endif() +add_executable(pluginbenchmarker pluginbenchmarker.cpp) +target_link_libraries(pluginbenchmarker KF6::Runner) diff --git a/autotests/dbusrunnertest.cpp b/autotests/dbusrunnertest.cpp new file mode 100644 index 0000000..4951120 --- /dev/null +++ b/autotests/dbusrunnertest.cpp @@ -0,0 +1,241 @@ +/* + SPDX-FileCopyrightText: 2017 David Edmundson + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "abstractrunnertest.h" +#include "kpluginmetadata_utils_p.h" + +using namespace KRunner; + +Q_DECLARE_METATYPE(KRunner::QueryMatch) +Q_DECLARE_METATYPE(QList) + +class DBusRunnerTest : public AbstractRunnerTest +{ + Q_OBJECT +public: + DBusRunnerTest(); + ~DBusRunnerTest() override; + +private Q_SLOTS: + void cleanup(); + void testMatch(); + void testMulti(); + void testFilterProperties(); + void testFilterProperties_data(); + void testRequestActionsOnce(); + void testDBusRunnerSyntaxIntegration(); + void testIconData(); + void testLifecycleMethods(); + void testRequestActionsWildcards(); +}; + +DBusRunnerTest::DBusRunnerTest() + : AbstractRunnerTest() +{ + qRegisterMetaType>(); + QStandardPaths::setTestModeEnabled(true); +} + +DBusRunnerTest::~DBusRunnerTest() +{ +} + +void DBusRunnerTest::cleanup() +{ + // Make sure kill the running processes after each test + killRunningDBusProcesses(); +} + +void DBusRunnerTest::testMatch() +{ + QProcess *process = startDBusRunnerProcess({QStringLiteral("net.krunnertests.dave")}); + initProperties(); + const auto matches = launchQuery(QStringLiteral("foo")); + + // verify matches + QCOMPARE(matches.count(), 1); + auto result = matches.first(); + + // see testremoterunner.cpp + QCOMPARE(result.id(), QStringLiteral("dbusrunnertest_id1")); // note the runner name is prepended + QCOMPARE(result.text(), QStringLiteral("Match 1")); + QCOMPARE(result.iconName(), QStringLiteral("icon1")); + QCOMPARE(result.categoryRelevance(), qToUnderlying(KRunner::QueryMatch::CategoryRelevance::Highest)); + QCOMPARE(result.isMultiLine(), true); + // relevance can't be compared easily because RunnerContext meddles with it + + // verify actions + QCOMPARE(result.actions().size(), 1); + auto action = result.actions().constFirst(); + + QCOMPARE(action.text(), QStringLiteral("Action 1")); + + QSignalSpy processSpy(process, &QProcess::readyRead); + manager->run(result); + processSpy.wait(); + QCOMPARE(process->readAllStandardOutput().trimmed().split('\n').constLast(), QByteArray("Running:id1:")); + + manager->run(result, action); + processSpy.wait(); + QCOMPARE(process->readAllStandardOutput().trimmed().split('\n').constLast(), QByteArray("Running:id1:action1")); +} + +void DBusRunnerTest::testMulti() +{ + startDBusRunnerProcess({QStringLiteral("net.krunnertests.multi.a1")}, QStringLiteral("net.krunnertests.multi.a1")); + startDBusRunnerProcess({QStringLiteral("net.krunnertests.multi.a2")}, QStringLiteral("net.krunnertests.multi.a2")); + manager.reset(new RunnerManager()); // This case is special, because we want to load the runners manually + + auto md = parseMetaDataFromDesktopFile(QFINDTESTDATA("plugins/dbusrunnertestmulti.desktop")); + QVERIFY(md.isValid()); + manager->loadRunner(md); + const auto matches = launchQuery(QStringLiteral("foo")); + + // verify matches, must be one from each + QCOMPARE(matches.count(), 2); + + const QString first = matches.at(0).data().toList().constFirst().toString(); + const QString second = matches.at(1).data().toList().constFirst().toString(); + QVERIFY(first != second); + QVERIFY(first == QLatin1String("net.krunnertests.multi.a1") || first == QStringLiteral("net.krunnertests.multi.a2")); + QVERIFY(second == QLatin1String("net.krunnertests.multi.a1") || second == QStringLiteral("net.krunnertests.multi.a2")); +} + +void DBusRunnerTest::testRequestActionsOnce() +{ + QProcess *process = startDBusRunnerProcess({QStringLiteral("net.krunnertests.dave")}); + initProperties(); + + launchQuery(QStringLiteral("foo")); + QVERIFY(!manager->matches().constFirst().actions().isEmpty()); + manager->matchSessionComplete(); + launchQuery(QStringLiteral("fooo")); + const QString processOutput(process->readAllStandardOutput()); + QCOMPARE(processOutput.count("Matching"), 2); + QCOMPARE(processOutput.count("Actions"), 1); + QVERIFY(!manager->matches().constFirst().actions().isEmpty()); +} + +void DBusRunnerTest::testFilterProperties_data() +{ + QTest::addColumn("rejectedQuery"); + QTest::addColumn("acceptedQuery"); + + QTest::newRow("min-letter-count") << "fo" + << "foo"; + QTest::newRow("match-regex") << "barfoo" + << "foobar"; +} + +void DBusRunnerTest::testFilterProperties() +{ + QFETCH(QString, rejectedQuery); + QFETCH(QString, acceptedQuery); + QProcess *process = startDBusRunnerProcess({QStringLiteral("net.krunnertests.dave")}); + initProperties(); + + launchQuery(rejectedQuery); + // Match method was not called, because of the min letter count or match regex property + QVERIFY(process->readAllStandardOutput().isEmpty()); + // accepted query fits those constraints + launchQuery(acceptedQuery); + QCOMPARE(QString(process->readAllStandardOutput()).remove("Actions").trimmed(), QStringLiteral("Matching:") + acceptedQuery); +} + +void DBusRunnerTest::testDBusRunnerSyntaxIntegration() +{ + startDBusRunnerProcess({QStringLiteral("net.krunnertests.dave")}); + initProperties(); + const QList syntaxes = runner->syntaxes(); + QCOMPARE(syntaxes.size(), 2); + + QCOMPARE(syntaxes.at(0).exampleQueries().size(), 1); + QCOMPARE(syntaxes.at(0).exampleQueries().constFirst(), QStringLiteral("syntax1")); + QCOMPARE(syntaxes.at(0).description(), QStringLiteral("description1")); + QCOMPARE(syntaxes.at(1).exampleQueries().size(), 1); + QCOMPARE(syntaxes.at(1).exampleQueries().constFirst(), QStringLiteral("syntax2")); + QCOMPARE(syntaxes.at(1).description(), QStringLiteral("description2")); +} + +void DBusRunnerTest::testIconData() +{ + startDBusRunnerProcess({QStringLiteral("net.krunnertests.dave")}); + initProperties(); + + const auto matches = launchQuery(QStringLiteral("fooCostomIcon")); + QCOMPARE(matches.count(), 1); + auto result = matches.first(); + + QImage expectedIcon(10, 10, QImage::Format_RGBA8888); + expectedIcon.fill(Qt::blue); + + QCOMPARE(result.icon().availableSizes().first(), QSize(10, 10)); + QCOMPARE(result.icon().pixmap(QSize(10, 10)), QPixmap::fromImage(expectedIcon)); +} + +void DBusRunnerTest::testLifecycleMethods() +{ + QProcess *process = startDBusRunnerProcess({QStringLiteral("net.krunnertests.dave"), QString()}); + manager.reset(new RunnerManager()); // This case is special, because we want to load the runners manually + auto md = parseMetaDataFromDesktopFile(QFINDTESTDATA("plugins/dbusrunnertestruntimeconfig.desktop")); + manager->loadRunner(md); + QCOMPARE(manager->runners().count(), 1); + // Match session should be set up automatically + launchQuery(QStringLiteral("fooo")); + + // Make sure we got our match, end the match session and give the process a bit of time to get the DBus signal + QTRY_COMPARE_WITH_TIMEOUT(manager->matches().count(), 1, 2000); + manager->matchSessionComplete(); + QTest::qWait(500); + + const QStringList lifeCycleSteps = QString::fromLocal8Bit(process->readAllStandardOutput()).split(QLatin1Char('\n'), Qt::SkipEmptyParts); + const QStringList expectedLifeCycleSteps = { + QStringLiteral("Config"), + QStringLiteral("Actions"), + QStringLiteral("Matching:fooo"), + QStringLiteral("Teardown"), + }; + QCOMPARE(lifeCycleSteps, expectedLifeCycleSteps); + + // The query does not match our min letter count we set at runtime + launchQuery(QStringLiteral("foo")); + QVERIFY(manager->matches().isEmpty()); + // The query does not match our match regex we set at runtime + launchQuery(QStringLiteral("barfoo")); + QVERIFY(manager->matches().isEmpty()); +} + +void DBusRunnerTest::testRequestActionsWildcards() +{ + initProperties(); + manager.reset(new RunnerManager()); // This case is special, because we want to load the runners manually + auto md = parseMetaDataFromDesktopFile(QFINDTESTDATA("plugins/dbusrunnertestmulti.desktop")); + QVERIFY(md.isValid()); + manager->loadRunner(md); + QCOMPARE(manager->runners().count(), 1); + + startDBusRunnerProcess({QStringLiteral("net.krunnertests.multi.a1")}, QStringLiteral("net.krunnertests.multi.a1")); + startDBusRunnerProcess({QStringLiteral("net.krunnertests.multi.a2")}, QStringLiteral("net.krunnertests.multi.a2")); + const auto matches = launchQuery("foo"); + QCOMPARE(matches.count(), 2); + + QCOMPARE(matches.at(0).actions().count(), 1); + QCOMPARE(matches.at(0).actions(), matches.at(1).actions()); +} + +QTEST_MAIN(DBusRunnerTest) + +#include "dbusrunnertest.moc" diff --git a/autotests/modelwidgettest.cpp b/autotests/modelwidgettest.cpp new file mode 100644 index 0000000..6ea33f4 --- /dev/null +++ b/autotests/modelwidgettest.cpp @@ -0,0 +1,51 @@ +/* + SPDX-FileCopyrightText: 2023 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include +#include +#include +#include +#include + +#include + +using namespace KRunner; + +class TestObject : public QWidget +{ + Q_OBJECT +public: + explicit TestObject() + : QWidget() + { + ResultsModel *model = new ResultsModel(this); + // Comment this line out to load all the system runners + model->runnerManager()->loadRunner(KPluginMetaData::findPluginById(QStringLiteral("krunnertest"), QStringLiteral("fakerunnerplugin"))); + + QListView *view = new QListView(this); + view->setModel(model); + view->setAlternatingRowColors(true); + + QLineEdit *edit = new QLineEdit(this); + connect(edit, &QLineEdit::textChanged, model, &ResultsModel::setQueryString); + edit->setText("foo"); + + QVBoxLayout *l = new QVBoxLayout(this); + l->addWidget(edit); + l->addWidget(view); + } +}; + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + TestObject obj; + obj.show(); + + return app.exec(); +} + +#include "modelwidgettest.moc" diff --git a/autotests/pluginbenchmarker.cpp b/autotests/pluginbenchmarker.cpp new file mode 100644 index 0000000..b4d2a92 --- /dev/null +++ b/autotests/pluginbenchmarker.cpp @@ -0,0 +1,60 @@ +/* + SPDX-FileCopyrightText: 2023 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.0-or-later +*/ +#include "runnermanager.h" +#include +#include +#include + +#include + +static void runQuery(const QString &runnerId, const QString &query, int iterations) +{ + QEventLoop loop; + KRunner::RunnerManager manager; + manager.setAllowedRunners({runnerId}); + manager.launchQuery("test"); + qWarning() << "Following runners are loaded" << manager.runners(); + QObject::connect(&manager, &KRunner::RunnerManager::queryFinished, &loop, &QEventLoop::quit); + for (int i = 0; i < iterations; ++i) { + // Setup of match session is done for first query automatically + for (int j = 1; j <= query.size(); ++j) { + manager.launchQuery(query.mid(0, j)); + loop.exec(); + } + manager.matchSessionComplete(); + } +} + +int main(int argv, char **argc) +{ + QCoreApplication app(argv, argc); + QCommandLineOption iterationsOption("iterations", "Number of iterations where the query will be run", "iterations"); + + QCommandLineParser parser; + parser.addOption(iterationsOption); + parser.addPositionalArgument("runner", "The runnerId you want to load"); + parser.addPositionalArgument("query", "The query to run, each letter is launched as it's own query"); + parser.process(app); + + const QStringList positionalArguments = parser.positionalArguments(); + if (positionalArguments.size() != 2) { + qWarning() << "The runnerId and query must be specified as the only positional arguments"; + exit(1); + } + const QString runner = positionalArguments.at(0); + const QString query = positionalArguments.at(1); + int iterations = parser.isSet(iterationsOption) ? parser.value(iterationsOption).toInt() : 1; + if (iterations < 1) { + qWarning() << "invalid iterations value set, it must be more than 1" << iterations; + } + + QTimer::singleShot(0, &app, [&app, runner, query, iterations]() { + runQuery(runner, query, iterations); + QTimer::singleShot(10, &app, &QCoreApplication::quit); + std::cout << "Finished running queries" << std::endl; + }); + + return app.exec(); +} diff --git a/autotests/plugins/dbusrunnertest.desktop b/autotests/plugins/dbusrunnertest.desktop new file mode 100644 index 0000000..3030c80 --- /dev/null +++ b/autotests/plugins/dbusrunnertest.desktop @@ -0,0 +1,20 @@ +[Desktop Entry] +Name=DBus runner test +Comment=DBus runner test +X-KDE-ServiceTypes=Plasma/Runner +Type=Service +Icon=internet-web-browser +X-KDE-PluginInfo-Author=Some Developer +X-KDE-PluginInfo-Email=kde@example.com +X-KDE-PluginInfo-Name=dbusrunnertest +X-KDE-PluginInfo-Version=1.0 +X-KDE-PluginInfo-License=LGPL +X-KDE-PluginInfo-EnabledByDefault=true +X-Plasma-API=DBus +X-Plasma-DBusRunner-Service=net.krunnertests.dave +X-Plasma-DBusRunner-Path=/dave +X-Plasma-Request-Actions-Once=true +X-Plasma-Runner-Min-Letter-Count=3 +X-Plasma-Runner-Match-Regex=^fo +X-Plasma-Runner-Syntaxes=syntax1,syntax2 +X-Plasma-Runner-Syntax-Descriptions=description1,description2 diff --git a/autotests/plugins/dbusrunnertestmulti.desktop b/autotests/plugins/dbusrunnertestmulti.desktop new file mode 100644 index 0000000..824b9c8 --- /dev/null +++ b/autotests/plugins/dbusrunnertestmulti.desktop @@ -0,0 +1,15 @@ +[Desktop Entry] +Name=DBus runner testmulti +Comment=DBus runner testmulti +X-KDE-ServiceTypes=Plasma/Runner +Type=Service +Icon=internet-web-browser +X-KDE-PluginInfo-Author=Some Developer +X-KDE-PluginInfo-Email=kde@example.com +X-KDE-PluginInfo-Name=dbusrunnertestmulti +X-KDE-PluginInfo-Version=1.0 +X-KDE-PluginInfo-License=LGPL +X-KDE-PluginInfo-EnabledByDefault=true +X-Plasma-API=DBus +X-Plasma-DBusRunner-Service=net.krunnertests.multi.* +X-Plasma-DBusRunner-Path=/dave diff --git a/autotests/plugins/dbusrunnertestruntimeconfig.desktop b/autotests/plugins/dbusrunnertestruntimeconfig.desktop new file mode 100644 index 0000000..fa20222 --- /dev/null +++ b/autotests/plugins/dbusrunnertestruntimeconfig.desktop @@ -0,0 +1,18 @@ +[Desktop Entry] +Name=DBus runner test +Comment=DBus runner test +X-KDE-ServiceTypes=Plasma/Runner +Type=Service +Icon=internet-web-browser +X-KDE-PluginInfo-Author=Some Developer +X-KDE-PluginInfo-Email=kde@example.com +X-KDE-PluginInfo-Name=dbusrunnertest +X-KDE-PluginInfo-Version=1.0 +X-KDE-PluginInfo-License=LGPL +X-KDE-PluginInfo-EnabledByDefault=true +X-Plasma-API=DBus2 +X-Plasma-DBusRunner-Service=net.krunnertests.dave +X-Plasma-DBusRunner-Path=/dave +X-Plasma-Request-Actions-Once=true +X-Plasma-Runner-Syntaxes=syntax1,syntax2 +X-Plasma-Runner-Syntax-Descriptions=description1,description2 diff --git a/autotests/plugins/fakerunner.h b/autotests/plugins/fakerunner.h new file mode 100644 index 0000000..21fe07a --- /dev/null +++ b/autotests/plugins/fakerunner.h @@ -0,0 +1,48 @@ +/* + SPDX-FileCopyrightText: 2021 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include +#include +#include +#include +#include + +using namespace KRunner; + +class FakeRunner : public AbstractRunner +{ +public: + explicit FakeRunner(QObject *parent, const KPluginMetaData &metadata) + : AbstractRunner(parent, metadata) + , m_action("someid", "sometext", "dialog-ok") + { + } + ~FakeRunner() + { + // qWarning() << Q_FUNC_INFO; + } + + void match(RunnerContext &context) override + { + // Do not use nested event loop, because that would be quit when quitting the QThread's event loop + QThread::msleep(50); + if (context.query().startsWith(QLatin1String("foo"))) { + context.addMatch(createDummyMatch(QStringLiteral("foo"), 0.1)); + context.addMatch(createDummyMatch(QStringLiteral("bar"), 0.2)); + } + } + +private: + QueryMatch createDummyMatch(const QString &text, qreal relevance) + { + QueryMatch queryMatch(this); + queryMatch.setId(text); + queryMatch.setText(text); + queryMatch.setRelevance(relevance); + queryMatch.setActions({m_action}); + return queryMatch; + } + KRunner::Action m_action; +}; diff --git a/autotests/plugins/fakerunnerplugin.cpp b/autotests/plugins/fakerunnerplugin.cpp new file mode 100644 index 0000000..d4d1267 --- /dev/null +++ b/autotests/plugins/fakerunnerplugin.cpp @@ -0,0 +1,10 @@ +/* + SPDX-FileCopyrightText: 2021 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include "fakerunner.h" + +K_PLUGIN_CLASS_WITH_JSON(FakeRunner, "metadatafile1.json") + +#include "fakerunnerplugin.moc" diff --git a/autotests/plugins/metadatafile1.desktop b/autotests/plugins/metadatafile1.desktop new file mode 100644 index 0000000..c943800 --- /dev/null +++ b/autotests/plugins/metadatafile1.desktop @@ -0,0 +1,7 @@ +[Desktop Entry] +Name=DBus runner test +X-KDE-ServiceTypes=Plasma/Runner +Type=Service +X-KDE-PluginInfo-EnabledByDefault=true +X-Plasma-Runner-Unique-Results=true +X-Plasma-Runner-Weak-Results=true diff --git a/autotests/plugins/metadatafile1.json b/autotests/plugins/metadatafile1.json new file mode 100644 index 0000000..78ca1e2 --- /dev/null +++ b/autotests/plugins/metadatafile1.json @@ -0,0 +1,11 @@ +{ + "KPlugin": { + "EnabledByDefault": true, + "Name": "DBus runner test", + "ServiceTypes": [ + "Plasma/Runner" + ] + }, + "X-Plasma-Runner-Unique-Results": true, + "X-Plasma-Runner-Weak-Results": true +} diff --git a/autotests/plugins/metadatafile1.json.license b/autotests/plugins/metadatafile1.json.license new file mode 100644 index 0000000..f24ebfe --- /dev/null +++ b/autotests/plugins/metadatafile1.json.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: none +SPDX-License-Identifier: CC0-1.0 diff --git a/autotests/plugins/metadatafile2.desktop b/autotests/plugins/metadatafile2.desktop new file mode 100644 index 0000000..f13ae2d --- /dev/null +++ b/autotests/plugins/metadatafile2.desktop @@ -0,0 +1,6 @@ +[Desktop Entry] +Name=DBus runner test +X-KDE-ServiceTypes=Plasma/Runner +Type=Service +X-Plasma-Runner-Unique-Results=true +X-Plasma-Runner-Weak-Results=false diff --git a/autotests/plugins/plasma-runner-dbusrunnertest.desktop b/autotests/plugins/plasma-runner-dbusrunnertest.desktop new file mode 100644 index 0000000..3030c80 --- /dev/null +++ b/autotests/plugins/plasma-runner-dbusrunnertest.desktop @@ -0,0 +1,20 @@ +[Desktop Entry] +Name=DBus runner test +Comment=DBus runner test +X-KDE-ServiceTypes=Plasma/Runner +Type=Service +Icon=internet-web-browser +X-KDE-PluginInfo-Author=Some Developer +X-KDE-PluginInfo-Email=kde@example.com +X-KDE-PluginInfo-Name=dbusrunnertest +X-KDE-PluginInfo-Version=1.0 +X-KDE-PluginInfo-License=LGPL +X-KDE-PluginInfo-EnabledByDefault=true +X-Plasma-API=DBus +X-Plasma-DBusRunner-Service=net.krunnertests.dave +X-Plasma-DBusRunner-Path=/dave +X-Plasma-Request-Actions-Once=true +X-Plasma-Runner-Min-Letter-Count=3 +X-Plasma-Runner-Match-Regex=^fo +X-Plasma-Runner-Syntaxes=syntax1,syntax2 +X-Plasma-Runner-Syntax-Descriptions=description1,description2 diff --git a/autotests/plugins/plasma-runner-testconversionfile.desktop b/autotests/plugins/plasma-runner-testconversionfile.desktop new file mode 100644 index 0000000..115ad8c --- /dev/null +++ b/autotests/plugins/plasma-runner-testconversionfile.desktop @@ -0,0 +1,5 @@ +[Desktop Entry] +Type=Service +Name=DBus runner test +Comment=Some Comment +X-KDE-PluginInfo-Name=testconversionfile diff --git a/autotests/plugins/suspendedrunner.cpp b/autotests/plugins/suspendedrunner.cpp new file mode 100644 index 0000000..8bb815e --- /dev/null +++ b/autotests/plugins/suspendedrunner.cpp @@ -0,0 +1,37 @@ + +/* + SPDX-FileCopyrightText: 2023 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include +#include +#include +#include +#include + +using namespace KRunner; + +class SuspendedRunner : public AbstractRunner +{ +public: + explicit SuspendedRunner(QObject *parent, const KPluginMetaData &metadata) + : AbstractRunner(parent, metadata) + { + } + void reloadConfiguration() override + { + QThread::msleep(3000); + } + + void match(RunnerContext &context) override + { + QueryMatch m(this); + m.setText("bla"); + context.addMatch(m); + } +}; + +K_PLUGIN_CLASS_WITH_JSON(SuspendedRunner, "metadatafile1.json") + +#include "suspendedrunner.moc" diff --git a/autotests/plugins/testremoterunner.cpp b/autotests/plugins/testremoterunner.cpp new file mode 100644 index 0000000..f80c820 --- /dev/null +++ b/autotests/plugins/testremoterunner.cpp @@ -0,0 +1,134 @@ +/* + SPDX-FileCopyrightText: 2017 David Edmundson + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include "testremoterunner.h" + +#include +#include +#include + +#include + +#include "krunner1adaptor.h" + +// Test DBus runner, if the search term contains "foo" it returns a match, otherwise nothing +// Run prints a line to stdout + +TestRemoteRunner::TestRemoteRunner(const QString &serviceName, bool showLifecycleMethodCalls) +{ + new Krunner1Adaptor(this); + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + const bool connected = QDBusConnection::sessionBus().registerService(serviceName); + Q_ASSERT(connected); + const bool registered = QDBusConnection::sessionBus().registerObject(QStringLiteral("/dave"), this); + Q_ASSERT(registered); + m_showLifecycleMethodCalls = showLifecycleMethodCalls; +} + +static RemoteImage serializeImage(const QImage &image) +{ + QImage convertedImage = image.convertToFormat(QImage::Format_RGBA8888); + RemoteImage remoteImage; + remoteImage.width = convertedImage.width(); + remoteImage.height = convertedImage.height(); + remoteImage.rowStride = convertedImage.bytesPerLine(); + remoteImage.hasAlpha = true, remoteImage.bitsPerSample = 8; + remoteImage.channels = 4, remoteImage.data = QByteArray(reinterpret_cast(convertedImage.constBits()), convertedImage.sizeInBytes()); + return remoteImage; +} + +RemoteMatches TestRemoteRunner::Match(const QString &searchTerm) +{ + RemoteMatches ms; + std::cout << "Matching:" << qPrintable(searchTerm) << std::endl; + if (searchTerm == QLatin1String("fooCostomIcon")) { + RemoteMatch m; + m.id = QStringLiteral("id2"); + m.text = QStringLiteral("Match 1"); + m.categoryRelevance = qToUnderlying(KRunner::QueryMatch::CategoryRelevance::Highest); + m.relevance = 0.8; + QImage icon(10, 10, QImage::Format_RGBA8888); + icon.fill(Qt::blue); + m.properties[QStringLiteral("icon-data")] = QVariant::fromValue(serializeImage(icon)); + + ms << m; + } else if (searchTerm.startsWith(QLatin1String("fooDelay"))) { + // This special query string "fooDelayNNNN" allows us to introduce a desired delay + // to simulate a slow query + const int requestedDelayMs = searchTerm.mid(8).toInt(); + RemoteMatch m; + m.id = QStringLiteral("id3"); + m.text = QStringLiteral("Match 1"); + m.iconName = QStringLiteral("icon1"); + m.categoryRelevance = qToUnderlying(KRunner::QueryMatch::CategoryRelevance::Highest); + m.relevance = 0.8; + m.properties[QStringLiteral("actions")] = QStringList(QStringLiteral("action1")); + QThread::msleep(requestedDelayMs); + ms << m; + } else if (searchTerm.contains(QLatin1String("foo"))) { + RemoteMatch m; + m.id = QStringLiteral("id1"); + m.text = QStringLiteral("Match 1"); + m.iconName = QStringLiteral("icon1"); + m.categoryRelevance = qToUnderlying(KRunner::QueryMatch::CategoryRelevance::Highest); + m.relevance = 0.8; + m.properties[QStringLiteral("actions")] = QStringList(QStringLiteral("action1")); + m.properties[QStringLiteral("multiline")] = true; + ms << m; + } + return ms; +} + +KRunner::Actions TestRemoteRunner::Actions() +{ + std::cout << "Actions" << std::endl; + KRunner::Action action("action1", "document-browser", "Action 1"); + + KRunner::Action action2("action2", "document-browser", "Action 2"); + return QList{action, action2}; +} + +void TestRemoteRunner::Run(const QString &id, const QString &actionId) +{ + std::cout << "Running:" << qPrintable(id) << ":" << qPrintable(actionId) << std::endl; + std::cout.flush(); +} + +void TestRemoteRunner::Teardown() +{ + if (m_showLifecycleMethodCalls) { + std::cout << "Teardown" << std::endl; + std::cout.flush(); + } +} + +QVariantMap TestRemoteRunner::Config() +{ + if (m_showLifecycleMethodCalls) { + std::cout << "Config" << std::endl; + std::cout.flush(); + } + + return { + {"MatchRegex", "^fo"}, + {"MinLetterCount", 4}, + }; +} + +int main(int argc, char **argv) +{ + QCoreApplication app(argc, argv); + const auto arguments = app.arguments(); + Q_ASSERT(arguments.count() >= 2); + TestRemoteRunner r(arguments[1], arguments.count() == 3); + app.exec(); +} + +#include "moc_testremoterunner.cpp" diff --git a/autotests/plugins/testremoterunner.h b/autotests/plugins/testremoterunner.h new file mode 100644 index 0000000..aeb41d7 --- /dev/null +++ b/autotests/plugins/testremoterunner.h @@ -0,0 +1,28 @@ +/* + SPDX-FileCopyrightText: 2017 David Edmundson + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#pragma once + +#include "../src/dbusutils_p.h" +#include +#include + +class TestRemoteRunner : public QObject +{ + Q_OBJECT +public: + explicit TestRemoteRunner(const QString &serviceName, bool showLifecycleMethodCalls); + +public Q_SLOTS: + KRunner::Actions Actions(); + RemoteMatches Match(const QString &searchTerm); + void Run(const QString &id, const QString &actionId); + void Teardown(); + QVariantMap Config(); + +private: + bool m_showLifecycleMethodCalls = false; +}; diff --git a/autotests/runnermanagerhistorytest.cpp b/autotests/runnermanagerhistorytest.cpp new file mode 100644 index 0000000..05e2c46 --- /dev/null +++ b/autotests/runnermanagerhistorytest.cpp @@ -0,0 +1,148 @@ +/* + SPDX-FileCopyrightText: 2021 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.1-or-later +*/ + +#include "runnermanager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace KRunner +{ +extern int __changeCountBeforeSaving; +} +using namespace KRunner; +class RunnerManagerHistoryTest : public QObject +{ + Q_OBJECT +public: + RunnerManagerHistoryTest() + { + __changeCountBeforeSaving = 1; + QStandardPaths::setTestModeEnabled(true); + stateConfigFile = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QDir::separator() + "krunnerstaterc"; + } + +private: + QString stateConfigFile; + void addToHistory(const QStringList &queries, RunnerManager &manager) + { + QCOMPARE(manager.runners().count(), 1); + for (const QString &query : queries) { + QueryMatch match(manager.runners().constFirst()); + // Make sure internally the term and untrimmedTerm are set + manager.launchQuery(query, "thisrunnerdoesnotexist"); + manager.searchContext()->setQuery(query); + manager.run(match); + } + } + void launchQuery(const QString &query, RunnerManager *manager) + { + QSignalSpy spy(manager, &KRunner::RunnerManager::queryFinished); + manager->launchQuery(query); + QVERIFY2(spy.wait(), "RunnerManager did not emit the queryFinished signal"); + } + +private Q_SLOTS: + void init() + { + if (QFileInfo::exists(stateConfigFile)) { + QFile::remove(stateConfigFile); + } + } + void testRunnerHistory(); + void testRunnerHistory_data(); + void testHistorySuggestionsAndRemoving(); + void testRelevanceForOftenLaunched(); +}; + +void RunnerManagerHistoryTest::testRunnerHistory() +{ + QFETCH(const QStringList, queries); + QFETCH(const QStringList, expectedEntries); + + RunnerManager manager; + manager.setAllowedRunners({QStringLiteral("fakerunnerplugin")}); + manager.loadRunner(KPluginMetaData::findPluginById(QStringLiteral("krunnertest"), QStringLiteral("fakerunnerplugin"))); + addToHistory(queries, manager); + QCOMPARE(manager.history(), expectedEntries); +} + +void RunnerManagerHistoryTest::testRunnerHistory_data() +{ + QTest::addColumn("queries"); + QTest::addColumn("expectedEntries"); + + QTest::newRow("should add simple entry to history") << QStringList{"test"} << QStringList{"test"}; + QTest::newRow("should not add entry that starts with space") << QStringList{" test"} << QStringList{}; + QTest::newRow("should not add duplicate entries") << QStringList{"test", "test"} << QStringList{"test"}; + QTest::newRow("should not add duplicate entries but put last run at beginning") << QStringList{"test", "test2", "test"} << QStringList{"test", "test2"}; +} + +void RunnerManagerHistoryTest::testHistorySuggestionsAndRemoving() +{ + RunnerManager manager; + manager.setAllowedRunners({QStringLiteral("fakerunnerplugin")}); + manager.loadRunner(KPluginMetaData::findPluginById(QStringLiteral("krunnertest"), QStringLiteral("fakerunnerplugin"))); + const QStringList queries = {"test1", "test2", "test3"}; + addToHistory(queries, manager); + QStringList expectedBeforeRemoval = QStringList{"test3", "test2", "test1"}; + QCOMPARE(manager.history(), expectedBeforeRemoval); + QCOMPARE(manager.getHistorySuggestion("t"), "test3"); + QCOMPARE(manager.getHistorySuggestion("doesnotexist"), QString()); + + manager.removeFromHistory(42); + QCOMPARE(manager.history(), expectedBeforeRemoval); + manager.removeFromHistory(0); + QStringList expectedAfterRemoval = QStringList{"test2", "test1"}; + QCOMPARE(manager.history(), expectedAfterRemoval); + QCOMPARE(manager.getHistorySuggestion("t"), "test2"); +} + +void RunnerManagerHistoryTest::testRelevanceForOftenLaunched() +{ + { + KConfig cfg(stateConfigFile); + cfg.group("PlasmaRunnerManager").writeEntry("LaunchCounts", "5 foo"); + cfg.sync(); + } + std::unique_ptr manager(new RunnerManager()); + manager->setAllowedRunners({QStringLiteral("fakerunnerplugin")}); + manager->loadRunner(KPluginMetaData::findPluginById(QStringLiteral("krunnertest"), QStringLiteral("fakerunnerplugin"))); + + launchQuery(QStringLiteral("foo"), manager.get()); + + const auto matches = manager->matches(); + QCOMPARE(matches.size(), 2); + QCOMPARE(matches.at(0).id(), QStringLiteral("foo")); + QCOMPARE(matches.at(1).id(), QStringLiteral("bar")); + QCOMPARE(matches.at(1).relevance(), 0.2); + + QVERIFY(matches.at(0).relevance() > matches.at(1).relevance()); + QVERIFY(matches.at(0).relevance() < 0.6); // 0.5 is the max we add as a bonus, 0.1 comes from the runner + { + KConfig cfg(stateConfigFile); + cfg.group("PlasmaRunnerManager").writeEntry("LaunchCounts", QStringList{"5 foo", "5 bar"}); + cfg.sync(); + KSharedConfig::openConfig(QStringLiteral("krunnerstaterc"), KConfig::NoGlobals, QStandardPaths::GenericDataLocation)->reparseConfiguration(); + } + manager = std::make_unique(); + manager->setAllowedRunners({QStringLiteral("fakerunnerplugin")}); + manager->loadRunner(KPluginMetaData::findPluginById(QStringLiteral("krunnertest"), QStringLiteral("fakerunnerplugin"))); + + launchQuery(QStringLiteral("foo"), manager.get()); + const auto newMatches = manager->matches(); + QCOMPARE(newMatches.size(), 2); + QVERIFY(newMatches.at(0).relevance() < newMatches.at(1).relevance()); +} + +QTEST_MAIN(RunnerManagerHistoryTest) + +#include "runnermanagerhistorytest.moc" diff --git a/autotests/runnermanagersinglerunnermodetest.cpp b/autotests/runnermanagersinglerunnermodetest.cpp new file mode 100644 index 0000000..8667cdd --- /dev/null +++ b/autotests/runnermanagersinglerunnermodetest.cpp @@ -0,0 +1,126 @@ +/* + SPDX-FileCopyrightText: 2021 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.1-or-later +*/ + +#include "runnermanager.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "abstractrunnertest.h" +#include "kpluginmetadata_utils_p.h" + +using namespace KRunner; + +class RunnerManagerSingleRunnerModeTest : public AbstractRunnerTest +{ + Q_OBJECT +private Q_SLOTS: + void loadTwoRunners() + { + startDBusRunnerProcess({QStringLiteral("net.krunnertests.dave")}); + startDBusRunnerProcess({QStringLiteral("net.krunnertests.multi.a1")}, QStringLiteral("net.krunnertests.multi.a1")); + qputenv("XDG_DATA_DIRS", QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation).toLocal8Bit()); + QCoreApplication::setLibraryPaths(QStringList()); + initProperties(); + auto md = parseMetaDataFromDesktopFile(QFINDTESTDATA("plugins/dbusrunnertestmulti.desktop")); + QVERIFY(md.isValid()); + manager->loadRunner(md); + } + + void cleanup() + { + killRunningDBusProcesses(); + const QString configFile = QStandardPaths::locate(QStandardPaths::ConfigLocation, "runnermanagersinglerunnermodetestrcm"); + if (!configFile.isEmpty()) { + QFile::remove(configFile); + } + } + + void testAllRunnerResults(); + void testSingleRunnerResults(); + void testNonExistentRunnerId(); + void testLoadingDisabledRunner(); +}; + +void RunnerManagerSingleRunnerModeTest::testAllRunnerResults() +{ + loadTwoRunners(); + launchQuery("foo"); + const auto matches = manager->matches(); + QCOMPARE(matches.count(), 2); + const QStringList ids = {matches.at(0).runner()->id(), matches.at(1).runner()->id()}; + // Both runners should have produced one result + QVERIFY(ids.contains("dbusrunnertest")); + QVERIFY(ids.contains("dbusrunnertestmulti")); +} + +void RunnerManagerSingleRunnerModeTest::testSingleRunnerResults() +{ + loadTwoRunners(); + launchQuery("foo", "dbusrunnertest"); + QCOMPARE(manager->matches().count(), 1); + QCOMPARE(manager->matches().constFirst().runner()->id(), "dbusrunnertest"); + launchQuery("foo", "dbusrunnertestmulti"); + QCOMPARE(manager->matches().count(), 1); + QCOMPARE(manager->matches().constFirst().runner()->id(), "dbusrunnertestmulti"); +} + +void RunnerManagerSingleRunnerModeTest::testNonExistentRunnerId() +{ + loadTwoRunners(); + manager->launchQuery("foo", "bla"); // This internally calls reset, we just wait a bit and make sure there are no matches + QTest::qSleep(250); + QVERIFY(manager->matches().isEmpty()); +} + +void RunnerManagerSingleRunnerModeTest::testLoadingDisabledRunner() +{ + loadTwoRunners(); + // Make sure the runner is disabled in the config + auto config = KSharedConfig::openConfig(); + config->deleteGroup("Plugins"); + config->group("Plugins").writeEntry("dbusrunnertestEnabled", false); + // reset our manager to start clean + manager = std::make_unique(config->group("Plugins"), config->group("State"), this); + // Ensure no system runners are picked up + manager->setAllowedRunners(QStringList{"dbusrunnertest", "dbusrunnertestmulti"}); + // Copy the service files to the appropriate location and only load runners from there + QString location = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/krunner/dbusplugins/"; + QDir().mkpath(location); + QFile::copy(QFINDTESTDATA("plugins/dbusrunnertest.desktop"), location + "dbusrunnertest.desktop"); + QFile::copy(QFINDTESTDATA("plugins/dbusrunnertestmulti.desktop"), location + "dbusrunnertestmulti.desktop"); + + // Only enabled runner should be loaded and have results + auto matches = launchQuery("foo"); + QCOMPARE(manager->runners().count(), 1); + QCOMPARE(manager->runners().constFirst()->id(), "dbusrunnertestmulti"); + QCOMPARE(matches.count(), 1); + QCOMPARE(matches.constFirst().runner()->id(), "dbusrunnertestmulti"); + + // Only enabled runner should be loaded and have results + matches = launchQuery("foo", "dbusrunnertest"); + QCOMPARE(manager->runners().count(), 2); + const QStringList ids{manager->runners().at(0)->id(), manager->runners().at(1)->id()}; + QVERIFY(ids.contains("dbusrunnertestmulti")); + QVERIFY(ids.contains("dbusrunnertest")); + QCOMPARE(matches.count(), 1); + QCOMPARE(matches.constFirst().runner()->id(), "dbusrunnertest"); + + // Only enabled runner should used for querying + matches = launchQuery("foo"); + QCOMPARE(manager->runners().count(), 2); + QCOMPARE(matches.count(), 1); + QCOMPARE(matches.constFirst().runner()->id(), "dbusrunnertestmulti"); +} + +QTEST_MAIN(RunnerManagerSingleRunnerModeTest) + +#include "runnermanagersinglerunnermodetest.moc" diff --git a/autotests/runnermanagertest.cpp b/autotests/runnermanagertest.cpp new file mode 100644 index 0000000..e7f0b84 --- /dev/null +++ b/autotests/runnermanagertest.cpp @@ -0,0 +1,178 @@ +/* + SPDX-FileCopyrightText: 2022 Eduardo Cruz + SPDX-License-Identifier: LGPL-2.1-or-later +*/ + +#include "runnermanager.h" + +#include +#include +#include +#include +#include +#include + +#include "abstractrunnertest.h" +#include "kpluginmetadata_utils_p.h" + +Q_DECLARE_METATYPE(KRunner::QueryMatch) +Q_DECLARE_METATYPE(QList) + +using namespace KRunner; +namespace KRunner +{ +extern int __changeCountBeforeSaving; +} + +class RunnerManagerTest : public AbstractRunnerTest +{ + Q_OBJECT +private Q_SLOTS: + void initTestCase() + { + __changeCountBeforeSaving = 1; + startDBusRunnerProcess({QStringLiteral("net.krunnertests.dave")}); + qputenv("XDG_DATA_DIRS", QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation).toLocal8Bit()); + QCoreApplication::setLibraryPaths(QStringList()); + initProperties(); + qRegisterMetaType>(); + } + + void cleanupTestCase() + { + killRunningDBusProcesses(); + } + + /** + * This will test the mechanismm that stalls for 250ms before emiting any result in RunnerManager::scheduleMatchesChanged() + * and the mechanism that anticipates the last results emission in RunnerManager::jobDone(). + */ + void testScheduleMatchesChanged() + { + QSignalSpy spyQueryFinished(manager.get(), &KRunner::RunnerManager::queryFinished); + QSignalSpy spyMatchesChanged(manager.get(), &KRunner::RunnerManager::matchesChanged); + + QVERIFY(spyQueryFinished.isValid()); + QVERIFY(spyMatchesChanged.isValid()); + + QCOMPARE(spyQueryFinished.count(), 0); + + // This will track the total execution time + QElapsedTimer timer; + timer.start(); + + // This special string will simulate a 300ms delay + manager->launchQuery("fooDelay300"); + + // However not yet a matcheschanged, it should be stalled for 250ms + QCOMPARE(spyMatchesChanged.count(), 0); + + // After 250ms it will emit with empty matches, we wait for that. + // We can't put a low upper limit on these wait() calls because the CI environment can be slow. + QVERIFY(spyMatchesChanged.wait()); // This should take just a tad longer than 250ms. + + // This should have taken no less than 250ms. It waits for 250s before "giving up" and emitting an empty matches list. + QVERIFY(timer.elapsed() >= 250); + QCOMPARE(spyMatchesChanged.count(), 1); + QCOMPARE(manager->matches().count(), 0); // This is the empty matches "reset" emission, result is not ready yet + QCOMPARE(spyQueryFinished.count(), 0); // Still the same, query is not done + + // We programmed it to emit the result after 300ms, so we need to wait 50ms more for the next emission + QVERIFY(spyQueryFinished.wait()); + + // This should have taken at least 300ms total, as we requested via the special query string + QVERIFY(timer.elapsed() >= 300); + + // At this point RunnerManager::jobDone() should have anticipated the final emission. + QCOMPARE(manager->matches().count(), 1); // The result is here + QCOMPARE(spyQueryFinished.count(), 1); // Will have emited queryFinished, job is done + QCOMPARE(spyMatchesChanged.count(), 2); // We had the second matchesChanged emission, now with the query result + + // Now we will make sure that RunnerManager::scheduleMatchesChanged() emits matchesChanged instantly + // if we start a query with an empty string. It will never produce results, stalling is meaningless + manager->launchQuery(""); + QCOMPARE(spyMatchesChanged.count(), 3); // One more, instantly, without stall + QCOMPARE(manager->matches().count(), 0); // Empty results for empty query string + QVERIFY(spyQueryFinished.wait()); + } + + /** + * This will test queryFinished signal from reset() is emitted when the previous runners are + * still running. + */ + void testQueryFinishedFromReset() + { + QSignalSpy spyQueryFinished(manager.get(), &KRunner::RunnerManager::queryFinished); + + manager->launchQuery("fooDelay1000"); + QTest::qSleep(500); + QCOMPARE(spyQueryFinished.size(), 0); + + manager->launchQuery("fooDelay300"); + QCOMPARE(spyQueryFinished.size(), 1); // From reset() + + QVERIFY(spyQueryFinished.wait()); + QCOMPARE(spyQueryFinished.size(), 2); + } + + /** + * When we delete the RunnerManager while a job is still running, we should not crash + */ + void testNotCrashWhenDeletingRunnerManager() + { + RunnerManager manager; + manager.setAllowedRunners({QStringLiteral("fakerunnerplugin")}); + manager.loadRunner(KPluginMetaData::findPluginById(QStringLiteral("krunnertest"), QStringLiteral("fakerunnerplugin"))); + + QCOMPARE(manager.runners().size(), 1); + + manager.launchQuery("somequery"); + } + + void testRunnerManagerStateGroups() + { + auto stateGrp = KSharedConfig::openConfig(QString(), KConfig::NoGlobals)->group("Testme"); + auto configGrp = KSharedConfig::openConfig(QString(), KConfig::NoGlobals)->group("Plugins"); + stateGrp.deleteGroup(); + RunnerManager manager(configGrp, stateGrp, this); + manager.setAllowedRunners({QStringLiteral("fakerunnerplugin")}); + manager.loadRunner(KPluginMetaData::findPluginById(QStringLiteral("krunnertest"), QStringLiteral("fakerunnerplugin"))); + QSignalSpy spyQueryFinished(&manager, &KRunner::RunnerManager::queryFinished); + + manager.launchQuery("foo"); + spyQueryFinished.wait(); + manager.run(manager.matches().constFirst()); + manager.matchSessionComplete(); + QCOMPARE(stateGrp.readEntry("LaunchCounts"), "1 foo"); + QCOMPARE(stateGrp.config()->groupList().size(), 1); + } + + void testRunnerSuspendWhileReloadingConfig() + { + RunnerManager manager; + manager.loadRunner(KPluginMetaData::findPluginById(QStringLiteral("krunnertest2"), QStringLiteral("suspendedrunnerplugin"))); + QCOMPARE(manager.runners().size(), 1); + + AbstractRunner *runner = manager.runners().constFirst(); + QVERIFY(runner->isMatchingSuspended()); + + QSignalSpy spy(&manager, &KRunner::RunnerManager::queryFinished); + manager.launchQuery("foo"); + QVERIFY2(spy.wait(), "RunnerManager did not emit the queryFinished signal"); + + QCOMPARE(manager.matches().size(), 1); + + QVERIFY(!runner->isMatchingSuspended()); + } + + void testAbstractRunnerTestTimeout() + { + QEXPECT_FAIL("", "This test is expected to fail", Continue); + const auto matches = launchQuery("fooDelay6000"); + QVERIFY(matches.isEmpty()); + } +}; + +QTEST_MAIN(RunnerManagerTest) + +#include "runnermanagertest.moc" diff --git a/autotests/runnermatchmethodstest.cpp b/autotests/runnermatchmethodstest.cpp new file mode 100644 index 0000000..8ef4cc4 --- /dev/null +++ b/autotests/runnermatchmethodstest.cpp @@ -0,0 +1,100 @@ +/* + SPDX-FileCopyrightText: 2021 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include "abstractrunner.h" +#include "plugins/fakerunner.h" +#include "runnermanager.h" + +#include +#include +#include + +#include "kpluginmetadata_utils_p.h" + +using namespace KRunner; + +inline QueryMatch createMatch(const QString &id, AbstractRunner *r = nullptr) +{ + QueryMatch m(r); + m.setId(id); + return m; +} + +class RunnerContextMatchMethodsTest : public QObject +{ + Q_OBJECT +public: + RunnerContextMatchMethodsTest(); + + std::unique_ptr ctx; + FakeRunner *runner1 = nullptr; + FakeRunner *runner2 = nullptr; +private Q_SLOTS: + void init() + { + ctx.reset(new RunnerContext()); + } + void testAdd(); + void testAddMulti(); + void testDuplicateIds(); +}; + +RunnerContextMatchMethodsTest::RunnerContextMatchMethodsTest() +{ + QStandardPaths::setTestModeEnabled(true); + const QByteArray defaultDataDirs = qEnvironmentVariableIsSet("XDG_DATA_DIRS") ? qgetenv("XDG_DATA_DIRS") : QByteArray("/usr/local:/usr"); + const QByteArray modifiedDataDirs = QFile::encodeName(QCoreApplication::applicationDirPath()) + QByteArrayLiteral("/data:") + defaultDataDirs; + qputenv("XDG_DATA_DIRS", modifiedDataDirs); + KPluginMetaData data1 = parseMetaDataFromDesktopFile(QFINDTESTDATA("plugins/metadatafile1.desktop")); + KPluginMetaData data2 = parseMetaDataFromDesktopFile(QFINDTESTDATA("plugins/metadatafile2.desktop")); + QVERIFY(data1.isValid()); + QVERIFY(data2.isValid()); + runner1 = new FakeRunner(this, data1); + runner2 = new FakeRunner(this, data2); +} + +void RunnerContextMatchMethodsTest::testAdd() +{ + QVERIFY(ctx->matches().isEmpty()); + QVERIFY(ctx->addMatch(createMatch(QStringLiteral("m1")))); + QVERIFY(ctx->addMatch(createMatch(QStringLiteral("m2")))); + QCOMPARE(ctx->matches().count(), 2); + QVERIFY(ctx->addMatch(createMatch(QStringLiteral("m3")))); + QCOMPARE(ctx->matches().count(), 3); +} + +void RunnerContextMatchMethodsTest::testAddMulti() +{ + QVERIFY(ctx->matches().isEmpty()); + QVERIFY(ctx->addMatches({createMatch(QStringLiteral("m1")), createMatch(QStringLiteral("m2"))})); + QCOMPARE(ctx->matches().count(), 2); +} + +void RunnerContextMatchMethodsTest::testDuplicateIds() +{ + const QueryMatch match1 = createMatch(QStringLiteral("id1"), runner1); + QVERIFY(ctx->addMatch(match1)); + const QueryMatch match2 = createMatch(QStringLiteral("id1"), runner2); + QVERIFY(ctx->addMatch(match2)); + const QueryMatch match3 = createMatch(QStringLiteral("id2"), runner1); + QVERIFY(ctx->addMatch(match3)); + const QueryMatch match4 = createMatch(QStringLiteral("id3"), runner2); + QVERIFY(ctx->addMatch(match4)); + const QueryMatch match5 = createMatch(QStringLiteral("id3"), runner2); + QVERIFY(ctx->addMatch(match5)); + + const QList matches = ctx->matches(); + QCOMPARE(matches.size(), 3); + // match2 should have replaced match1 + QCOMPARE(matches.at(0), match2); + QCOMPARE(matches.at(1), match3); + // match4 should not have been replaced, the runner does not have the weak property set + QCOMPARE(matches.at(2), match4); +} + +QTEST_MAIN(RunnerContextMatchMethodsTest) + +#include "runnermatchmethodstest.moc" diff --git a/autotests/testmetadataconversion.cpp b/autotests/testmetadataconversion.cpp new file mode 100644 index 0000000..a041ab4 --- /dev/null +++ b/autotests/testmetadataconversion.cpp @@ -0,0 +1,26 @@ +/* + SPDX-FileCopyrightText: 2021 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.1-or-later +*/ + +#include "kpluginmetadata_utils_p.h" +#include + +class TestMetaDataConversion : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void testMetaDataConversion() + { + const KPluginMetaData data = parseMetaDataFromDesktopFile(QFINDTESTDATA("plugins/plasma-runner-testconversionfile.desktop")); + QVERIFY(data.isValid()); + QCOMPARE(data.pluginId(), "testconversionfile"); + QCOMPARE(data.name(), "DBus runner test"); + QCOMPARE(data.description(), "Some Comment"); + } +}; + +QTEST_MAIN(TestMetaDataConversion) + +#include "testmetadataconversion.moc" diff --git a/autotests/threadingtest.cpp b/autotests/threadingtest.cpp new file mode 100644 index 0000000..ab81ee6 --- /dev/null +++ b/autotests/threadingtest.cpp @@ -0,0 +1,94 @@ +/* + SPDX-FileCopyrightText: 2023 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.1-or-later +*/ +#include +#include +#include + +using namespace KRunner; + +class ThreadingTest : public AbstractRunnerTest +{ + Q_OBJECT + + AbstractRunner *fakeRunner = nullptr; +private Q_SLOTS: + void init() + { + initProperties(); + startDBusRunnerProcess({QStringLiteral("net.krunnertests.dave")}); + fakeRunner = manager->loadRunner(KPluginMetaData::findPluginById("krunnertest", "fakerunnerplugin")); + QCOMPARE(manager->runners().size(), 2); + } + void cleanup() + { + killRunningDBusProcesses(); + } + + void testParallelQuerying() + { + constexpr int trottlingDelay = 250; + manager->launchQuery("fooDelay300"); + + QSignalSpy changedSpy(manager.get(), &RunnerManager::matchesChanged); + QSignalSpy finishedSpy(manager.get(), &RunnerManager::queryFinished); + QVERIFY(changedSpy.wait(trottlingDelay + 10)); // Due to throttling, otherwise we'd have this signal after 50 ms + QCOMPARE(finishedSpy.count(), 0); + + const auto matches = manager->matches(); + QCOMPARE(matches.size(), 2); + QVERIFY(std::all_of(matches.begin(), matches.end(), [this](QueryMatch m) { + return m.runner() == fakeRunner; + })); + + QVERIFY(finishedSpy.wait(trottlingDelay - 5)); + QCOMPARE(changedSpy.count(), 2); + + QCOMPARE(manager->matches().size(), 3); + } + + void testDeletionOfRunningJob() + { + QPointer ptr(fakeRunner); + manager->setAllowedRunners({"fakerunnerplugin"}); + manager->launchQuery("foo"); + QThread::msleep(1); // Wait for runner to be invoked and query started + + QEventLoop loop; + QTimer::singleShot(500, &loop, &QEventLoop::quit); + + QVERIFY(manager->querying()); + manager.reset(nullptr); + QVERIFY(ptr); // Runner should not be deleted or reset now + + loop.exec(); + QVERIFY(!ptr); + } + + void testTeardownWhileJobIsRunning() + { + manager->launchQuery("fooDelay500"); + manager->matchSessionComplete(); + QSignalSpy spy(fakeRunner, &AbstractRunner::teardown); + QSignalSpy dbusSpy(manager->runners().constFirst(), &AbstractRunner::teardown); + spy.wait(100); + QCOMPARE(dbusSpy.count(), 0); // Should not be called due to the match fimeout + } + + void benchmarkQuerying() + { + QSKIP("Skipped by default"); + QStandardPaths::setTestModeEnabled(false); + manager.reset(new RunnerManager()); + QBENCHMARK_ONCE { + launchQuery("test"); + launchQuery("spell bla"); + launchQuery("define test"); + } + } +}; + +QTEST_MAIN(ThreadingTest) + +#include "threadingtest.moc" diff --git a/docs/Doxyfile.local b/docs/Doxyfile.local new file mode 100644 index 0000000..1fa2df3 --- /dev/null +++ b/docs/Doxyfile.local @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: none +# SPDX-License-Identifier: CC0-1.0 + +### KApiDox Project-specific Overrides File + +# define so that deprecated API is not skipped +PREDEFINED += \ + "KRUNNER_ENABLE_DEPRECATED_SINCE(x, y)=1" \ + "KRUNNER_BUILD_DEPRECATED_SINCE(x, y)=1" \ + "KRUNNER_DEPRECATED_VERSION(x, y, t)=" \ + "KRUNNER_ENUMERATOR_DEPRECATED_VERSION(x, y, t)=" \ + "KRUNNER_DEPRECATED_VERSION_BELATED(x, y, xt, yt, t)=" diff --git a/metainfo.yaml b/metainfo.yaml new file mode 100644 index 0000000..edb706b --- /dev/null +++ b/metainfo.yaml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: none +# SPDX-License-Identifier: CC0-1.0 + +description: Parallelized query system +tier: 3 +type: solution +platforms: + - name: Linux + - name: FreeBSD +portingAid: false +deprecated: false +release: true +libraries: + - cmake: "KF6::Runner" +cmakename: KF6Runner + +public_lib: true +group: Frameworks +subgroup: Tier 3 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..36b5b42 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,146 @@ +# SPDX-FileCopyrightText: KDE Contributors +# SPDX-License-Identifier: BSD-2-Clause + +add_library(KF6Runner SHARED) +add_library(KF6::Runner ALIAS KF6Runner) + +set_target_properties(KF6Runner PROPERTIES + VERSION ${KRUNNER_VERSION} + SOVERSION ${KRUNNER_SOVERSION} + EXPORT_NAME Runner +) + +target_sources(KF6Runner PRIVATE + abstractrunner.cpp + abstractrunner.h + abstractrunnertest.h + dbusrunner.cpp + dbusrunner_p.h + dbusutils_p.h + querymatch.cpp + querymatch.h + runnercontext.cpp + runnercontext.h + runnermanager.cpp + runnermanager.h + runnersyntax.cpp + runnersyntax.h + action.h + action.cpp + + model/runnerresultsmodel.cpp + model/runnerresultsmodel_p.h + model/resultsmodel.cpp + model/resultsmodel.h +) +ecm_qt_declare_logging_category(KF6Runner + HEADER krunner_debug.h + IDENTIFIER KRUNNER + CATEGORY_NAME kf.runner + OLD_CATEGORY_NAMES org.kde.krunner + DESCRIPTION "KRunner" + EXPORT KRUNNER +) +set_property(SOURCE "data/org.kde.krunner1.xml" PROPERTY INCLUDE dbusutils_p.h) + +ecm_generate_export_header(KF6Runner + BASE_NAME KRunner + GROUP_BASE_NAME KF + VERSION ${KF_VERSION} + USE_VERSION_HEADER + DEPRECATED_BASE_VERSION 0 + DEPRECATION_VERSIONS + EXCLUDE_DEPRECATED_BEFORE_AND_AT ${EXCLUDE_DEPRECATED_BEFORE_AND_AT} +) + +set(KRunner_BUILD_INCLUDE_DIRS ${KRunner_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}) +target_include_directories(KF6Runner INTERFACE "$") +target_include_directories(KF6Runner PUBLIC "$") + + +target_link_libraries(KF6Runner + PUBLIC + Qt6::Core + KF6::CoreAddons # KPluginFactory + PRIVATE + Qt6::DBus + Qt6::Gui + KF6::ConfigCore + KF6::I18n + KF6::ItemModels +) +ecm_generate_headers(KRunner_CamelCase_HEADERS + HEADER_NAMES + AbstractRunner + Action + RunnerContext + RunnerManager + RunnerSyntax + QueryMatch + AbstractRunnerTest + + PREFIX KRunner + REQUIRED_HEADERS KRunner_HEADERS +) +ecm_generate_headers(KRunner_CamelCase_HEADERS + HEADER_NAMES ResultsModel + PREFIX KRunner + REQUIRED_HEADERS KRunner_HEADERS + RELATIVE model +) + +# Install files + +install(TARGETS KF6Runner + EXPORT KF6RunnerTargets + ${KF_INSTALL_TARGETS_DEFAULT_ARGS}) + +install(FILES ${KRunner_CamelCase_HEADERS} + DESTINATION ${KDE_INSTALL_INCLUDEDIR_KF}/KRunner/KRunner + COMPONENT Devel) + +install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/krunner_export.h + ${KRunner_HEADERS} + DESTINATION ${KDE_INSTALL_INCLUDEDIR_KF}/KRunner/krunner + COMPONENT Devel) + +ecm_qt_install_logging_categories( + EXPORT KRUNNER + FILE krunner.categories + DESTINATION ${KDE_INSTALL_LOGGINGCATEGORIESDIR} +) + + +if(BUILD_QCH) + ecm_add_qch( + KF6Runner_QCH + NAME KRunner + BASE_NAME KF6Runner + VERSION ${KF_VERSION} + ORG_DOMAIN org.kde + SOURCES # using only public headers, to cover only public API + ${KRunner_HEADERS} + MD_MAINPAGE "${CMAKE_SOURCE_DIR}/README.md" + LINK_QCHS + Qt6Core_QCH + KF6CoreAddons_QCH + INCLUDE_DIRS + ${KRunner_BUILD_INCLUDE_DIRS} + BLANK_MACROS + KRUNNER_EXPORT + KRUNNER_DEPRECATED + KRUNNER_DEPRECATED_EXPORT + "KRUNNER_DEPRECATED_VERSION(x, y, t)" + "KRUNNER_DEPRECATED_VERSION_BELATED(x, y, xt, yt, t)" + "KRUNNER_ENUMERATOR_DEPRECATED_VERSION(x, y, t)" + TAGFILE_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR} + QCH_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR} + COMPONENT Devel + ) +endif() + +install(FILES + "data/org.kde.krunner1.xml" + DESTINATION ${KDE_INSTALL_DBUSINTERFACEDIR} + RENAME kf6_org.kde.krunner1.xml) diff --git a/src/abstractrunner.cpp b/src/abstractrunner.cpp new file mode 100644 index 0000000..b3d953e --- /dev/null +++ b/src/abstractrunner.cpp @@ -0,0 +1,190 @@ +/* + SPDX-FileCopyrightText: 2006-2007 Aaron Seigo + SPDX-FileCopyrightText: 2020-2023 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include "abstractrunner.h" +#include "abstractrunner_p.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace KRunner +{ +AbstractRunner::AbstractRunner(QObject *parent, const KPluginMetaData &pluginMetaData) + : QObject(nullptr) + , d(new AbstractRunnerPrivate(this, pluginMetaData)) +{ + // By now, runners who do "qobject_cast(parent)" should have saved the value + // By setting the parent to a nullptr, we are allowed to move the object to another thread + Q_ASSERT(parent); + setObjectName(pluginMetaData.pluginId()); // Only for debugging purposes + + // Suspend matching while we initialize the runner. Once it is ready, the last query will be run + QTimer::singleShot(0, this, [this]() { + init(); + // In case the runner didn't specify anything explicitly, we resume matching after the initialization + bool doesNotHaveExplicitSuspend = true; + { + QReadLocker l(&d->lock); + doesNotHaveExplicitSuspend = !d->suspendMatching.has_value(); + } + if (doesNotHaveExplicitSuspend) { + suspendMatching(false); + } + }); +} + +AbstractRunner::~AbstractRunner() = default; + +KConfigGroup AbstractRunner::config() const +{ + KConfigGroup runners(KSharedConfig::openConfig(QStringLiteral("krunnerrc")), QStringLiteral("Runners")); + return runners.group(id()); +} + +void AbstractRunner::reloadConfiguration() +{ +} + +void AbstractRunner::addSyntax(const RunnerSyntax &syntax) +{ + d->syntaxes.append(syntax); +} + +void AbstractRunner::setSyntaxes(const QList &syntaxes) +{ + d->syntaxes = syntaxes; +} + +QList AbstractRunner::syntaxes() const +{ + return d->syntaxes; +} + +QMimeData *AbstractRunner::mimeDataForMatch(const QueryMatch &match) +{ + if (match.urls().isEmpty()) { + return nullptr; + } + QMimeData *result = new QMimeData(); + result->setUrls(match.urls()); + return result; +} + +void AbstractRunner::run(const KRunner::RunnerContext & /*search*/, const KRunner::QueryMatch & /*action*/) +{ +} + +QString AbstractRunner::name() const +{ + return d->translatedName; +} + +QString AbstractRunner::id() const +{ + return d->runnerDescription.pluginId(); +} + +KPluginMetaData AbstractRunner::metadata() const +{ + return d->runnerDescription; +} + +void AbstractRunner::init() +{ + reloadConfiguration(); +} + +bool AbstractRunner::isMatchingSuspended() const +{ + QReadLocker lock(&d->lock); + return d->suspendMatching.value_or(true); +} + +void AbstractRunner::suspendMatching(bool suspend) +{ + QWriteLocker lock(&d->lock); + if (d->suspendMatching.has_value() && d->suspendMatching.value() == suspend) { + return; + } + + d->suspendMatching = suspend; + if (!suspend) { + Q_EMIT matchingResumed(); + } +} + +int AbstractRunner::minLetterCount() const +{ + return d->minLetterCount; +} + +void AbstractRunner::setMinLetterCount(int count) +{ + d->minLetterCount = count; +} + +QRegularExpression AbstractRunner::matchRegex() const +{ + return d->matchRegex; +} + +void AbstractRunner::setMatchRegex(const QRegularExpression ®ex) +{ + d->matchRegex = regex; + d->hasMatchRegex = regex.isValid() && !regex.pattern().isEmpty(); +} + +void AbstractRunner::setTriggerWords(const QStringList &triggerWords) +{ + int minTriggerWordLetters = 0; + QString constructedRegex = QStringLiteral("^"); + for (const QString &triggerWord : triggerWords) { + // We want to link them with an or + if (constructedRegex.length() > 1) { + constructedRegex += QLatin1Char('|'); + } + constructedRegex += QRegularExpression::escape(triggerWord); + if (minTriggerWordLetters == 0 || triggerWord.length() < minTriggerWordLetters) { + minTriggerWordLetters = triggerWord.length(); + } + } + // If we can reject the query because of the length we don't need the regex + setMinLetterCount(minTriggerWordLetters); + setMatchRegex(QRegularExpression(constructedRegex)); +} + +bool AbstractRunner::hasMatchRegex() const +{ + return d->hasMatchRegex; +} + +void AbstractRunner::matchInternal(KRunner::RunnerContext context) +{ + if (context.isValid()) { // Otherwise, we would just waste resources + match(context); + } + Q_EMIT matchInternalFinished(context.runnerJobId(this)); +} +// Suspend the runner while reloading the config +void AbstractRunner::reloadConfigurationInternal() +{ + bool isSuspended = isMatchingSuspended(); + suspendMatching(true); + reloadConfiguration(); + suspendMatching(isSuspended); +} + +} // KRunner namespace + +#include "moc_abstractrunner.cpp" diff --git a/src/abstractrunner.h b/src/abstractrunner.h new file mode 100644 index 0000000..07308e2 --- /dev/null +++ b/src/abstractrunner.h @@ -0,0 +1,301 @@ +/* + SPDX-FileCopyrightText: 2006-2007 Aaron Seigo + SPDX-FileCopyrightText: 2020-2023 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#ifndef KRUNNER_ABSTRACTRUNNER_H +#define KRUNNER_ABSTRACTRUNNER_H + +#include "krunner_export.h" + +#include +#include + +#include +#include + +#include + +#include "querymatch.h" +#include "runnercontext.h" +#include "runnersyntax.h" + +class KConfigGroup; +class QMimeData; +class QRegularExpression; +class QIcon; + +namespace KRunner +{ +class AbstractRunnerPrivate; + +/** + * @class AbstractRunner abstractrunner.h + * + * @short An abstract base class for Plasma Runner plugins. + * + * Be aware that runners will be moved to their own thread after being instantiated. + * This means that except for AbstractRunner::run and the constructor, all methods will be non-blocking + * for the UI. + * Consider doing heavy resource initialization in the init method instead of the constructor. + */ +class KRUNNER_EXPORT AbstractRunner : public QObject +{ + Q_OBJECT + +public: + ~AbstractRunner() override; + + /** + * This is the main query method. It should trigger creation of + * QueryMatch instances through RunnerContext::addMatch and + * RunnerContext::addMatches. + * + * If the runner can run precisely the requested term (RunnerContext::query()), + * it should create an exact match by setting the type to RunnerContext::ExactMatch. + * The first runner that creates a QueryMatch will be the + * default runner. Other runner's matches will be suggested in the + * interface. Non-exact matches should be offered via RunnerContext::PossibleMatch. + * + * The match will be activated via run() if the user selects it. + * + * All matches need to be reported once this method returns. Asynchronous runners therefore need + * to make use of a local event loop to wait for all matches. + * + * It is recommended to use local status data in async runners. The simplest way is + * to have a separate class doing all the work like so: + * + * \code + * void MyFancyAsyncRunner::match(RunnerContext &context) + * { + * QEventLoop loop; + * MyAsyncWorker worker(context); + * connect(&worker, &MyAsyncWorker::finished, &loop, &MyAsyncWorker::quit); + * worker.work(); + * loop.exec(); + * } + * \endcode + * + * Here MyAsyncWorker creates all the matches and calls RunnerContext::addMatch + * in some internal slot. It emits the finished() signal once done which will + * quit the loop and make the match() method return. + * + * Execution of the correct action should be handled in the run method. + * + * @warning Returning from this method means to end execution of the runner. + * + * @sa run(), RunnerContext::addMatch, RunnerContext::addMatches, QueryMatch + */ + virtual void match(KRunner::RunnerContext &context) = 0; + + /** + * Called whenever an exact or possible match associated with this + * runner is triggered. + * + * @param context The context in which the match is triggered, i.e. for which + * the match was created. + * @param match The actual match to run/execute. + */ + virtual void run(const KRunner::RunnerContext &context, const KRunner::QueryMatch &match); + + /** + * @return the plugin metadata for this runner that was passed in the constructor + */ + KPluginMetaData metadata() const; + + /** + * Returns the translated name from the runner's metadata + */ + QString name() const; + + /** + * @return an id from the runner's metadata' + */ + QString id() const; + + /** + * Reloads the runner's configuration. This is called when it's KCM in the PluginSelector is applied. + * This function may be used to set for example using setMatchRegex, setMinLetterCount or setTriggerWords. + * Also, syntaxes should be updated when this method is called. + * While reloading the config, matching is suspended. + */ + virtual void reloadConfiguration(); + + /** + * @return the syntaxes the runner has registered that it accepts and understands + */ + QList syntaxes() const; + + /** + * @return true if the runner is currently busy with non-interuptable work, signaling that + * the RunnerManager may not query it or read it's config properties + */ + bool isMatchingSuspended() const; + + /** + * This is the minimum letter count for the query. If the query is shorter than this value + * and KRunner is not in the singleRunnerMode, match method is not called. + * This can be set using the X-Plasma-Runner-Min-Letter-Count property or the setMinLetterCount method. + * The default value is 0. + * + * @see setMinLetterCount + * @see match + * @since 5.75 + */ + int minLetterCount() const; + + /** + * Set the minLetterCount property + * @param count + * @since 5.75 + */ + void setMinLetterCount(int count); + + /** + * If this regex is set with a non empty pattern it must match the query in order for match being called. + * Just like the minLetterCount property this check is ignored when the runner is in the singleRunnerMode. + * In case both the regex and the letter count is set the letter count is checked first. + * @return matchRegex property + * @see hasMatchRegex + * @since 5.75 + */ + QRegularExpression matchRegex() const; + + /** + * Set the matchRegex property + * @param regex + * @since 5.75 + */ + void setMatchRegex(const QRegularExpression ®ex); + + /** + * Constructs internally a regex which requires the query to start with the trigger words. + * Multiple words are concatenated with or, for instance: "^word1|word2|word3". + * The trigger words are internally escaped. + * Also the minLetterCount is set to the shortest word in the list. + * @since 5.75 + * @see matchRegex + */ + void setTriggerWords(const QStringList &triggerWords); + + /** + * If the runner has a valid regex and non empty regex + * @internal + * @since 5.75 + */ + bool hasMatchRegex() const; + +Q_SIGNALS: + /** + * This signal is emitted when matching is about to commence, giving runners + * an opportunity to prepare themselves, e.g. loading data sets or preparing + * IPC or network connections. Things that should be loaded once and remain + * extant for the lifespan of the AbstractRunner should be done in init(). + * @see init() + */ + void prepare(); + + /** + * This signal is emitted when a session of matches is complete, giving runners + * the opportunity to tear down anything set up as a result of the prepare() + * method. + */ + void teardown(); + +protected: + friend class RunnerManager; + friend class RunnerManagerPrivate; + + /** + * Constructor for a KRunner plugin + * + * @note You should connect here to the prepare/teardown signals. However, avoid doing heavy initialization here + * in favor of doing it in AbstractRunner::init + * + * @param parent parent object for this runner + * @param pluginMetaData metadata that was embedded in the runner + * @param args for compatibility with KPluginFactory, since 6.0 this can be omitted + * @since 5.72 + */ + explicit AbstractRunner(QObject *parent, const KPluginMetaData &pluginMetaData); + + /** + * Sets whether or not the runner is available for match requests. Useful to + * prevent queries when the runner is in a busy state. + * @note Do not permanently suspend the runner. This is only intended as a temporary measure to + * avoid useless queries being launched or async fetching of config/data being interfered with. + */ + void suspendMatching(bool suspend); + + /** + * Provides access to the runner's configuration object. + * This config is saved in the "krunnerrc" file in the [Runners][] config group + * Settings should be written in a KDE config module. See https://develop.kde.org/docs/plasma/krunner/#runner-configuration + */ + KConfigGroup config() const; + + /** + * Adds a registered syntax that this runner understands. This is used to + * display to the user what this runner can understand and how it can be + * used. + * + * @param syntax the syntax to register + */ + void addSyntax(const RunnerSyntax &syntax); + + /** + * Utility overload for creating a syntax based on the given parameters + * @see RunnerSyntax + * @since 5.106 + */ + inline void addSyntax(const QString &exampleQuery, const QString &description) + { + addSyntax(QStringList(exampleQuery), description); + } + + /// @copydoc addSyntax(const QString &exampleQuery, const QString &description) + inline void addSyntax(const QStringList &exampleQueries, const QString &description) + { + addSyntax(KRunner::RunnerSyntax(exampleQueries, description)); + } + + /** + * Sets the list of syntaxes; passing in an empty list effectively clears + * the syntaxes. + * + * @param the syntaxes to register for this runner + */ + void setSyntaxes(const QList &syntaxes); + + /** + * Reimplement this to run any initialization routines on first load. + * Because it is executed in the runner's thread, it will not block the UI and is thus preferred. + * By default, it calls reloadConfiguration(); + * + * Until the runner is initialized, it will not be queried by the RunnerManager. + */ + virtual void init(); + + /** + * Reimplement this if you want your runner to support serialization and drag and drop. + * By default, this sets the QMimeData urls to the ones specified in @ref QueryMatch::urls + */ + virtual QMimeData *mimeDataForMatch(const KRunner::QueryMatch &match); + +private: + std::unique_ptr const d; + KRUNNER_NO_EXPORT Q_INVOKABLE void matchInternal(KRunner::RunnerContext context); + KRUNNER_NO_EXPORT Q_INVOKABLE void reloadConfigurationInternal(); + KRUNNER_NO_EXPORT Q_SIGNAL void matchInternalFinished(const QString &jobId); + KRUNNER_NO_EXPORT Q_SIGNAL void matchingResumed(); + friend class RunnerManager; + friend class RunnerContext; + friend class RunnerContextPrivate; + friend class QueryMatchPrivate; + friend class DBusRunner; // Because it "overrides" matchInternal +}; + +} // KRunner namespace +#endif diff --git a/src/abstractrunner_p.h b/src/abstractrunner_p.h new file mode 100644 index 0000000..75385f3 --- /dev/null +++ b/src/abstractrunner_p.h @@ -0,0 +1,43 @@ +/* + SPDX-FileCopyrightText: 2020-2023 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.0-or-later +*/ +#include "abstractrunner.h" +#include "runnersyntax.h" +#include +#include +#include + +namespace KRunner +{ +class AbstractRunnerPrivate +{ +public: + explicit AbstractRunnerPrivate(AbstractRunner *r, const KPluginMetaData &data) + : runnerDescription(data) + , translatedName(data.name()) + , runner(r) + , minLetterCount(data.value(QStringLiteral("X-Plasma-Runner-Min-Letter-Count"), 0)) + , hasUniqueResults(data.value(QStringLiteral("X-Plasma-Runner-Unique-Results"), false)) + , hasWeakResults(data.value(QStringLiteral("X-Plasma-Runner-Weak-Results"), false)) + { + if (const QString regexStr = data.value(QStringLiteral("X-Plasma-Runner-Match-Regex")); !regexStr.isEmpty()) { + matchRegex = QRegularExpression(regexStr); + hasMatchRegex = matchRegex.isValid() && !matchRegex.pattern().isEmpty(); + } + } + + QReadWriteLock lock; + const KPluginMetaData runnerDescription; + // We can easily call this a few hundred times for a few queries. Thus just reuse the value and not do a lookup of the translated string every time + const QString translatedName; + const AbstractRunner *runner; + QList syntaxes; + std::optional suspendMatching; + int minLetterCount = 0; + QRegularExpression matchRegex; + bool hasMatchRegex = false; + const bool hasUniqueResults = false; + const bool hasWeakResults = false; +}; +} diff --git a/src/abstractrunnertest.h b/src/abstractrunnertest.h new file mode 100644 index 0000000..ab6dc22 --- /dev/null +++ b/src/abstractrunnertest.h @@ -0,0 +1,149 @@ +/* + SPDX-FileCopyrightText: 2020 Alexander Lohnau + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#ifndef KRUNNER_ABSTRACTRUNNERTEST_H +#define KRUNNER_ABSTRACTRUNNERTEST_H + +#include +#include +#include +#include + +#include +#include +#if KRUNNER_DBUS_RUNNER_TESTING +#include +#include +#include +#include +#include +#endif + +namespace KRunner +{ +/** + * This class provides a basic structure for a runner test. + * The compile definitions should be configured using the `krunner_configure_test` cmake macro + * @since 5.80 + */ +class AbstractRunnerTest : public QObject +{ +public: + using QObject::QObject; + std::unique_ptr manager = nullptr; + KRunner::AbstractRunner *runner = nullptr; + + /** + * Load the runner and set the manager and runner properties. + */ + void initProperties() + { + qputenv("LC_ALL", "C.utf-8"); + manager.reset(new KRunner::RunnerManager()); + +#if KRUNNER_DBUS_RUNNER_TESTING + auto md = manager->convertDBusRunnerToJson(QStringLiteral(KRUNNER_TEST_DESKTOP_FILE)); + QVERIFY(md.isValid()); + manager->loadRunner(md); +#else + const QString pluginId = QFileInfo(QStringLiteral(KRUNNER_TEST_RUNNER_PLUGIN_NAME)).completeBaseName(); + auto metaData = KPluginMetaData::findPluginById(QStringLiteral(KRUNNER_TEST_RUNNER_PLUGIN_DIR), pluginId); + QVERIFY2(metaData.isValid(), + qPrintable(QStringLiteral("Could not find plugin %1 in folder %2").arg(pluginId, QStringLiteral(KRUNNER_TEST_RUNNER_PLUGIN_DIR)))); + + // Set internal variables + manager->loadRunner(metaData); +#endif + QCOMPARE(manager->runners().count(), 1); + runner = manager->runners().constFirst(); + + // Just make sure all went well + QVERIFY(runner); + } + + /** + * Launch a query and wait for the RunnerManager to finish + * @param query + * @param runnerName + * @return matches of the current query + */ + QList launchQuery(const QString &query, const QString &runnerName = QString()) + { + QSignalSpy spy(manager.get(), &KRunner::RunnerManager::queryFinished); + manager->launchQuery(query, runnerName); + if (!QTest::qVerify(spy.wait(), "spy.wait()", "RunnerManager did not emit the queryFinished signal", __FILE__, __LINE__)) { + return {}; + } + return manager->matches(); + } +#if KRUNNER_DBUS_RUNNER_TESTING + /** + * Launch the configured DBus executable with the given arguments and wait for the process to be started. + * @param args + * @param waitForService Wait for this service to be registered, this will default to the service from the metadata + * @return Process that was successfully started + */ + QProcess *startDBusRunnerProcess(const QStringList &args = {}, const QString waitForService = QString()) + { + qputenv("LC_ALL", "C.utf-8"); + QProcess *process = new QProcess(); + auto md = manager->convertDBusRunnerToJson(QStringLiteral(KRUNNER_TEST_DESKTOP_FILE)); + QString serviceToWatch = waitForService; + if (serviceToWatch.isEmpty()) { + serviceToWatch = md.value(QStringLiteral("X-Plasma-DBusRunner-Service")); + } + QEventLoop loop; + // Wait for the service to show up. Same logic as the dbusrunner + connect(QDBusConnection::sessionBus().interface(), + &QDBusConnectionInterface::serviceOwnerChanged, + &loop, + [&loop, serviceToWatch](const QString &serviceName, const QString &, const QString &newOwner) { + if (serviceName == serviceToWatch && !newOwner.isEmpty()) { + loop.quit(); + } + }); + + // Otherwise, we just wait forever without any indication what we are waiting for + QTimer::singleShot(10000, &loop, [&loop, process]() { + loop.quit(); + + if (process->state() == QProcess::ProcessState::NotRunning) { + qWarning() << "stderr of" << KRUNNER_TEST_DBUS_EXECUTABLE << "is:"; + qWarning().noquote() << process->readAllStandardError(); + } + Q_ASSERT_X(false, "AbstractRunnerTest::startDBusRunnerProcess", "DBus service was not registered within 10 seconds"); + }); + process->start(QStringLiteral(KRUNNER_TEST_DBUS_EXECUTABLE), args); + loop.exec(); + process->waitForStarted(5); + + Q_ASSERT(process->state() == QProcess::ProcessState::Running); + m_runningProcesses << process; + return process; + } + + /** + * Kill all processes that got started with the startDBusRunnerProcess + */ + void killRunningDBusProcesses() + { + for (auto &process : std::as_const(m_runningProcesses)) { + process->kill(); + QVERIFY(process->waitForFinished()); + if (QTest::currentTestFailed()) { + qWarning().noquote() << "Output from " << process->program() << ": " << process->readAll(); + } + } + qDeleteAll(m_runningProcesses); + m_runningProcesses.clear(); + } + +private: + QList m_runningProcesses; +#endif +}; +} + +#endif diff --git a/src/action.cpp b/src/action.cpp new file mode 100644 index 0000000..ad4061d --- /dev/null +++ b/src/action.cpp @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: 2023 Alexander Lohnau +// SPDX-License-Identifier: LGPL-2.0-or-later +#include "action.h" + +#include + +namespace KRunner +{ +class ActionPrivate +{ +public: + explicit ActionPrivate(const QString id, const QString text, const QString iconName) + : m_id(id) + , m_text(text) + , m_iconSource(iconName) + { + } + explicit ActionPrivate() = default; + explicit ActionPrivate(const ActionPrivate &action) = default; + const QString m_id; + const QString m_text; + const QString m_iconSource; +}; + +Action::Action(const QString &id, const QString &iconName, const QString &text) + : d(new ActionPrivate(id, text, iconName)) +{ +} +Action::Action(const Action &action) + : d(new ActionPrivate(*action.d)) +{ +} +Action::Action() + : d(new ActionPrivate()) +{ +} + +Action::~Action() = default; +Action &Action::operator=(const Action &other) +{ + d.reset(new ActionPrivate(*other.d)); + return *this; +} + +QString Action::id() const +{ + return d->m_id; +} +QString Action::text() const +{ + return d->m_text; +} +QString Action::iconSource() const +{ + return d->m_iconSource; +} +} + +#include "moc_action.cpp" diff --git a/src/action.h b/src/action.h new file mode 100644 index 0000000..4c0637b --- /dev/null +++ b/src/action.h @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: 2023 Alexander Lohnau +// SPDX-License-Identifier: LGPL-2.0-or-later +#ifndef KRUNNER_ACTION_H +#define KRUNNER_ACTION_H + +#include "krunner_export.h" + +#include +#include +#include + +namespace KRunner +{ +class ActionPrivate; +/** + * This class represents an action that will be shown next to a match. + * The goal is to make it more reliable, because QIcon::fromTheme which is often needed in a QAction constructor is not thread safe. + * Also, it makes the API more consistent with the org.kde.krunner1 DBus interface and forces consumers to set an icon. + * + * @since 6.0 + */ +class KRUNNER_EXPORT Action final +{ + Q_GADGET + /// User-visible text + Q_PROPERTY(QString text READ text CONSTANT) + /// Source for the icon: Name of the icon from a theme, file path or file URL + Q_PROPERTY(QString iconSource READ iconSource CONSTANT) +public: + /** + * Constructs a new action + * @param id ID which identifies the action uniquely within the context of the respective runner plugin + * @param iconSource name for the icon, that can be passed in to QIcon::fromTheme or file path/URL + */ + explicit Action(const QString &id, const QString &iconSource, const QString &text); + + /// Empty constructor creating invalid action + Action(); + + ~Action(); + + /** + * Copy constructor + * @internal + */ + Action(const KRunner::Action &other); + + Action &operator=(const Action &other); + + /// Check if the action is valid + explicit operator bool() const + { + return !id().isEmpty(); + } + + bool operator==(const KRunner::Action &other) const + { + return id() == other.id(); + } + + QString id() const; + QString text() const; + QString iconSource() const; + +private: + std::unique_ptr d; +}; + +using Actions = QList; +} + +Q_DECLARE_METATYPE(KRunner::Action) +#endif diff --git a/src/data/org.kde.krunner1.xml b/src/data/org.kde.krunner1.xml new file mode 100644 index 0000000..b61ffe0 --- /dev/null +++ b/src/data/org.kde.krunner1.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/dbusrunner.cpp b/src/dbusrunner.cpp new file mode 100644 index 0000000..bb8c5a3 --- /dev/null +++ b/src/dbusrunner.cpp @@ -0,0 +1,343 @@ +/* + SPDX-FileCopyrightText: 2017, 2018 David Edmundson + SPDX-FileCopyrightText: 2020 Alexander Lohnau + SPDX-FileCopyrightText: 2020 Kai Uwe Broulik + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include "dbusrunner_p.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "dbusutils_p.h" +#include "krunner_debug.h" + +namespace KRunner +{ +DBusRunner::DBusRunner(QObject *parent, const KPluginMetaData &data) + : KRunner::AbstractRunner(parent, data) + , m_path(data.value(QStringLiteral("X-Plasma-DBusRunner-Path"), QStringLiteral("/runner"))) + , m_hasUniqueResults(data.value(QStringLiteral("X-Plasma-Runner-Unique-Results"), false)) + , m_requestActionsOnce(data.value(QStringLiteral("X-Plasma-Request-Actions-Once"), false)) + , m_callLifecycleMethods(data.value(QStringLiteral("X-Plasma-API")) == QLatin1String("DBus2")) + , m_ifaceName(QStringLiteral("org.kde.krunner1")) +{ + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + + QString requestedServiceName = data.value(QStringLiteral("X-Plasma-DBusRunner-Service")); + if (requestedServiceName.isEmpty() || m_path.isEmpty()) { + qCWarning(KRUNNER) << "Invalid entry:" << data; + return; + } + + if (requestedServiceName.endsWith(QLatin1Char('*'))) { + requestedServiceName.chop(1); + // find existing matching names + auto namesReply = QDBusConnection::sessionBus().interface()->registeredServiceNames(); + if (namesReply.isValid()) { + const auto names = namesReply.value(); + for (const QString &serviceName : names) { + if (serviceName.startsWith(requestedServiceName)) { + m_matchingServices << serviceName; + } + } + } + // and watch for changes + connect(QDBusConnection::sessionBus().interface(), + &QDBusConnectionInterface::serviceOwnerChanged, + this, + [this, requestedServiceName](const QString &serviceName, const QString &oldOwner, const QString &newOwner) { + if (!serviceName.startsWith(requestedServiceName)) { + return; + } + if (!oldOwner.isEmpty() && !newOwner.isEmpty()) { + // changed owner, but service still exists. Don't need to adjust anything + return; + } + if (!newOwner.isEmpty()) { + m_matchingServices.insert(serviceName); + } + if (!oldOwner.isEmpty()) { + m_matchingServices.remove(serviceName); + } + }); + } else { + // don't check when not wildcarded, as it could be used with DBus-activation + m_matchingServices << requestedServiceName; + } + + connect(this, &AbstractRunner::teardown, this, &DBusRunner::teardown); + + // Load the runner syntaxes + const QStringList syntaxes = data.value(QStringLiteral("X-Plasma-Runner-Syntaxes"), QStringList()); + const QStringList syntaxDescriptions = data.value(QStringLiteral("X-Plasma-Runner-Syntax-Descriptions"), QStringList()); + const int descriptionCount = syntaxDescriptions.count(); + for (int i = 0; i < syntaxes.count(); ++i) { + const QString &query = syntaxes.at(i); + const QString description = i < descriptionCount ? syntaxDescriptions.at(i) : QString(); + addSyntax(query, description); + } +} + +void DBusRunner::reloadConfiguration() +{ + // If we have already loaded a config, but the runner is told to reload it's config + if (m_callLifecycleMethods) { + suspendMatching(true); + requestConfig(); + } +} + +void DBusRunner::teardown() +{ + if (m_matchWasCalled) { + for (const QString &service : std::as_const(m_matchingServices)) { + auto method = QDBusMessage::createMethodCall(service, m_path, m_ifaceName, QStringLiteral("Teardown")); + QDBusConnection::sessionBus().asyncCall(method); + } + } + m_actionsForSessionRequested = false; + m_matchWasCalled = false; +} + +void DBusRunner::requestActionsForService(const QString &service, const std::function &finishedCallback) +{ + if (m_actionsForSessionRequested) { + finishedCallback(); + return; // only once per match session + } + if (m_requestActionsOnce) { + if (m_requestedActionServices.contains(service)) { + finishedCallback(); + return; + } else { + m_requestedActionServices << service; + } + } + + auto getActionsMethod = QDBusMessage::createMethodCall(service, m_path, m_ifaceName, QStringLiteral("Actions")); + QDBusPendingReply> reply = QDBusConnection::sessionBus().asyncCall(getActionsMethod); + connect(new QDBusPendingCallWatcher(reply), &QDBusPendingCallWatcher::finished, this, [this, service, reply, finishedCallback](auto watcher) { + watcher->deleteLater(); + if (!reply.isValid()) { + qCDebug(KRUNNER) << "Error requesting actions; calling" << service << " :" << reply.error().name() << reply.error().message(); + } else { + m_actions[service] = reply.value(); + } + finishedCallback(); + }); +} + +void DBusRunner::requestConfig() +{ + const QString service = *m_matchingServices.constBegin(); + auto getConfigMethod = QDBusMessage::createMethodCall(service, m_path, m_ifaceName, QStringLiteral("Config")); + QDBusPendingReply reply = QDBusConnection::sessionBus().asyncCall(getConfigMethod); + + auto watcher = new QDBusPendingCallWatcher(reply); + connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, watcher, service]() { + watcher->deleteLater(); + QDBusReply reply = *watcher; + if (!reply.isValid()) { + suspendMatching(false); + qCWarning(KRUNNER) << "Error requesting config; calling" << service << " :" << reply.error().name() << reply.error().message(); + return; + } + const QVariantMap config = reply.value(); + for (auto it = config.cbegin(), end = config.cend(); it != end; ++it) { + if (it.key() == QLatin1String("MatchRegex")) { + QRegularExpression regex(it.value().toString()); + setMatchRegex(regex); + } else if (it.key() == QLatin1String("MinLetterCount")) { + setMinLetterCount(it.value().toInt()); + } else if (it.key() == QLatin1String("TriggerWords")) { + setTriggerWords(it.value().toStringList()); + } else if (it.key() == QLatin1String("Actions")) { + m_actions[service] = it.value().value>(); + m_requestedActionServices << service; + } + } + suspendMatching(false); + }); +} + +QList DBusRunner::convertMatches(const QString &service, const RemoteMatches &remoteMatches) +{ + QList matches; + for (const RemoteMatch &match : remoteMatches) { + KRunner::QueryMatch m(this); + + m.setText(match.text); + m.setIconName(match.iconName); + m.setCategoryRelevance(match.categoryRelevance); + m.setRelevance(match.relevance); + + // split is essential items are as native DBus types, optional extras are in the property map (which is obviously a lot slower to parse) + m.setUrls(QUrl::fromStringList(match.properties.value(QStringLiteral("urls")).toStringList())); + m.setMatchCategory(match.properties.value(QStringLiteral("category")).toString()); + m.setSubtext(match.properties.value(QStringLiteral("subtext")).toString()); + m.setData(QVariantList({service})); + m.setId(match.id); + m.setMultiLine(match.properties.value(QStringLiteral("multiline")).toBool()); + + const auto actionsIt = match.properties.find(QStringLiteral("actions")); + const KRunner::Actions actionList = m_actions.value(service); + if (actionsIt == match.properties.cend()) { + m.setActions(actionList); + } else { + KRunner::Actions requestedActions; + const QStringList actionIds = actionsIt.value().toStringList(); + for (const auto &action : actionList) { + if (actionIds.contains(action.id())) { + requestedActions << action; + } + } + m.setActions(requestedActions); + } + + const QVariant iconData = match.properties.value(QStringLiteral("icon-data")); + if (iconData.isValid()) { + const auto iconDataArgument = iconData.value(); + if (iconDataArgument.currentType() == QDBusArgument::StructureType && iconDataArgument.currentSignature() == QLatin1String("(iiibiiay)")) { + const RemoteImage remoteImage = qdbus_cast(iconDataArgument); + if (QImage decodedImage = decodeImage(remoteImage); !decodedImage.isNull()) { + const QPixmap pix = QPixmap::fromImage(std::move(decodedImage)); + QIcon icon(pix); + m.setIcon(icon); + // iconName normally takes precedence + m.setIconName(QString()); + } + } else { + qCWarning(KRUNNER) << "Invalid signature of icon-data property:" << iconDataArgument.currentSignature(); + } + } + matches.append(m); + } + return matches; +} +void DBusRunner::matchInternal(KRunner::RunnerContext context) +{ + const QString jobId = context.runnerJobId(this); + if (m_matchingServices.isEmpty()) { + Q_EMIT matchInternalFinished(jobId); + } + m_matchWasCalled = true; + + // we scope watchers to make sure the lambda that captures context by reference definitely gets disconnected when this function ends + std::shared_ptr> pendingServices(new std::set); + + for (const QString &service : std::as_const(m_matchingServices)) { + pendingServices->insert(service); + + const auto onActionsFinished = [=, this]() mutable { + auto matchMethod = QDBusMessage::createMethodCall(service, m_path, m_ifaceName, QStringLiteral("Match")); + matchMethod.setArguments(QList({context.query()})); + QDBusPendingReply reply = QDBusConnection::sessionBus().asyncCall(matchMethod); + + auto watcher = new QDBusPendingCallWatcher(reply); + + connect(watcher, &QDBusPendingCallWatcher::finished, this, [this, service, context, reply, jobId, pendingServices, watcher]() mutable { + watcher->deleteLater(); + pendingServices->erase(service); + if (reply.isError()) { + qCWarning(KRUNNER) << "Error requesting matches; calling" << service << " :" << reply.error().name() << reply.error().message(); + } else { + context.addMatches(convertMatches(service, reply.value())); + } + // We are finished when all watchers finished + if (pendingServices->size() == 0) { + Q_EMIT matchInternalFinished(jobId); + } + }); + }; + requestActionsForService(service, onActionsFinished); + } + m_actionsForSessionRequested = true; +} + +void DBusRunner::run(const KRunner::RunnerContext & /*context*/, const KRunner::QueryMatch &match) +{ + QString actionId; + QString matchId; + if (m_hasUniqueResults) { + matchId = match.id(); + } else { + matchId = match.id().mid(id().length() + 1); // QueryMatch::setId mangles the match ID with runnerID + '_'. This unmangles it + } + const QString service = match.data().toList().constFirst().toString(); + + if (match.selectedAction()) { + actionId = match.selectedAction().id(); + } + + auto runMethod = QDBusMessage::createMethodCall(service, m_path, m_ifaceName, QStringLiteral("Run")); + runMethod.setArguments(QList({matchId, actionId})); + QDBusConnection::sessionBus().call(runMethod, QDBus::NoBlock); +} + +QImage DBusRunner::decodeImage(const RemoteImage &remoteImage) +{ + auto copyLineRGB32 = [](QRgb *dst, const char *src, int width) { + const char *end = src + width * 3; + for (; src != end; ++dst, src += 3) { + *dst = qRgb(src[0], src[1], src[2]); + } + }; + + auto copyLineARGB32 = [](QRgb *dst, const char *src, int width) { + const char *end = src + width * 4; + for (; src != end; ++dst, src += 4) { + *dst = qRgba(src[0], src[1], src[2], src[3]); + } + }; + + if (remoteImage.width <= 0 || remoteImage.width >= 2048 || remoteImage.height <= 0 || remoteImage.height >= 2048 || remoteImage.rowStride <= 0) { + qCWarning(KRUNNER) << "Invalid image metadata (width:" << remoteImage.width << "height:" << remoteImage.height << "rowStride:" << remoteImage.rowStride + << ")"; + return QImage(); + } + + QImage::Format format = QImage::Format_Invalid; + void (*copyFn)(QRgb *, const char *, int) = nullptr; + if (remoteImage.bitsPerSample == 8) { + if (remoteImage.channels == 4) { + format = QImage::Format_ARGB32; + copyFn = copyLineARGB32; + } else if (remoteImage.channels == 3) { + format = QImage::Format_RGB32; + copyFn = copyLineRGB32; + } + } + if (format == QImage::Format_Invalid) { + qCWarning(KRUNNER) << "Unsupported image format (hasAlpha:" << remoteImage.hasAlpha << "bitsPerSample:" << remoteImage.bitsPerSample + << "channels:" << remoteImage.channels << ")"; + return QImage(); + } + + QImage image(remoteImage.width, remoteImage.height, format); + const QByteArray pixels = remoteImage.data; + const char *ptr = pixels.data(); + const char *end = ptr + pixels.length(); + for (int y = 0; y < remoteImage.height; ++y, ptr += remoteImage.rowStride) { + if (Q_UNLIKELY(ptr + remoteImage.channels * remoteImage.width > end)) { + qCWarning(KRUNNER) << "Image data is incomplete. y:" << y << "height:" << remoteImage.height; + break; + } + copyFn(reinterpret_cast(image.scanLine(y)), ptr, remoteImage.width); + } + + return image; +} +} +#include "moc_dbusrunner_p.cpp" diff --git a/src/dbusrunner_p.h b/src/dbusrunner_p.h new file mode 100644 index 0000000..4efddd5 --- /dev/null +++ b/src/dbusrunner_p.h @@ -0,0 +1,55 @@ +/* + SPDX-FileCopyrightText: 2017 David Edmundson + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#pragma once + +#include + +#include "dbusutils_p.h" +#include +#include +#include +#include + +namespace KRunner +{ +class DBusRunner : public KRunner::AbstractRunner +{ + Q_OBJECT + +public: + explicit DBusRunner(QObject *parent, const KPluginMetaData &data); + + // matchInternal is overwritten. Meaning we do not need the original match + void match(KRunner::RunnerContext &) override + { + } + void reloadConfiguration() override; + void run(const KRunner::RunnerContext &context, const KRunner::QueryMatch &match) override; + + Q_INVOKABLE void matchInternal(KRunner::RunnerContext context); + +private: + void teardown(); + + // Returns RemoteActions with service name as key + void requestActions(); + void requestActionsForService(const QString &service, const std::function &finishedCallback); + QList convertMatches(const QString &service, const RemoteMatches &remoteMatches); + void requestConfig(); + static QImage decodeImage(const RemoteImage &remoteImage); + QSet m_matchingServices; + QHash> m_actions; + const QString m_path; + const bool m_hasUniqueResults; + const bool m_requestActionsOnce; + bool m_actionsForSessionRequested = false; + bool m_matchWasCalled = false; + bool m_callLifecycleMethods = false; + const QString m_ifaceName; + QSet m_requestedActionServices; +}; +} diff --git a/src/dbusutils_p.h b/src/dbusutils_p.h new file mode 100644 index 0000000..e3e433b --- /dev/null +++ b/src/dbusutils_p.h @@ -0,0 +1,123 @@ +/* + SPDX-FileCopyrightText: 2017, 2018 David Edmundson + SPDX-FileCopyrightText: 2020 Alexander Lohnau + SPDX-FileCopyrightText: 2020 Kai Uwe Broulik + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#pragma once + +#include "action.h" +#include +#include +#include +#include +#include + +struct RemoteMatch { + // sssida{sv} + QString id; + QString text; + QString iconName; + int categoryRelevance = qToUnderlying(KRunner::QueryMatch::CategoryRelevance::Lowest); + qreal relevance = 0; + QVariantMap properties; +}; + +typedef QList RemoteMatches; + +struct RemoteImage { + // iiibiiay (matching notification spec image-data attribute) + int width = 0; + int height = 0; + int rowStride = 0; + bool hasAlpha = false; + int bitsPerSample = 0; + int channels = 0; + QByteArray data; +}; + +inline QDBusArgument &operator<<(QDBusArgument &argument, const RemoteMatch &match) +{ + argument.beginStructure(); + argument << match.id; + argument << match.text; + argument << match.iconName; + argument << match.categoryRelevance; + argument << match.relevance; + argument << match.properties; + argument.endStructure(); + return argument; +} + +inline const QDBusArgument &operator>>(const QDBusArgument &argument, RemoteMatch &match) +{ + argument.beginStructure(); + argument >> match.id; + argument >> match.text; + argument >> match.iconName; + argument >> match.categoryRelevance; + argument >> match.relevance; + argument >> match.properties; + argument.endStructure(); + + return argument; +} + +inline QDBusArgument &operator<<(QDBusArgument &argument, const KRunner::Action &action) +{ + argument.beginStructure(); + argument << action.id(); + argument << action.text(); + argument << action.iconSource(); + argument.endStructure(); + return argument; +} + +inline const QDBusArgument &operator>>(const QDBusArgument &argument, KRunner::Action &action) +{ + QString id; + QString text; + QString iconName; + argument.beginStructure(); + argument >> id; + argument >> text; + argument >> iconName; + argument.endStructure(); + action = KRunner::Action(id, iconName, text); + return argument; +} + +inline QDBusArgument &operator<<(QDBusArgument &argument, const RemoteImage &image) +{ + argument.beginStructure(); + argument << image.width; + argument << image.height; + argument << image.rowStride; + argument << image.hasAlpha; + argument << image.bitsPerSample; + argument << image.channels; + argument << image.data; + argument.endStructure(); + return argument; +} + +inline const QDBusArgument &operator>>(const QDBusArgument &argument, RemoteImage &image) +{ + argument.beginStructure(); + argument >> image.width; + argument >> image.height; + argument >> image.rowStride; + argument >> image.hasAlpha; + argument >> image.bitsPerSample; + argument >> image.channels; + argument >> image.data; + argument.endStructure(); + return argument; +} + +Q_DECLARE_METATYPE(QList) +Q_DECLARE_METATYPE(RemoteMatch) +Q_DECLARE_METATYPE(RemoteMatches) +Q_DECLARE_METATYPE(RemoteImage) diff --git a/src/kpluginmetadata_utils_p.h b/src/kpluginmetadata_utils_p.h new file mode 100644 index 0000000..5d106ba --- /dev/null +++ b/src/kpluginmetadata_utils_p.h @@ -0,0 +1,59 @@ +/* + SPDX-FileCopyrightText: 2022 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include +#include +#include +#include +#include +#include + +template +inline void copyIfExists(const KConfigGroup &grp, QJsonObject &obj, const char *key, const T &t = QString()) +{ + copyAndRenameIfExists(grp, obj, key, key, t); +} + +template +inline void copyAndRenameIfExists(const KConfigGroup &grp, QJsonObject &obj, const char *oldKey, const char *key, const T &t) +{ + if (grp.hasKey(oldKey)) { + obj.insert(QLatin1String(key), grp.readEntry(oldKey, t)); + } +} +inline KPluginMetaData parseMetaDataFromDesktopFile(const QString &fileName) +{ + KDesktopFile file(fileName); + const KConfigGroup grp = file.desktopGroup(); + + QJsonObject kplugin; + copyIfExists(grp, kplugin, "Name"); + copyIfExists(grp, kplugin, "Icon"); + copyAndRenameIfExists(grp, kplugin, "X-KDE-PluginInfo-Name", "Id", QString()); + copyAndRenameIfExists(grp, kplugin, "Comment", "Description", QString()); + copyAndRenameIfExists(grp, kplugin, "X-KDE-PluginInfo-EnabledByDefault", "EnabledByDefault", false); + QJsonObject root; + root.insert(QLatin1String("KPlugin"), kplugin); + + copyIfExists(grp, root, "X-Plasma-DBusRunner-Service"); + copyIfExists(grp, root, "X-Plasma-DBusRunner-Path"); + copyIfExists(grp, root, "X-Plasma-Runner-Unique-Results", false); + copyIfExists(grp, root, "X-Plasma-Runner-Weak-Results", false); + copyIfExists(grp, root, "X-Plasma-API"); + copyIfExists(grp, root, "X-Plasma-Request-Actions-Once", false); + copyIfExists(grp, root, "X-Plasma-Runner-Min-Letter-Count", 0); + copyIfExists(grp, root, "X-Plasma-Runner-Match-Regex"); + copyIfExists(grp, root, "X-KDE-ConfigModule"); // DBus-Runners may also specify KCMs + root.insert(QLatin1String("X-Plasma-Runner-Syntaxes"), QJsonArray::fromStringList(grp.readEntry("X-Plasma-Runner-Syntaxes", QStringList()))); + root.insert(QLatin1String("X-Plasma-Runner-Syntax-Descriptions"), + QJsonArray::fromStringList(grp.readEntry("X-Plasma-Runner-Syntax-Descriptions", QStringList()))); + QJsonObject author; + author.insert(QLatin1String("Name"), grp.readEntry("X-KDE-PluginInfo-Author")); + author.insert(QLatin1String("Email"), grp.readEntry("X-KDE-PluginInfo-Email")); + author.insert(QLatin1String("Website"), grp.readEntry("X-KDE-PluginInfo-Website")); + + return KPluginMetaData(root, fileName); +} diff --git a/src/model/resultsmodel.cpp b/src/model/resultsmodel.cpp new file mode 100644 index 0000000..2026392 --- /dev/null +++ b/src/model/resultsmodel.cpp @@ -0,0 +1,432 @@ +/* + * This file is part of the KDE Milou Project + * SPDX-FileCopyrightText: 2019 Kai Uwe Broulik + * SPDX-FileCopyrightText: 2023 Alexander Lohnau + * + * SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL + * + */ + +#include "resultsmodel.h" + +#include "runnerresultsmodel_p.h" + +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace KRunner; + +/** + * Sorts the matches and categories by their type and relevance + * + * A category gets type and relevance of the highest + * scoring match within. + */ +class SortProxyModel : public QSortFilterProxyModel +{ + Q_OBJECT + +public: + explicit SortProxyModel(QObject *parent) + : QSortFilterProxyModel(parent) + { + setDynamicSortFilter(true); + sort(0, Qt::DescendingOrder); + } + + void setQueryString(const QString &queryString) + { + const QStringList words = queryString.split(QLatin1Char(' '), Qt::SkipEmptyParts); + if (m_words != words) { + m_words = words; + invalidate(); + } + } + +protected: + bool lessThan(const QModelIndex &sourceA, const QModelIndex &sourceB) const override + { + bool isCategoryComparison = !sourceA.internalId() && !sourceB.internalId(); + Q_ASSERT((bool)sourceA.internalId() == (bool)sourceB.internalId()); + // Only check the favorite index if we compare categories. For individual matches, they will always be the same + if (isCategoryComparison) { + const int favoriteA = sourceA.data(ResultsModel::FavoriteIndexRole).toInt(); + const int favoriteB = sourceB.data(ResultsModel::FavoriteIndexRole).toInt(); + bool isFavoriteA = favoriteA != -1; + bool isFavoriteB = favoriteB != -1; + if (isFavoriteA && !isFavoriteB) { + return false; + } else if (!isFavoriteA && isFavoriteB) { + return true; + } + + const int favoritesCount = sourceA.data(ResultsModel::FavoriteCountRole).toInt(); + const double favoriteAMultiplicationFactor = (favoriteA ? 1 + ((favoritesCount - favoriteA) * 0.2) : 1); + const double typeA = sourceA.data(ResultsModel::CategoryRelevanceRole).toReal() * favoriteAMultiplicationFactor; + const double favoriteBMultiplicationFactor = (favoriteB ? 1 + ((favoritesCount - favoriteB) * 0.2) : 1); + const double typeB = sourceB.data(ResultsModel::CategoryRelevanceRole).toReal() * favoriteBMultiplicationFactor; + return typeA < typeB; + } + + const qreal relevanceA = sourceA.data(ResultsModel::RelevanceRole).toReal(); + const qreal relevanceB = sourceB.data(ResultsModel::RelevanceRole).toReal(); + + if (!qFuzzyCompare(relevanceA, relevanceB)) { + return relevanceA < relevanceB; + } + + return QSortFilterProxyModel::lessThan(sourceA, sourceB); + } + +public: + QStringList m_words; +}; + +/** + * Distributes the number of matches shown per category + * + * Each category may occupy a maximum of 1/(n+1) of the given @c limit, + * this means the further down you get, the less matches there are. + * There is at least one match shown per category. + * + * This model assumes the results to already be sorted + * descending by their relevance/score. + */ +class CategoryDistributionProxyModel : public QSortFilterProxyModel +{ + Q_OBJECT + +public: + explicit CategoryDistributionProxyModel(QObject *parent) + : QSortFilterProxyModel(parent) + { + } + void setSourceModel(QAbstractItemModel *sourceModel) override + { + if (this->sourceModel()) { + disconnect(this->sourceModel(), nullptr, this, nullptr); + } + + QSortFilterProxyModel::setSourceModel(sourceModel); + + if (sourceModel) { + connect(sourceModel, &QAbstractItemModel::rowsInserted, this, &CategoryDistributionProxyModel::invalidateFilter); + connect(sourceModel, &QAbstractItemModel::rowsMoved, this, &CategoryDistributionProxyModel::invalidateFilter); + connect(sourceModel, &QAbstractItemModel::rowsRemoved, this, &CategoryDistributionProxyModel::invalidateFilter); + } + } + + int limit() const + { + return m_limit; + } + + void setLimit(int limit) + { + if (m_limit == limit) { + return; + } + m_limit = limit; + invalidateFilter(); + Q_EMIT limitChanged(); + } + +Q_SIGNALS: + void limitChanged(); + +protected: + bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override + { + if (m_limit <= 0) { + return true; + } + + if (!sourceParent.isValid()) { + return true; + } + + const int categoryCount = sourceModel()->rowCount(); + + int maxItemsInCategory = m_limit; + + if (categoryCount > 1) { + int itemsBefore = 0; + for (int i = 0; i <= sourceParent.row(); ++i) { + const int itemsInCategory = sourceModel()->rowCount(sourceModel()->index(i, 0)); + + // Take into account that every category gets at least one item shown + const int availableSpace = m_limit - itemsBefore - std::ceil(m_limit / qreal(categoryCount)); + + // The further down the category is the less relevant it is and the less space it my occupy + // First category gets max half the total limit, second category a third, etc + maxItemsInCategory = std::min(availableSpace, int(std::ceil(m_limit / qreal(i + 2)))); + + // At least show one item per category + maxItemsInCategory = std::max(1, maxItemsInCategory); + + itemsBefore += std::min(itemsInCategory, maxItemsInCategory); + } + } + + if (sourceRow >= maxItemsInCategory) { + return false; + } + + return true; + } + +private: + // if you change this, update the default in resetLimit() + int m_limit = 0; +}; + +/** + * This model hides the root items of data originally in a tree structure + * + * KDescendantsProxyModel collapses the items but keeps all items in tact. + * The root items of the RunnerMatchesModel represent the individual cateories + * which we don't want in the resulting flat list. + * This model maps the items back to the given @c treeModel and filters + * out any item with an invalid parent, i.e. "on the root level" + */ +class HideRootLevelProxyModel : public QSortFilterProxyModel +{ + Q_OBJECT + +public: + explicit HideRootLevelProxyModel(QObject *parent) + : QSortFilterProxyModel(parent) + { + } + + QAbstractItemModel *treeModel() const + { + return m_treeModel; + } + void setTreeModel(QAbstractItemModel *treeModel) + { + m_treeModel = treeModel; + invalidateFilter(); + } + +protected: + bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override + { + KModelIndexProxyMapper mapper(sourceModel(), m_treeModel); + const QModelIndex treeIdx = mapper.mapLeftToRight(sourceModel()->index(sourceRow, 0, sourceParent)); + return treeIdx.parent().isValid(); + } + +private: + QAbstractItemModel *m_treeModel = nullptr; +}; + +class KRunner::ResultsModelPrivate +{ +public: + explicit ResultsModelPrivate(const KConfigGroup &configGroup, const KConfigGroup &stateConfigGroup, ResultsModel *q) + : q(q) + , resultsModel(new RunnerResultsModel(configGroup, stateConfigGroup, q)) + { + } + + ResultsModel *q; + + QPointer runner = nullptr; + + RunnerResultsModel *const resultsModel; + SortProxyModel *const sortModel = new SortProxyModel(q); + CategoryDistributionProxyModel *const distributionModel = new CategoryDistributionProxyModel(q); + KDescendantsProxyModel *const flattenModel = new KDescendantsProxyModel(q); + HideRootLevelProxyModel *const hideRootModel = new HideRootLevelProxyModel(q); + const KModelIndexProxyMapper mapper{q, resultsModel}; +}; + +ResultsModel::ResultsModel(QObject *parent) + : ResultsModel(KConfigGroup(), KConfigGroup(), parent) +{ +} +ResultsModel::ResultsModel(const KConfigGroup &configGroup, const KConfigGroup &stateConfigGroup, QObject *parent) + : QSortFilterProxyModel(parent) + , d(new ResultsModelPrivate(configGroup, stateConfigGroup, this)) +{ + connect(d->resultsModel, &RunnerResultsModel::queryStringChanged, this, &ResultsModel::queryStringChanged); + connect(runnerManager(), &RunnerManager::queryingChanged, this, &ResultsModel::queryingChanged); + connect(d->resultsModel, &RunnerResultsModel::queryStringChangeRequested, this, &ResultsModel::queryStringChangeRequested); + connect(d->resultsModel, &RunnerResultsModel::runnerManagerChanged, this, [this]() { + connect(runnerManager(), &RunnerManager::queryingChanged, this, &ResultsModel::queryingChanged); + }); + + // The matches for the old query string remain on display until the first set of matches arrive for the new query string. + // Therefore we must not update the query string inside RunnerResultsModel exactly when the query string changes, otherwise it would + // re-sort the old query string matches based on the new query string. + // So we only make it aware of the query string change at the time when we receive the first set of matches for the new query string. + connect(d->resultsModel, &RunnerResultsModel::matchesChanged, this, [this]() { + d->sortModel->setQueryString(queryString()); + }); + + connect(d->distributionModel, &CategoryDistributionProxyModel::limitChanged, this, &ResultsModel::limitChanged); + + // The data flows as follows: + // - RunnerResultsModel + // - SortProxyModel + // - CategoryDistributionProxyModel + // - KDescendantsProxyModel + // - HideRootLevelProxyModel + + d->sortModel->setSourceModel(d->resultsModel); + + d->distributionModel->setSourceModel(d->sortModel); + + d->flattenModel->setSourceModel(d->distributionModel); + + d->hideRootModel->setSourceModel(d->flattenModel); + d->hideRootModel->setTreeModel(d->resultsModel); + + setSourceModel(d->hideRootModel); + + // Initialize the runners, this will speed the first query up. + // While there were lots of optimizations, instantiating plugins, creating threads and AbstractRunner::init is still heavy work + QTimer::singleShot(0, this, [this]() { + runnerManager()->runners(); + }); +} + +ResultsModel::~ResultsModel() = default; + +void ResultsModel::setFavoriteIds(const QStringList &ids) +{ + d->resultsModel->m_favoriteIds = ids; + Q_EMIT favoriteIdsChanged(); +} + +QStringList ResultsModel::favoriteIds() const +{ + return d->resultsModel->m_favoriteIds; +} + +QString ResultsModel::queryString() const +{ + return d->resultsModel->queryString(); +} + +void ResultsModel::setQueryString(const QString &queryString) +{ + d->resultsModel->setQueryString(queryString, singleRunner()); +} + +int ResultsModel::limit() const +{ + return d->distributionModel->limit(); +} + +void ResultsModel::setLimit(int limit) +{ + d->distributionModel->setLimit(limit); +} + +void ResultsModel::resetLimit() +{ + setLimit(0); +} + +bool ResultsModel::querying() const +{ + return runnerManager()->querying(); +} + +QString ResultsModel::singleRunner() const +{ + return d->runner ? d->runner->id() : QString(); +} + +void ResultsModel::setSingleRunner(const QString &runnerId) +{ + if (runnerId == singleRunner()) { + return; + } + if (runnerId.isEmpty()) { + d->runner = nullptr; + } else { + d->runner = runnerManager()->runner(runnerId); + } + Q_EMIT singleRunnerChanged(); +} + +KPluginMetaData ResultsModel::singleRunnerMetaData() const +{ + return d->runner ? d->runner->metadata() : KPluginMetaData(); +} + +QHash ResultsModel::roleNames() const +{ + auto names = QAbstractProxyModel::roleNames(); + names[IdRole] = QByteArrayLiteral("matchId"); // "id" is QML-reserved + names[EnabledRole] = QByteArrayLiteral("enabled"); + names[CategoryRole] = QByteArrayLiteral("category"); + names[SubtextRole] = QByteArrayLiteral("subtext"); + names[UrlsRole] = QByteArrayLiteral("urls"); + names[ActionsRole] = QByteArrayLiteral("actions"); + names[MultiLineRole] = QByteArrayLiteral("multiLine"); + return names; +} + +void ResultsModel::clear() +{ + d->resultsModel->clear(); +} + +bool ResultsModel::run(const QModelIndex &idx) +{ + KModelIndexProxyMapper mapper(this, d->resultsModel); + const QModelIndex resultsIdx = mapper.mapLeftToRight(idx); + if (!resultsIdx.isValid()) { + return false; + } + return d->resultsModel->run(resultsIdx); +} + +bool ResultsModel::runAction(const QModelIndex &idx, int actionNumber) +{ + KModelIndexProxyMapper mapper(this, d->resultsModel); + const QModelIndex resultsIdx = mapper.mapLeftToRight(idx); + if (!resultsIdx.isValid()) { + return false; + } + return d->resultsModel->runAction(resultsIdx, actionNumber); +} + +QMimeData *ResultsModel::getMimeData(const QModelIndex &idx) const +{ + if (auto resultIdx = d->mapper.mapLeftToRight(idx); resultIdx.isValid()) { + return runnerManager()->mimeDataForMatch(d->resultsModel->fetchMatch(resultIdx)); + } + return nullptr; +} + +KRunner::RunnerManager *ResultsModel::runnerManager() const +{ + return d->resultsModel->runnerManager(); +} + +KRunner::QueryMatch ResultsModel::getQueryMatch(const QModelIndex &idx) const +{ + const QModelIndex resultIdx = d->mapper.mapLeftToRight(idx); + return resultIdx.isValid() ? d->resultsModel->fetchMatch(resultIdx) : QueryMatch(); +} + +void ResultsModel::setRunnerManager(KRunner::RunnerManager *manager) +{ + d->resultsModel->setRunnerManager(manager); + Q_EMIT runnerManagerChanged(); +} + +#include "moc_resultsmodel.cpp" +#include "resultsmodel.moc" diff --git a/src/model/resultsmodel.h b/src/model/resultsmodel.h new file mode 100644 index 0000000..efee26d --- /dev/null +++ b/src/model/resultsmodel.h @@ -0,0 +1,156 @@ +/* + * SPDX-FileCopyrightText: 2019 Kai Uwe Broulik + * SPDX-FileCopyrightText: 2023 Alexander Lohnau + * + * SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL + * + */ + +#ifndef KRUNNER_RESULTSMODEL +#define KRUNNER_RESULTSMODEL + +#include "krunner_export.h" + +#include +#include +#include +#include + +namespace KRunner +{ +class ResultsModelPrivate; + +/** + * @class ResultsModel resultsmodel.h + * + * A model that exposes and sorts results for a given query. + * + * @since 6.0 + */ +class KRUNNER_EXPORT ResultsModel : public QSortFilterProxyModel +{ + Q_OBJECT + + /** + * The query string to run + */ + Q_PROPERTY(QString queryString READ queryString WRITE setQueryString NOTIFY queryStringChanged) + /** + * The preferred maximum number of matches in the model + * + * If there are lots of results from different categories, + * the limit can be slightly exceeded. + * + * Default is 0, which means no limit. + */ + Q_PROPERTY(int limit READ limit WRITE setLimit RESET resetLimit NOTIFY limitChanged) + /** + * Whether the query is currently being run + * + * This can be used to show a busy indicator + */ + Q_PROPERTY(bool querying READ querying NOTIFY queryingChanged) + + /** + * The single runner to use for querying in single runner mode + * + * Defaults to empty string which means all runners + */ + Q_PROPERTY(QString singleRunner READ singleRunner WRITE setSingleRunner NOTIFY singleRunnerChanged) + Q_PROPERTY(KPluginMetaData singleRunnerMetaData READ singleRunnerMetaData NOTIFY singleRunnerChanged) + + Q_PROPERTY(KRunner::RunnerManager *runnerManager READ runnerManager WRITE setRunnerManager NOTIFY runnerManagerChanged) + Q_PROPERTY(QStringList favoriteIds READ favoriteIds WRITE setFavoriteIds NOTIFY favoriteIdsChanged) + +public: + explicit ResultsModel(const KConfigGroup &configGroup, const KConfigGroup &stateConfigGroup, QObject *parent = nullptr); + explicit ResultsModel(QObject *parent = nullptr); + ~ResultsModel() override; + + enum Roles { + IdRole = Qt::UserRole + 1, + CategoryRelevanceRole, + RelevanceRole, + EnabledRole, + CategoryRole, + SubtextRole, + ActionsRole, + MultiLineRole, + UrlsRole, + QueryMatchRole, /// @internal + FavoriteIndexRole, /// @internal + FavoriteCountRole, /// @internal + }; + Q_ENUM(Roles) + + QString queryString() const; + void setQueryString(const QString &queryString); + Q_SIGNAL void queryStringChanged(const QString &queryString); + + /** + * IDs of favorite plugins. Those plugins are always in a fixed order before the other ones. + * @param ids KPluginMetaData::pluginId values of plugins + */ + void setFavoriteIds(const QStringList &ids); + QStringList favoriteIds() const; + Q_SIGNAL void favoriteIdsChanged(); + + int limit() const; + void setLimit(int limit); + void resetLimit(); + Q_SIGNAL void limitChanged(); + + bool querying() const; + Q_SIGNAL void queryingChanged(); + + QString singleRunner() const; + void setSingleRunner(const QString &runner); + Q_SIGNAL void singleRunnerChanged(); + + KPluginMetaData singleRunnerMetaData() const; + + QHash roleNames() const override; + + /** + * Clears the model content and resets the runner context, i.e. no new items will appear. + */ + Q_INVOKABLE void clear(); + + /** + * Run the result at the given model index @p idx + */ + Q_INVOKABLE bool run(const QModelIndex &idx); + /** + * Run the action @p actionNumber at given model index @p idx + */ + Q_INVOKABLE bool runAction(const QModelIndex &idx, int actionNumber); + + /** + * Get mime data for the result at given model index @p idx + */ + Q_INVOKABLE QMimeData *getMimeData(const QModelIndex &idx) const; + + /** + * Get match for the result at given model index @p idx + */ + KRunner::QueryMatch getQueryMatch(const QModelIndex &idx) const; + + KRunner::RunnerManager *runnerManager() const; + /// @since 6.9 + void setRunnerManager(KRunner::RunnerManager *manager); + /// @since 6.9 + Q_SIGNAL void runnerManagerChanged(); + +Q_SIGNALS: + /** + * This signal is emitted when a an InformationalMatch is run, and it is advised + * to update the search term, e.g. used for calculator runner results + */ + void queryStringChangeRequested(const QString &queryString, int pos); + +private: + const std::unique_ptr d; +}; + +} // namespace KRunner +#endif diff --git a/src/model/runnerresultsmodel.cpp b/src/model/runnerresultsmodel.cpp new file mode 100644 index 0000000..0f739e4 --- /dev/null +++ b/src/model/runnerresultsmodel.cpp @@ -0,0 +1,383 @@ +/* + * SPDX-FileCopyrightText: 2019 Kai Uwe Broulik + * + * SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL + * + */ + +#include "runnerresultsmodel_p.h" + +#include + +#include + +#include "resultsmodel.h" + +namespace KRunner +{ +RunnerResultsModel::RunnerResultsModel(const KConfigGroup &configGroup, const KConfigGroup &stateConfigGroup, QObject *parent) + : QAbstractItemModel(parent) +{ + // Invalid groups are passed in to avoid unneeded overloads and such + setRunnerManager(configGroup.isValid() && stateConfigGroup.isValid() ? new RunnerManager(configGroup, stateConfigGroup, this) : new RunnerManager(this)); +} + +KRunner::QueryMatch RunnerResultsModel::fetchMatch(const QModelIndex &idx) const +{ + const QString category = m_categories.value(int(idx.internalId() - 1)); + return m_matches.value(category).value(idx.row()); +} + +void RunnerResultsModel::onMatchesChanged(const QList &matches) +{ + // Build the list of new categories and matches + QSet newCategories; + // here we use QString as key since at this point we don't care about the order + // of categories but just what matches we have for each one. + // Below when we populate the actual m_matches we'll make sure to keep the order + // of existing categories to avoid pointless model changes. + QHash> newMatches; + for (const auto &match : matches) { + const QString category = match.matchCategory(); + newCategories.insert(category); + newMatches[category].append(match); + } + + // Get rid of all categories that are no longer present + auto it = m_categories.begin(); + while (it != m_categories.end()) { + const int categoryNumber = int(std::distance(m_categories.begin(), it)); + + if (!newCategories.contains(*it)) { + beginRemoveRows(QModelIndex(), categoryNumber, categoryNumber); + m_matches.remove(*it); + it = m_categories.erase(it); + endRemoveRows(); + } else { + ++it; + } + } + + // Update the existing categories by adding/removing new/removed rows and + // updating changed ones + for (auto it = m_categories.constBegin(); it != m_categories.constEnd(); ++it) { + Q_ASSERT(newCategories.contains(*it)); + + const int categoryNumber = int(std::distance(m_categories.constBegin(), it)); + const QModelIndex categoryIdx = index(categoryNumber, 0); + + // don't use operator[] as to not insert an empty list + // TODO why? shouldn't m_categories and m_matches be in sync? + auto oldCategoryIt = m_matches.find(*it); + Q_ASSERT(oldCategoryIt != m_matches.end()); + + auto &oldMatchesInCategory = *oldCategoryIt; + const auto newMatchesInCategory = newMatches.value(*it); + + Q_ASSERT(!oldMatchesInCategory.isEmpty()); + Q_ASSERT(!newMatches.isEmpty()); + + // Emit a change for all existing matches if any of them changed + // TODO only emit a change for the ones that changed + bool emitDataChanged = false; + + const int oldCount = oldMatchesInCategory.count(); + const int newCount = newMatchesInCategory.count(); + + const int countCeiling = qMin(oldCount, newCount); + + for (int i = 0; i < countCeiling; ++i) { + auto &oldMatch = oldMatchesInCategory[i]; + if (oldMatch != newMatchesInCategory.at(i)) { + oldMatch = newMatchesInCategory.at(i); + emitDataChanged = true; + } + } + + // Now that the source data has been updated, emit the data changes we noted down earlier + if (emitDataChanged) { + Q_EMIT dataChanged(index(0, 0, categoryIdx), index(countCeiling - 1, 0, categoryIdx)); + } + + // Signal insertions for any new items + if (newCount > oldCount) { + beginInsertRows(categoryIdx, oldCount, newCount - 1); + oldMatchesInCategory = newMatchesInCategory; + endInsertRows(); + } else if (newCount < oldCount) { + beginRemoveRows(categoryIdx, newCount, oldCount - 1); + oldMatchesInCategory = newMatchesInCategory; + endRemoveRows(); + } + + // Remove it from the "new" categories so in the next step we can add all genuinely new categories in one go + newCategories.remove(*it); + } + + // Finally add all the new categories + if (!newCategories.isEmpty()) { + beginInsertRows(QModelIndex(), m_categories.count(), m_categories.count() + newCategories.count() - 1); + + for (const QString &newCategory : newCategories) { + const auto matchesInNewCategory = newMatches.value(newCategory); + + m_matches[newCategory] = matchesInNewCategory; + m_categories.append(newCategory); + } + + endInsertRows(); + } + + Q_ASSERT(m_categories.count() == m_matches.count()); + + m_hasMatches = !m_matches.isEmpty(); + + Q_EMIT matchesChanged(); +} + +QString RunnerResultsModel::queryString() const +{ + return m_queryString; +} + +void RunnerResultsModel::setQueryString(const QString &queryString, const QString &runner) +{ + // If our query and runner are the same we don't need to query again + if (m_queryString.trimmed() == queryString.trimmed() && m_prevRunner == runner) { + return; + } + + m_prevRunner = runner; + m_queryString = queryString; + m_hasMatches = false; + if (queryString.isEmpty()) { + clear(); + } else if (!queryString.trimmed().isEmpty()) { + m_manager->launchQuery(queryString, runner); + } + Q_EMIT queryStringChanged(queryString); // NOLINT(readability-misleading-indentation) +} + +void RunnerResultsModel::clear() +{ + m_manager->reset(); + m_manager->matchSessionComplete(); + + // When our session is over, the term is also no longer relevant + // If the same term is used again, the RunnerManager should be asked again + if (!m_queryString.isEmpty()) { + m_queryString.clear(); + Q_EMIT queryStringChanged(m_queryString); + } + + beginResetModel(); + m_categories.clear(); + m_matches.clear(); + endResetModel(); + + m_hasMatches = false; +} + +bool RunnerResultsModel::run(const QModelIndex &idx) +{ + KRunner::QueryMatch match = fetchMatch(idx); + if (match.isValid() && match.isEnabled()) { + return m_manager->run(match); + } + return false; +} + +bool RunnerResultsModel::runAction(const QModelIndex &idx, int actionNumber) +{ + KRunner::QueryMatch match = fetchMatch(idx); + if (!match.isValid() || !match.isEnabled()) { + return false; + } + + if (actionNumber < 0 || actionNumber >= match.actions().count()) { + return false; + } + + return m_manager->run(match, match.actions().at(actionNumber)); +} + +int RunnerResultsModel::columnCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + return 1; +} + +int RunnerResultsModel::rowCount(const QModelIndex &parent) const +{ + if (parent.column() > 0) { + return 0; + } + + if (!parent.isValid()) { // root level + return m_categories.count(); + } + + if (parent.internalId()) { + return 0; + } + + const QString category = m_categories.value(parent.row()); + return m_matches.value(category).count(); +} + +QVariant RunnerResultsModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid()) { + return QVariant(); + } + + if (index.internalId()) { // runner match + if (int(index.internalId() - 1) >= m_categories.count()) { + return QVariant(); + } + + KRunner::QueryMatch match = fetchMatch(index); + if (!match.isValid()) { + return QVariant(); + } + + switch (role) { + case Qt::DisplayRole: + return match.text(); + case Qt::DecorationRole: + if (!match.iconName().isEmpty()) { + return match.iconName(); + } + return match.icon(); + case ResultsModel::CategoryRelevanceRole: + return match.categoryRelevance(); + case ResultsModel::RelevanceRole: + return match.relevance(); + case ResultsModel::IdRole: + return match.id(); + case ResultsModel::EnabledRole: + return match.isEnabled(); + case ResultsModel::CategoryRole: + return match.matchCategory(); + case ResultsModel::SubtextRole: + return match.subtext(); + case ResultsModel::UrlsRole: + return QVariant::fromValue(match.urls()); + case ResultsModel::MultiLineRole: + return match.isMultiLine(); + case ResultsModel::ActionsRole: { + const auto actions = match.actions(); + QVariantList actionsList; + actionsList.reserve(actions.size()); + + for (const KRunner::Action &action : actions) { + actionsList.append(QVariant::fromValue(action)); + } + + return actionsList; + } + case ResultsModel::QueryMatchRole: + return QVariant::fromValue(match); + } + + return QVariant(); + } + + // category + if (index.row() >= m_categories.count()) { + return QVariant(); + } + + switch (role) { + case Qt::DisplayRole: + return m_categories.at(index.row()); + + case ResultsModel::FavoriteIndexRole: { + for (int i = 0; i < rowCount(index); ++i) { + auto match = this->index(i, 0, index).data(ResultsModel::QueryMatchRole).value(); + if (match.isValid()) { + const QString id = match.runner()->id(); + int idx = m_favoriteIds.indexOf(id); + return idx; + } + } + // Any match that is not a favorite will have a greater index than an actual favorite + return m_favoriteIds.size(); + } + case ResultsModel::FavoriteCountRole: + return m_favoriteIds.size(); + // Returns the highest type/role within the group + case ResultsModel::CategoryRelevanceRole: { + int highestType = 0; + for (int i = 0; i < rowCount(index); ++i) { + const int type = this->index(i, 0, index).data(ResultsModel::CategoryRelevanceRole).toInt(); + if (type > highestType) { + highestType = type; + } + } + return highestType; + } + case ResultsModel::RelevanceRole: { + qreal highestRelevance = 0.0; + for (int i = 0; i < rowCount(index); ++i) { + const qreal relevance = this->index(i, 0, index).data(ResultsModel::RelevanceRole).toReal(); + if (relevance > highestRelevance) { + highestRelevance = relevance; + } + } + return highestRelevance; + } + } + + return QVariant(); +} + +QModelIndex RunnerResultsModel::index(int row, int column, const QModelIndex &parent) const +{ + if (row < 0 || column != 0) { + return QModelIndex(); + } + + if (parent.isValid()) { + const QString category = m_categories.value(parent.row()); + const auto matches = m_matches.value(category); + if (row < matches.count()) { + return createIndex(row, column, int(parent.row() + 1)); + } + + return QModelIndex(); + } + + if (row < m_categories.count()) { + return createIndex(row, column, nullptr); + } + + return QModelIndex(); +} + +QModelIndex RunnerResultsModel::parent(const QModelIndex &child) const +{ + if (child.internalId()) { + return createIndex(int(child.internalId() - 1), 0, nullptr); + } + + return QModelIndex(); +} + +KRunner::RunnerManager *RunnerResultsModel::runnerManager() const +{ + return m_manager; +} + +void RunnerResultsModel::setRunnerManager(KRunner::RunnerManager *manager) +{ + disconnect(m_manager); + m_manager = manager; + + connect(m_manager, &RunnerManager::matchesChanged, this, &RunnerResultsModel::onMatchesChanged); + connect(m_manager, &RunnerManager::requestUpdateQueryString, this, &RunnerResultsModel::queryStringChangeRequested); + Q_EMIT runnerManagerChanged(); +} +} + +#include "moc_runnerresultsmodel_p.cpp" diff --git a/src/model/runnerresultsmodel_p.h b/src/model/runnerresultsmodel_p.h new file mode 100644 index 0000000..c2a1229 --- /dev/null +++ b/src/model/runnerresultsmodel_p.h @@ -0,0 +1,75 @@ +/* + * This file is part of the KDE Milou Project + * SPDX-FileCopyrightText: 2019 Kai Uwe Broulik + * + * SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL + * + */ + +#pragma once + +#include +#include +#include +#include + +#include + +namespace KRunner +{ +class RunnerManager; +} + +namespace KRunner +{ +class RunnerResultsModel : public QAbstractItemModel +{ + Q_OBJECT + +public: + explicit RunnerResultsModel(const KConfigGroup &configGroup, const KConfigGroup &stateConfigGroup, QObject *parent = nullptr); + + QString queryString() const; + void setQueryString(const QString &queryString, const QString &runner); + Q_SIGNAL void queryStringChanged(const QString &queryString); + + void setRunnerManager(KRunner::RunnerManager *manager); + Q_SIGNAL void runnerManagerChanged(); + + /** + * Clears the model content and resets the runner context, i.e. no new items will appear. + */ + void clear(); + + bool run(const QModelIndex &idx); + bool runAction(const QModelIndex &idx, int actionNumber); + + int columnCount(const QModelIndex &parent) const override; + int rowCount(const QModelIndex &parent) const override; + + QVariant data(const QModelIndex &index, int role) const override; + + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + QModelIndex parent(const QModelIndex &child) const override; + + KRunner::RunnerManager *runnerManager() const; + KRunner::QueryMatch fetchMatch(const QModelIndex &idx) const; + + QStringList m_favoriteIds; +Q_SIGNALS: + void queryStringChangeRequested(const QString &queryString, int pos); + + void matchesChanged(); + +private: + void onMatchesChanged(const QList &matches); + + KRunner::RunnerManager *m_manager = nullptr; + QString m_queryString; + QString m_prevRunner; + bool m_hasMatches = false; + QStringList m_categories; + QHash> m_matches; +}; + +} // namespace Milou diff --git a/src/querymatch.cpp b/src/querymatch.cpp new file mode 100644 index 0000000..a29e98c --- /dev/null +++ b/src/querymatch.cpp @@ -0,0 +1,311 @@ +/* + SPDX-FileCopyrightText: 2006-2007 Aaron Seigo + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include "querymatch.h" +#include "action.h" + +#include +#include +#include +#include +#include + +#include "abstractrunner.h" +#include "abstractrunner_p.h" + +namespace KRunner +{ +class QueryMatchPrivate : public QSharedData +{ +public: + explicit QueryMatchPrivate(AbstractRunner *r) + : QSharedData() + , runner(r) + { + } + + QueryMatchPrivate(const QueryMatchPrivate &other) + : QSharedData(other) + { + QReadLocker l(&other.lock); + runner = other.runner; + categoryRelevance = other.categoryRelevance; + relevance = other.relevance; + selAction = other.selAction; + enabled = other.enabled; + idSetByData = other.idSetByData; + matchCategory = other.matchCategory; + id = other.id; + text = other.text; + subtext = other.subtext; + icon = other.icon; + iconName = other.iconName; + data = other.data; + urls = other.urls; + actions = other.actions; + multiLine = other.multiLine; + } + + void setId(const QString &newId) + { + if (runner && runner->d->hasUniqueResults) { + id = newId; + } else { + if (runner) { + id = runner.data()->id(); + } + if (!id.isEmpty()) { + id.append(QLatin1Char('_')).append(newId); + } + } + idSetByData = false; + } + + mutable QReadWriteLock lock; + QPointer runner; + QString matchCategory; + QString id; + QString text; + QString subtext; + QString mimeType; + QList urls; + QIcon icon; + QString iconName; + QVariant data; + qreal categoryRelevance = 50; + qreal relevance = .7; + KRunner::Action selAction; + KRunner::Actions actions; + bool enabled = true; + bool idSetByData = false; + bool multiLine = false; +}; + +QueryMatch::QueryMatch(AbstractRunner *runner) + : d(new QueryMatchPrivate(runner)) +{ +} + +QueryMatch::QueryMatch(const QueryMatch &other) + : d(other.d) +{ +} + +QueryMatch::~QueryMatch() = default; + +bool QueryMatch::isValid() const +{ + return d->runner != nullptr; +} + +QString QueryMatch::id() const +{ + if (d->id.isEmpty() && d->runner) { + return d->runner.data()->id(); + } + + return d->id; +} + +void QueryMatch::setCategoryRelevance(qreal relevance) +{ + d->categoryRelevance = qBound(0.0, relevance, 100.0); +} + +qreal QueryMatch::categoryRelevance() const +{ + return d->categoryRelevance; +} + +void QueryMatch::setMatchCategory(const QString &category) +{ + d->matchCategory = category; +} + +QString QueryMatch::matchCategory() const +{ + if (d->matchCategory.isEmpty() && d->runner) { + return d->runner->name(); + } + return d->matchCategory; +} + +void QueryMatch::setRelevance(qreal relevance) +{ + d->relevance = qMax(qreal(0.0), relevance); +} + +qreal QueryMatch::relevance() const +{ + return d->relevance; +} + +AbstractRunner *QueryMatch::runner() const +{ + return d->runner.data(); +} + +void QueryMatch::setText(const QString &text) +{ + QWriteLocker locker(&d->lock); + d->text = text; +} + +void QueryMatch::setSubtext(const QString &subtext) +{ + QWriteLocker locker(&d->lock); + d->subtext = subtext; +} + +void QueryMatch::setData(const QVariant &data) +{ + QWriteLocker locker(&d->lock); + d->data = data; + + if (d->id.isEmpty() || d->idSetByData) { + const QString matchId = data.toString(); + if (!matchId.isEmpty()) { + d->setId(matchId); + d->idSetByData = true; + } + } +} + +void QueryMatch::setId(const QString &id) +{ + QWriteLocker locker(&d->lock); + d->setId(id); +} + +void QueryMatch::setIcon(const QIcon &icon) +{ + QWriteLocker locker(&d->lock); + d->icon = icon; +} + +void QueryMatch::setIconName(const QString &iconName) +{ + QWriteLocker locker(&d->lock); + d->iconName = iconName; +} + +QVariant QueryMatch::data() const +{ + QReadLocker locker(&d->lock); + return d->data; +} + +QString QueryMatch::text() const +{ + QReadLocker locker(&d->lock); + return d->text; +} + +QString QueryMatch::subtext() const +{ + QReadLocker locker(&d->lock); + return d->subtext; +} + +QIcon QueryMatch::icon() const +{ + QReadLocker locker(&d->lock); + return d->icon; +} + +QString QueryMatch::iconName() const +{ + QReadLocker locker(&d->lock); + return d->iconName; +} + +void QueryMatch::setUrls(const QList &urls) +{ + QWriteLocker locker(&d->lock); + d->urls = urls; +} + +QList QueryMatch::urls() const +{ + QReadLocker locker(&d->lock); + return d->urls; +} + +void QueryMatch::setEnabled(bool enabled) +{ + d->enabled = enabled; +} + +bool QueryMatch::isEnabled() const +{ + return d->enabled && d->runner; +} + +KRunner::Action QueryMatch::selectedAction() const +{ + return d->selAction; +} + +void QueryMatch::setSelectedAction(const KRunner::Action &action) +{ + d->selAction = action; +} + +void QueryMatch::setMultiLine(bool multiLine) +{ + d->multiLine = multiLine; +} + +bool QueryMatch::isMultiLine() const +{ + return d->multiLine; +} + +QueryMatch &QueryMatch::operator=(const QueryMatch &other) +{ + if (d != other.d) { + d = other.d; + } + + return *this; +} + +bool QueryMatch::operator==(const QueryMatch &other) const +{ + return (d == other.d); +} + +bool QueryMatch::operator!=(const QueryMatch &other) const +{ + return (d != other.d); +} + +void QueryMatch::setActions(const QList &actions) +{ + QWriteLocker locker(&d->lock); + d->actions = actions; +} + +void QueryMatch::addAction(const KRunner::Action &action) +{ + QWriteLocker locker(&d->lock); + d->actions << action; +} + +KRunner::Actions QueryMatch::actions() const +{ + QReadLocker locker(&d->lock); + return d->actions; +} + +QDebug operator<<(QDebug debug, const KRunner::QueryMatch &match) +{ + QDebugStateSaver saver(debug); + debug.nospace() << "QueryMatch(category: " << match.matchCategory() << " text:" << match.text() << ")"; + return debug; +} + +} // KRunner namespace diff --git a/src/querymatch.h b/src/querymatch.h new file mode 100644 index 0000000..3080c34 --- /dev/null +++ b/src/querymatch.h @@ -0,0 +1,305 @@ +/* + SPDX-FileCopyrightText: 2006-2007 Aaron Seigo + SPDX-FileCopyrightText: 2023 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#ifndef KRUNNER_QUERYMATCH_H +#define KRUNNER_QUERYMATCH_H + +#include +#include +#include + +#include "krunner_export.h" + +class QIcon; +class QVariant; + +namespace KRunner +{ +class Action; +class AbstractRunner; +class QueryMatchPrivate; + +/** + * @class QueryMatch querymatch.h + * + * @short A match returned by an AbstractRunner in response to a given RunnerContext. + */ +class KRUNNER_EXPORT QueryMatch +{ +public: + /** + * Constructs a PossibleMatch associated with a given RunnerContext + * and runner. + * + * @param runner the runner this match belongs to + */ + explicit QueryMatch(AbstractRunner *runner = nullptr); + + /** + * Copy constructor + */ + QueryMatch(const QueryMatch &other); + + ~QueryMatch(); + QueryMatch &operator=(const QueryMatch &other); + bool operator==(const QueryMatch &other) const; + bool operator!=(const QueryMatch &other) const; + + /** + * @return the runner associated with this action + */ + AbstractRunner *runner() const; + + /** + * @return true if the match is valid and can therefore be run, + * an invalid match does not have an associated AbstractRunner + */ + bool isValid() const; + + /** + * Helper for reading standardized category relevance values + */ + enum class CategoryRelevance { + Lowest = 0, + Low = 30, + Moderate = 50, + High = 70, + Highest = 100, + }; + + /** + * Relevance for matches in the category. The match with the highest relevance is respected for the entire category. + * This value only affects the sorting of categories and not the sorting within the category. Use @ref setRelevance for this. + * The value should be from 0 to 100. + * + * @since 6.0 + */ + void setCategoryRelevance(CategoryRelevance relevance) + { + setCategoryRelevance(qToUnderlying(relevance)); + } + + /** + * @internal Internal for now, consumers should utilize CategoryRelevance enum + * + * @since 6.0 + */ + void setCategoryRelevance(qreal relevance); + + /** + * Category relevance for this match + * + * @since 6.0 + */ + qreal categoryRelevance() const; + + /** + * Sets information about the type of the match which is + * used to group the matches. + * + * This string should be translated as it is displayed in an UI. + * The default is @ref AbstractRunner::name + */ + void setMatchCategory(const QString &category); + + /** + * Extra information about the match which can be used + * to categorize the type. + * + * The default is @ref AbstractRunner::name + */ + QString matchCategory() const; + + /** + * Sets the relevance of this action for the search + * it was created for. + * + * @param relevance a number between 0 and 1. + */ + void setRelevance(qreal relevance); + + /** + * The relevance of this action to the search. By default, + * the relevance is 1. + * + * @return a number between 0 and 1 + */ + qreal relevance() const; + + /** + * Sets data to be used internally by the runner's @ref AbstractRunner::run implementation. + * + * When set, it is also used to form part of the @ref id for this match. + * If that is inappropriate as an id, the runner may generate its own + * id and set that with @ref setId + */ + void setData(const QVariant &data); + + /** + * @return the data associated with this match; usually runner-specific + */ + QVariant data() const; + + /** + * Sets the id for this match; useful if the id does not + * match data().toString(). The id must be unique to all + * matches from this runner, and should remain constant + * for the same query for best results. + * + * If the "X-Plasma-Runner-Unique-Results" property from the metadata + * is set to true, the runnerId will not be prepended to the ID. + * This allows KRunner to de-duplicate results from different runners. + * In case the runner's matches are less specific than ones from other runners, the + * "X-Plasma-Runner-Weak-Results" property can be set so that duplicates from this + * runner are removed. + * + * @param id the new identifying string to use to refer + * to this entry + */ + void setId(const QString &id); + + /** + * @return a string that can be used as an ID for this match, + * even between different queries. It is based in part + * on the source of the match (the AbstractRunner) and + * distinguishing information provided by the runner, + * ensuring global uniqueness as well as consistency + * between query matches. + */ + QString id() const; + + /** + * Sets the main title text for this match; should be short + * enough to fit nicely on one line in a user interface + * For styled and multiline text, @ref setMultiLine should be set to true + * + * @param text the text to use as the title + */ + void setText(const QString &text); + + /** + * @return the title text for this match + */ + QString text() const; + + /** + * Sets the descriptive text for this match; can be longer + * than the main title text + * + * @param text the text to use as the description + */ + void setSubtext(const QString &text); + + /** + * @return the descriptive text for this match + */ + QString subtext() const; + + /** + * Sets the icon associated with this match + * + * Prefer using setIconName. + * + * @param icon the icon to show along with the match + */ + void setIcon(const QIcon &icon); + + /** + * @return the icon for this match + */ + QIcon icon() const; + + /** + * Sets the icon name associated with this match + * + * @param icon the name of the icon to show along with the match + * @since 5.24 + */ + void setIconName(const QString &iconName); + + /** + * @return the name of the icon for this match + * @since 5.24 + */ + QString iconName() const; + + /** + * Sets the urls, if any, associated with this match + */ + void setUrls(const QList &urls); + + /** + * @return the urls for this match, empty list if none + * These will be used in the default implementation of AbstractRunner::mimeDataForMatch + */ + QList urls() const; + + /** + * Sets whether or not this match can be activited + * + * @param enable true if the match is enabled and therefore runnable + */ + void setEnabled(bool enable); + + /** + * @return true if the match is enabled and therefore runnable, otherwise false + */ + bool isEnabled() const; + + /** + * Set the actions for this match. + * This method allows you to set the actions inside of the AbstractRunner::match method + * @see RunnerManager::actionsForMatch + * @since 5.75 + */ + void setActions(const QList &actions); + + /** + * Adds an action to this match + * @since 5.75 + * @see setActions + */ + void addAction(const KRunner::Action &action); + + /** + * List of actions set for this match + * @return actions + * @since 5.75 + */ + QList actions() const; + + /** + * The action that the user has selected when running the match. + * This returns a nullptr if no action was selected. + */ + KRunner::Action selectedAction() const; + + /** + * Set if the text should be displayed as a multiLine string + * @param multiLine + * @since 5.82 + */ + void setMultiLine(bool multiLine); + + /** + * If the text should be displayed as a multiLine string + * If no explicit value is set set using setMultiline it will default to false + * @return bool + * @since 5.82 + */ + bool isMultiLine() const; + +private: + KRUNNER_NO_EXPORT void setSelectedAction(const KRunner::Action &action); + friend class RunnerManager; + QSharedDataPointer d; +}; + +/// @since 6.0 +KRUNNER_EXPORT QDebug operator<<(QDebug debug, const KRunner::QueryMatch &match); +} +#endif diff --git a/src/runnercontext.cpp b/src/runnercontext.cpp new file mode 100644 index 0000000..7c89468 --- /dev/null +++ b/src/runnercontext.cpp @@ -0,0 +1,315 @@ +/* + SPDX-FileCopyrightText: 2006-2007 Aaron Seigo + SPDX-FileCopyrightText: 2023 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include "runnercontext.h" + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "abstractrunner.h" +#include "abstractrunner_p.h" +#include "querymatch.h" +#include "runnermanager.h" + +namespace KRunner +{ +KRUNNER_EXPORT int __changeCountBeforeSaving = 5; // For tests +class RunnerContextPrivate : public QSharedData +{ +public: + explicit RunnerContextPrivate(RunnerManager *manager) + : QSharedData() + , m_manager(manager) + { + } + + RunnerContextPrivate(const RunnerContextPrivate &p) + : QSharedData(p) + , m_manager(p.m_manager) + , launchCounts(p.launchCounts) + , changedLaunchCounts(p.changedLaunchCounts) + { + } + + ~RunnerContextPrivate() + { + } + + void invalidate() + { + m_isValid = false; + } + + void addMatch(const QueryMatch &match) + { + if (match.runner() && match.runner()->d->hasUniqueResults) { + if (uniqueIds.contains(match.id())) { + const QueryMatch &existentMatch = uniqueIds.value(match.id()); + if (existentMatch.runner() && existentMatch.runner()->d->hasWeakResults) { + // There is an existing match with the same ID and we are allowed to replace it + matches.removeOne(existentMatch); + matches.append(match); + } + } else { + // There is no existing match with the same id + uniqueIds.insert(match.id(), match); + matches.append(match); + } + } else { + // Runner has the unique results property not set + matches.append(match); + } + } + + void matchesChanged() + { + if (m_manager) { + QMetaObject::invokeMethod(m_manager, "onMatchesChanged"); + } + } + + QReadWriteLock lock; + QPointer m_manager; + bool m_isValid = true; + QList matches; + QHash launchCounts; + int changedLaunchCounts = 0; // We want to sync them while the app is running, but for each query it is overkill + QString term; + bool singleRunnerQueryMode = false; + bool shouldIgnoreCurrentMatchForHistory = false; + QMap uniqueIds; + QString requestedText; + int requestedCursorPosition = 0; + qint64 queryStartTs = 0; +}; + +RunnerContext::RunnerContext(RunnerManager *manager) + : d(new RunnerContextPrivate(manager)) +{ +} + +// copy ctor +RunnerContext::RunnerContext(const RunnerContext &other) +{ + QReadLocker locker(&other.d->lock); + d = other.d; +} + +RunnerContext::~RunnerContext() +{ +} + +RunnerContext &RunnerContext::operator=(const RunnerContext &other) +{ + if (this->d == other.d) { + return *this; + } + + auto oldD = d; // To avoid the old ptr getting destroyed while the mutex is locked + QWriteLocker locker(&d->lock); + QReadLocker otherLocker(&other.d->lock); + d = other.d; + return *this; +} + +/** + * Resets the search term for this object. + * This removes all current matches in the process and + * turns off single runner query mode. + * Copies of this object that are used by runner are invalidated + * and adding matches will be a noop. + */ +void RunnerContext::reset() +{ + { + QWriteLocker locker(&d->lock); + // We will detach if we are a copy of someone. But we will reset + // if we are the 'main' context others copied from. Resetting + // one RunnerContext makes all the copies obsolete. + + // We need to mark the q pointer of the detached RunnerContextPrivate + // as dirty on detach to avoid receiving results for old queries + d->invalidate(); + } + + d.detach(); + // But out detached version is valid! + d->m_isValid = true; + + // we still have to remove all the matches, since if the + // ref count was 1 (e.g. only the RunnerContext is using + // the dptr) then we won't get a copy made + d->matches.clear(); + d->term.clear(); + d->matchesChanged(); + + d->uniqueIds.clear(); + d->singleRunnerQueryMode = false; + d->shouldIgnoreCurrentMatchForHistory = false; +} + +void RunnerContext::setQuery(const QString &term) +{ + if (!this->query().isEmpty()) { + reset(); + } + + if (term.isEmpty()) { + return; + } + + d->requestedText.clear(); // Invalidate this field whenever the query changes + d->term = term; +} + +QString RunnerContext::query() const +{ + // the query term should never be set after + // a search starts. in fact, reset() ensures this + // and setQuery(QString) calls reset() + return d->term; +} + +bool RunnerContext::isValid() const +{ + QReadLocker locker(&d->lock); + return d->m_isValid; +} + +bool RunnerContext::addMatches(const QList &matches) +{ + if (matches.isEmpty() || !isValid()) { + // Bail out if the query is empty or the qptr is dirty + return false; + } + + { + QWriteLocker locker(&d->lock); + for (QueryMatch match : matches) { + // Give previously launched matches a slight boost in relevance + // The boost smoothly saturates to 0.5; + if (int count = d->launchCounts.value(match.id())) { + match.setRelevance(match.relevance() + 0.5 * (1 - exp(-count * 0.3))); + } + d->addMatch(match); + } + } + d->matchesChanged(); + + return true; +} + +bool RunnerContext::addMatch(const QueryMatch &match) +{ + return addMatches({match}); +} + +QList RunnerContext::matches() const +{ + QReadLocker locker(&d->lock); + QList matches = d->matches; + return matches; +} + +void RunnerContext::requestQueryStringUpdate(const QString &text, int cursorPosition) const +{ + d->requestedText = text; + d->requestedCursorPosition = cursorPosition; +} + +void RunnerContext::setSingleRunnerQueryMode(bool enabled) +{ + d->singleRunnerQueryMode = enabled; +} + +bool RunnerContext::singleRunnerQueryMode() const +{ + return d->singleRunnerQueryMode; +} + +void RunnerContext::ignoreCurrentMatchForHistory() const +{ + d->shouldIgnoreCurrentMatchForHistory = true; +} + +bool RunnerContext::shouldIgnoreCurrentMatchForHistory() const +{ + return d->shouldIgnoreCurrentMatchForHistory; +} + +/** + * Sets the launch counts for the associated match ids + * + * If a runner adds a match to this context, the context will check if the + * match id has been launched before and increase the matches relevance + * correspondingly. In this manner, any front end can implement adaptive search + * by sorting items according to relevance. + * + * @param config the config group where launch data was stored + */ +void RunnerContext::restore(const KConfigGroup &config) +{ + const QStringList cfgList = config.readEntry("LaunchCounts", QStringList()); + + for (const QString &entry : cfgList) { + if (int idx = entry.indexOf(QLatin1Char(' ')); idx != -1) { + const int count = entry.mid(0, idx).toInt(); + const QString id = entry.mid(idx + 1); + d->launchCounts[id] = count; + } + } +} + +void RunnerContext::save(KConfigGroup &config) +{ + if (d->changedLaunchCounts < __changeCountBeforeSaving) { + return; + } + d->changedLaunchCounts = 0; + QStringList countList; + countList.reserve(d->launchCounts.size()); + for (auto it = d->launchCounts.cbegin(), end = d->launchCounts.cend(); it != end; ++it) { + countList << QString::number(it.value()) + QLatin1Char(' ') + it.key(); + } + + config.writeEntry("LaunchCounts", countList); + config.sync(); +} + +void RunnerContext::increaseLaunchCount(const QueryMatch &match) +{ + ++d->launchCounts[match.id()]; + ++d->changedLaunchCounts; +} + +QString RunnerContext::requestedQueryString() const +{ + return d->requestedText; +} +int RunnerContext::requestedCursorPosition() const +{ + return d->requestedCursorPosition; +} + +void RunnerContext::setJobStartTs(qint64 queryStartTs) +{ + d->queryStartTs = queryStartTs; +} +QString RunnerContext::runnerJobId(AbstractRunner *runner) const +{ + return QLatin1String("%1-%2-%3").arg(runner->id(), query(), QString::number(d->queryStartTs)); +} + +} // KRunner namespace diff --git a/src/runnercontext.h b/src/runnercontext.h new file mode 100644 index 0000000..3cf5f5f --- /dev/null +++ b/src/runnercontext.h @@ -0,0 +1,142 @@ +/* + SPDX-FileCopyrightText: 2006-2007 Aaron Seigo + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#ifndef KRUNNER_RUNNERCONTEXT_H +#define KRUNNER_RUNNERCONTEXT_H + +#include +#include +#include + +#include "krunner_export.h" + +class KConfigGroup; + +namespace KRunner +{ +class RunnerManager; +class QueryMatch; +class AbstractRunner; +class RunnerContextPrivate; + +/** + * @class RunnerContext runnercontext.h + * + * @short The RunnerContext class provides information related to a search, + * including the search term and collected matches. + */ +class KRUNNER_EXPORT RunnerContext final +{ +public: + explicit RunnerContext(RunnerManager *manager = nullptr); + + /** + * Copy constructor + */ + RunnerContext(const RunnerContext &other); + + /** + * Assignment operator + */ + RunnerContext &operator=(const RunnerContext &other); + + ~RunnerContext(); + + /** + * Sets the query term for this object and attempts to determine + * the type of the search. + */ + void setQuery(const QString &term); + + /** + * @return the current search query term. + */ + QString query() const; + + /** + * @returns true if this context is no longer valid and therefore + * matching using it should abort. + * While not required to be used within runners, it provides a nice way + * to avoid unnecessary processing in runners that may run for an extended + * period (as measured in 10s of ms) and therefore improve the user experience. + */ + bool isValid() const; + + /** + * Appends lists of matches to the list of matches. + * + * @param matches the matches to add + * @return true if matches were added, false if matches were e.g. outdated + */ + bool addMatches(const QList &matches); + + /** + * Appends a match to the existing list of matches. + * + * If you are going to be adding multiple matches, it is + * more performant to use @see addMatches instead. + * + * @param match the match to add + * @return true if the match was added, false otherwise. + */ + bool addMatch(const QueryMatch &match); + + /** + * Retrieves all available matches for the current search term. + * + * @return a list of matches + */ + QList matches() const; + + /** + * Request that KRunner updates the query string and stasy open, even after running a match. + * This method is const so it can be called in a const context. + * + * @param text Text that will be displayed in the search field + * @param cursorPosition Position of the cursor, if this is different than the length of the text, + * the characters between the position and text will be selected + * + * @since 5.90 + */ + void requestQueryStringUpdate(const QString &text, int cursorPosition) const; + + /** + * @return true if the current query is a single runner query + */ + bool singleRunnerQueryMode() const; + + /** + * Set this to true in the AbstractRunner::run method to prevent the entry + * from being saved to the history. + * @since 5.90 + */ + void ignoreCurrentMatchForHistory() const; + +private: + KRUNNER_NO_EXPORT void increaseLaunchCount(const QueryMatch &match); + KRUNNER_NO_EXPORT QString requestedQueryString() const; + KRUNNER_NO_EXPORT int requestedCursorPosition() const; + KRUNNER_NO_EXPORT bool shouldIgnoreCurrentMatchForHistory() const; + // Sets single runner query mode. Note that a call to reset() will turn off single runner query mode. + KRUNNER_NO_EXPORT void setSingleRunnerQueryMode(bool enabled); + + friend class RunnerManager; + friend class AbstractRunner; + friend class DBusRunner; + friend class RunnerManagerPrivate; + + KRUNNER_NO_EXPORT void restore(const KConfigGroup &config); + KRUNNER_NO_EXPORT void save(KConfigGroup &config); + KRUNNER_NO_EXPORT void reset(); + KRUNNER_NO_EXPORT void setJobStartTs(qint64 queryStartTs); + KRUNNER_NO_EXPORT QString runnerJobId(AbstractRunner *runner) const; + + QExplicitlySharedDataPointer d; +}; +} + +Q_DECLARE_METATYPE(KRunner::RunnerContext) +#endif diff --git a/src/runnermanager.cpp b/src/runnermanager.cpp new file mode 100644 index 0000000..f16d617 --- /dev/null +++ b/src/runnermanager.cpp @@ -0,0 +1,716 @@ +/* + SPDX-FileCopyrightText: 2006 Aaron Seigo + SPDX-FileCopyrightText: 2007, 2009 Ryan P. Bitanga + SPDX-FileCopyrightText: 2008 Jordi Polo + SPDX-FileCopyrightText: 2023 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include "runnermanager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "abstractrunner_p.h" +#include "dbusrunner_p.h" +#include "kpluginmetadata_utils_p.h" +#include "krunner_debug.h" +#include "querymatch.h" + +namespace KRunner +{ +class RunnerManagerPrivate +{ +public: + RunnerManagerPrivate(const KConfigGroup &configurationGroup, const KConfigGroup &stateConfigGroup, RunnerManager *parent) + : q(parent) + , context(parent) + , pluginConf(configurationGroup) + , stateData(stateConfigGroup) + { + initializeKNotifyPluginWatcher(); + matchChangeTimer.setSingleShot(true); + matchChangeTimer.setTimerType(Qt::TimerType::PreciseTimer); // Without this, autotest will fail due to imprecision of this timer + + QObject::connect(&matchChangeTimer, &QTimer::timeout, q, [this]() { + matchesChanged(); + }); + + // Set up tracking of the last time matchesChanged was signalled + lastMatchChangeSignalled.start(); + QObject::connect(q, &RunnerManager::matchesChanged, q, [&] { + lastMatchChangeSignalled.restart(); + }); + loadConfiguration(); + } + + void scheduleMatchesChanged() + { + // We avoid over-refreshing the client. We only refresh every this much milliseconds + constexpr int refreshPeriod = 250; + // This will tell us if we are reseting the matches to start a new search. RunnerContext::reset() clears its query string for its emission + if (context.query().isEmpty()) { + matchChangeTimer.stop(); + // This actually contains the query string for the new search that we're launching (if any): + if (!this->untrimmedTerm.trimmed().isEmpty()) { + // We are starting a new search, we shall stall for some time before deciding to show an empty matches list. + // This stall should be enough for the engine to provide more meaningful result, so we avoid refreshing with + // an empty results list if possible. + matchChangeTimer.start(refreshPeriod); + // We "pretend" that we have refreshed it so the next call will be forced to wait the timeout: + lastMatchChangeSignalled.restart(); + } else { + // We have an empty input string, so it's not a real query. We don't expect any results to come, so no need to stall + Q_EMIT q->matchesChanged(context.matches()); + } + } else if (lastMatchChangeSignalled.hasExpired(refreshPeriod)) { + matchChangeTimer.stop(); + Q_EMIT q->matchesChanged(context.matches()); + } else { + matchChangeTimer.start(refreshPeriod - lastMatchChangeSignalled.elapsed()); + } + } + + void matchesChanged() + { + Q_EMIT q->matchesChanged(context.matches()); + } + + void loadConfiguration() + { + const KConfigGroup generalConfig = pluginConf.config()->group(QStringLiteral("General")); + context.restore(stateData); + } + + void loadSingleRunner() + { + // In case we are not in the single runner mode of we do not have an id + if (!singleMode || singleModeRunnerId.isEmpty()) { + currentSingleRunner = nullptr; + return; + } + + if (currentSingleRunner && currentSingleRunner->id() == singleModeRunnerId) { + return; + } + currentSingleRunner = q->runner(singleModeRunnerId); + // If there are no runners loaded or the single runner could no be loaded, + // this is the case if it was disabled but gets queries using the singleRunnerMode, BUG: 435050 + if (runners.isEmpty() || !currentSingleRunner) { + loadRunners(singleModeRunnerId); + currentSingleRunner = q->runner(singleModeRunnerId); + } + } + + void deleteRunners(const QList &runners) + { + for (const auto runner : runners) { + if (qobject_cast(runner)) { + runner->deleteLater(); + } else { + Q_ASSERT(runner->thread() != q->thread()); + runner->thread()->quit(); + QObject::connect(runner->thread(), &QThread::finished, runner->thread(), &QObject::deleteLater); + QObject::connect(runner->thread(), &QThread::finished, runner, &QObject::deleteLater); + } + } + } + + void loadRunners(const QString &singleRunnerId = QString()) + { + QList offers = RunnerManager::runnerMetaDataList(); + + const bool loadAll = stateData.readEntry("loadAll", false); + const bool noWhiteList = whiteList.isEmpty(); + + QList deadRunners; + QMutableListIterator it(offers); + while (it.hasNext()) { + const KPluginMetaData &description = it.next(); + qCDebug(KRUNNER) << "Loading runner: " << description.pluginId(); + + const QString runnerName = description.pluginId(); + const bool isPluginEnabled = description.isEnabled(pluginConf); + const bool loaded = runners.contains(runnerName); + bool selected = loadAll || disabledRunnerIds.contains(runnerName) || (isPluginEnabled && (noWhiteList || whiteList.contains(runnerName))); + if (!selected && runnerName == singleRunnerId) { + selected = true; + disabledRunnerIds << runnerName; + } + + if (selected) { + if (!loaded) { + if (auto runner = loadInstalledRunner(description)) { + qCDebug(KRUNNER) << "Loaded:" << runnerName; + runners.insert(runnerName, runner); + } + } + } else if (loaded) { + // Remove runner + deadRunners.append(runners.take(runnerName)); + qCDebug(KRUNNER) << "Plugin disabled. Removing runner: " << runnerName; + } + } + + deleteRunners(deadRunners); + // in case we deleted it up above, just to be sure we do not have a dangeling pointer + currentSingleRunner = nullptr; + qCDebug(KRUNNER) << "All runners loaded, total:" << runners.count(); + } + + AbstractRunner *loadInstalledRunner(const KPluginMetaData &pluginMetaData) + { + if (!pluginMetaData.isValid()) { + return nullptr; + } + + AbstractRunner *runner = nullptr; + + const QString api = pluginMetaData.value(QStringLiteral("X-Plasma-API")); + const bool isCppPlugin = api.isEmpty(); + + if (isCppPlugin) { + if (auto res = KPluginFactory::instantiatePlugin(pluginMetaData, q)) { + runner = res.plugin; + } else { + qCWarning(KRUNNER).nospace() << "Could not load runner " << pluginMetaData.name() << ":" << res.errorString + << " (library path was:" << pluginMetaData.fileName() << ")"; + } + } else if (api.startsWith(QLatin1String("DBus"))) { + runner = new DBusRunner(q, pluginMetaData); + } else { + qCWarning(KRUNNER) << "Unknown X-Plasma-API requested for runner" << pluginMetaData.fileName(); + return nullptr; + } + + if (runner) { + QPointer ptr(runner); + q->connect(runner, &AbstractRunner::matchingResumed, q, [this, ptr]() { + if (ptr) { + runnerMatchingResumed(ptr.get()); + } + }); + if (isCppPlugin) { + auto thread = new QThread(); + thread->setObjectName(pluginMetaData.pluginId()); + thread->start(); + runner->moveToThread(thread); + } + // The runner might outlive the manager due to us waiting for the thread to exit + q->connect(runner, &AbstractRunner::matchInternalFinished, q, [this](const QString &jobId) { + onRunnerJobFinished(jobId); + }); + + if (prepped) { + Q_EMIT runner->prepare(); + } + } + + return runner; + } + + void onRunnerJobFinished(const QString &jobId) + { + if (currentJobs.remove(jobId) && currentJobs.isEmpty()) { + // If there are any new matches scheduled to be notified, we should anticipate it and just refresh right now + if (matchChangeTimer.isActive()) { + matchChangeTimer.stop(); + matchesChanged(); + } else if (context.matches().isEmpty()) { + // we finished our run, and there are no valid matches, and so no + // signal will have been sent out, so we need to emit the signal ourselves here + matchesChanged(); + } + setQuerying(false); + Q_EMIT q->queryFinished(); + } + if (!currentJobs.isEmpty()) { + qCDebug(KRUNNER) << "Current jobs are" << currentJobs; + } + } + + void teardown() + { + pendingJobsAfterSuspend.clear(); // Do not start old jobs when the match session is over + if (allRunnersPrepped) { + for (AbstractRunner *runner : std::as_const(runners)) { + Q_EMIT runner->teardown(); + } + allRunnersPrepped = false; + } + + if (singleRunnerPrepped) { + if (currentSingleRunner) { + Q_EMIT currentSingleRunner->teardown(); + } + singleRunnerPrepped = false; + } + + prepped = false; + } + + void runnerMatchingResumed(AbstractRunner *runner) + { + Q_ASSERT(runner); + const QString jobId = pendingJobsAfterSuspend.value(runner); + if (jobId.isEmpty()) { + qCDebug(KRUNNER) << runner << "was not scheduled for current query"; + return; + } + // Ignore this runner + if (singleMode && runner->id() != singleModeRunnerId) { + qCDebug(KRUNNER) << runner << "did not match requested singlerunnermode ID"; + return; + } + + const QString query = context.query(); + bool matchesCount = singleMode || runner->minLetterCount() <= query.size(); + bool matchesRegex = singleMode || !runner->hasMatchRegex() || runner->matchRegex().match(query).hasMatch(); + + if (matchesCount && matchesRegex) { + startJob(runner); + } else { + onRunnerJobFinished(jobId); + } + } + + void startJob(AbstractRunner *runner) + { + QMetaObject::invokeMethod(runner, "matchInternal", Qt::QueuedConnection, Q_ARG(KRunner::RunnerContext, context)); + } + + // Must only be called once + void initializeKNotifyPluginWatcher() + { + Q_ASSERT(!watcher); + watcher = KConfigWatcher::create(KSharedConfig::openConfig(pluginConf.config()->name())); + q->connect(watcher.data(), &KConfigWatcher::configChanged, q, [this](const KConfigGroup &group, const QByteArrayList &changedNames) { + const QString groupName = group.name(); + if (groupName == QLatin1String("Plugins")) { + q->reloadConfiguration(); + } else if (groupName == QLatin1String("Runners")) { + for (auto *runner : std::as_const(runners)) { + // Signals from the KCM contain the component name, which is the KRunner plugin's id + if (changedNames.contains(runner->metadata().pluginId().toUtf8())) { + QMetaObject::invokeMethod(runner, "reloadConfigurationInternal"); + } + } + } else if (group.parent().isValid() && group.parent().name() == QLatin1String("Runners")) { + for (auto *runner : std::as_const(runners)) { + // If the same config group has been modified which gets created in AbstractRunner::config() + if (groupName == runner->id()) { + QMetaObject::invokeMethod(runner, "reloadConfigurationInternal"); + } + } + } + }); + } + + void setQuerying(bool querying) + { + if (m_querying != querying) { + m_querying = querying; + Q_EMIT q->queryingChanged(); + } + } + + void addToHistory() + { + const QString term = context.query(); + // We want to imitate the shall behavior + if (!historyEnabled || term.isEmpty() || untrimmedTerm.startsWith(QLatin1Char(' '))) { + return; + } + QStringList historyEntries = readHistoryForCurrentEnv(); + // Avoid removing the same item from the front and prepending it again + if (!historyEntries.isEmpty() && historyEntries.constFirst() == term) { + return; + } + + historyEntries.removeOne(term); + historyEntries.prepend(term); + + while (historyEntries.count() > 50) { // we don't want to store more than 50 entries + historyEntries.removeLast(); + } + writeHistory(historyEntries); + } + + void writeHistory(const QStringList &historyEntries) + { + stateData.group(QStringLiteral("History")).writeEntry(historyEnvironmentIdentifier, historyEntries, KConfig::Notify); + stateData.sync(); + } + + inline QStringList readHistoryForCurrentEnv() + { + return stateData.group(QStringLiteral("History")).readEntry(historyEnvironmentIdentifier, QStringList()); + } + + QString historyEnvironmentIdentifier = QStringLiteral("default"); + RunnerManager *const q; + bool m_querying = false; + RunnerContext context; + QTimer matchChangeTimer; + QElapsedTimer lastMatchChangeSignalled; + QHash runners; + QHash pendingJobsAfterSuspend; + AbstractRunner *currentSingleRunner = nullptr; + QSet currentJobs; + QString singleModeRunnerId; + bool prepped = false; + bool allRunnersPrepped = false; + bool singleRunnerPrepped = false; + bool singleMode = false; + bool historyEnabled = true; + QStringList whiteList; + KConfigWatcher::Ptr watcher; + QString untrimmedTerm; + KConfigGroup pluginConf; + KConfigGroup stateData; + QSet disabledRunnerIds; // Runners that are disabled but were loaded as single runners +}; + +RunnerManager::RunnerManager(const KConfigGroup &pluginConfigGroup, const KConfigGroup &stateConfigGroup, QObject *parent) + : QObject(parent) + , d(new RunnerManagerPrivate(pluginConfigGroup, stateConfigGroup, this)) +{ + Q_ASSERT(pluginConfigGroup.isValid()); + Q_ASSERT(stateConfigGroup.isValid()); +} + +RunnerManager::RunnerManager(QObject *parent) + : QObject(parent) +{ + auto defaultStatePtr = KSharedConfig::openConfig(QStringLiteral("krunnerstaterc"), KConfig::NoGlobals, QStandardPaths::GenericDataLocation); + auto configPtr = KSharedConfig::openConfig(QStringLiteral("krunnerrc"), KConfig::NoGlobals); + d = std::make_unique(configPtr->group(QStringLiteral("Plugins")), + defaultStatePtr->group(QStringLiteral("PlasmaRunnerManager")), + this); +} + +RunnerManager::~RunnerManager() +{ + d->context.reset(); + d->deleteRunners(d->runners.values()); +} + +void RunnerManager::reloadConfiguration() +{ + d->pluginConf.config()->reparseConfiguration(); + d->stateData.config()->reparseConfiguration(); + d->loadConfiguration(); + d->loadRunners(); +} + +void RunnerManager::setAllowedRunners(const QStringList &runners) +{ + d->whiteList = runners; + if (!d->runners.isEmpty()) { + // this has been called with runners already created. so let's do an instant reload + d->loadRunners(); + } +} + +AbstractRunner *RunnerManager::loadRunner(const KPluginMetaData &pluginMetaData) +{ + const QString runnerId = pluginMetaData.pluginId(); + if (auto loadedRunner = d->runners.value(runnerId)) { + return loadedRunner; + } + if (!runnerId.isEmpty()) { + if (AbstractRunner *runner = d->loadInstalledRunner(pluginMetaData)) { + d->runners.insert(runnerId, runner); + return runner; + } + } + return nullptr; +} + +AbstractRunner *RunnerManager::runner(const QString &pluginId) const +{ + if (d->runners.isEmpty()) { + d->loadRunners(); + } + + return d->runners.value(pluginId, nullptr); +} + +QList RunnerManager::runners() const +{ + if (d->runners.isEmpty()) { + d->loadRunners(); + } + return d->runners.values(); +} + +RunnerContext *RunnerManager::searchContext() const +{ + return &d->context; +} + +QList RunnerManager::matches() const +{ + return d->context.matches(); +} + +bool RunnerManager::run(const QueryMatch &match, const KRunner::Action &selectedAction) +{ + if (!match.isValid() || !match.isEnabled()) { // The model should prevent this + return false; + } + + // Modify the match and run it + QueryMatch m = match; + m.setSelectedAction(selectedAction); + m.runner()->run(d->context, m); + // To allow the RunnerContext to increase the relevance of often launched apps + d->context.increaseLaunchCount(m); + + if (!d->context.shouldIgnoreCurrentMatchForHistory()) { + d->addToHistory(); + } + if (d->context.requestedQueryString().isEmpty()) { + return true; + } else { + Q_EMIT requestUpdateQueryString(d->context.requestedQueryString(), d->context.requestedCursorPosition()); + return false; + } +} + +QMimeData *RunnerManager::mimeDataForMatch(const QueryMatch &match) const +{ + return match.isValid() ? match.runner()->mimeDataForMatch(match) : nullptr; +} + +QList RunnerManager::runnerMetaDataList() +{ + QList pluginMetaDatas = KPluginMetaData::findPlugins(QStringLiteral("kf6/krunner")); + QSet knownRunnerIds; + knownRunnerIds.reserve(pluginMetaDatas.size()); + for (const KPluginMetaData &pluginMetaData : std::as_const(pluginMetaDatas)) { + knownRunnerIds.insert(pluginMetaData.pluginId()); + } + + const QStringList dBusPlugindirs = + QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("krunner/dbusplugins"), QStandardPaths::LocateDirectory); + const QStringList dbusRunnerFiles = KFileUtils::findAllUniqueFiles(dBusPlugindirs, QStringList(QStringLiteral("*.desktop"))); + for (const QString &dbusRunnerFile : dbusRunnerFiles) { + KPluginMetaData pluginMetaData = parseMetaDataFromDesktopFile(dbusRunnerFile); + if (pluginMetaData.isValid() && !knownRunnerIds.contains(pluginMetaData.pluginId())) { + pluginMetaDatas.append(pluginMetaData); + knownRunnerIds.insert(pluginMetaData.pluginId()); + } + } + + return pluginMetaDatas; +} + +void RunnerManager::setupMatchSession() +{ + if (d->prepped) { + return; + } + + d->prepped = true; + if (d->singleMode) { + if (d->currentSingleRunner) { + Q_EMIT d->currentSingleRunner->prepare(); + d->singleRunnerPrepped = true; + } + } else { + for (AbstractRunner *runner : std::as_const(d->runners)) { + if (!d->disabledRunnerIds.contains(runner->name())) { + Q_EMIT runner->prepare(); + } + } + + d->allRunnersPrepped = true; + } +} + +void RunnerManager::matchSessionComplete() +{ + if (!d->prepped) { + return; + } + + d->teardown(); + // We save the context config after each session, just like the history entries + // BUG: 424505 + d->context.save(d->stateData); +} + +void RunnerManager::launchQuery(const QString &untrimmedTerm, const QString &runnerName) +{ + d->pendingJobsAfterSuspend.clear(); // Do not start old jobs when we got a new query + QString term = untrimmedTerm.trimmed(); + const QString prevSingleRunner = d->singleModeRunnerId; + d->untrimmedTerm = untrimmedTerm; + + // Set the required values and load the runner + d->singleModeRunnerId = runnerName; + d->singleMode = !runnerName.isEmpty(); + d->loadSingleRunner(); + // If we could not load the single runner we reset + if (!runnerName.isEmpty() && !d->currentSingleRunner) { + reset(); + return; + } + if (term.isEmpty()) { + QTimer::singleShot(0, this, &RunnerManager::queryFinished); + reset(); + return; + } + + if (d->context.query() == term && prevSingleRunner == runnerName) { + // we already are searching for this! + return; + } + + if (!d->singleMode && d->runners.isEmpty()) { + d->loadRunners(); + } + + reset(); + d->context.setQuery(term); + + QHash runnable; + + // if the name is not empty we will launch only the specified runner + if (d->singleMode) { + runnable.insert(QString(), d->currentSingleRunner); + d->context.setSingleRunnerQueryMode(true); + } else { + runnable = d->runners; + } + + qint64 startTs = QDateTime::currentMSecsSinceEpoch(); + d->context.setJobStartTs(startTs); + setupMatchSession(); + for (KRunner::AbstractRunner *r : std::as_const(runnable)) { + const QString &jobId = d->context.runnerJobId(r); + if (r->isMatchingSuspended()) { + d->pendingJobsAfterSuspend.insert(r, jobId); + d->currentJobs.insert(jobId); + continue; + } + // If this runner is loaded but disabled + if (!d->singleMode && d->disabledRunnerIds.contains(r->id())) { + continue; + } + // The runners can set the min letter count as a property, this way we don't + // have to spawn threads just for the runner to reject the query, because it is too short + if (!d->singleMode && term.length() < r->minLetterCount()) { + continue; + } + // If the runner has one ore more trigger words it can set the matchRegex to prevent + // thread spawning if the pattern does not match + if (!d->singleMode && r->hasMatchRegex() && !r->matchRegex().match(term).hasMatch()) { + continue; + } + + d->currentJobs.insert(jobId); + d->startJob(r); + } + // In the unlikely case that no runner gets queried we have to emit the signals here + if (d->currentJobs.isEmpty()) { + QTimer::singleShot(0, this, [this]() { + d->currentJobs.clear(); + Q_EMIT matchesChanged({}); + Q_EMIT queryFinished(); + }); + d->setQuerying(false); + } else { + d->setQuerying(true); + } +} + +QString RunnerManager::query() const +{ + return d->context.query(); +} + +QStringList RunnerManager::history() const +{ + return d->readHistoryForCurrentEnv(); +} + +void RunnerManager::removeFromHistory(int index) +{ + QStringList changedHistory = history(); + if (index < changedHistory.length()) { + changedHistory.removeAt(index); + d->writeHistory(changedHistory); + } +} + +QString RunnerManager::getHistorySuggestion(const QString &typedQuery) const +{ + const QStringList historyList = history(); + for (const QString &entry : historyList) { + if (entry.startsWith(typedQuery, Qt::CaseInsensitive)) { + return entry; + } + } + return QString(); +} + +void RunnerManager::reset() +{ + if (!d->currentJobs.empty()) { + Q_EMIT queryFinished(); + d->currentJobs.clear(); + } + d->context.reset(); +} + +KPluginMetaData RunnerManager::convertDBusRunnerToJson(const QString &filename) const +{ + return parseMetaDataFromDesktopFile(filename); +} + +bool RunnerManager::historyEnabled() +{ + return d->historyEnabled; +} + +bool RunnerManager::querying() const +{ + return d->m_querying; +} + +void RunnerManager::setHistoryEnabled(bool enabled) +{ + d->historyEnabled = enabled; + Q_EMIT historyEnabledChanged(); +} + +// Gets called by RunnerContext to inform that we got new matches +void RunnerManager::onMatchesChanged() +{ + d->scheduleMatchesChanged(); +} +void RunnerManager::setHistoryEnvironmentIdentifier(const QString &identifier) +{ + Q_ASSERT(!identifier.isEmpty()); + d->historyEnvironmentIdentifier = identifier; +} + +} // KRunner namespace + +#include "moc_runnermanager.cpp" diff --git a/src/runnermanager.h b/src/runnermanager.h new file mode 100644 index 0000000..779648e --- /dev/null +++ b/src/runnermanager.h @@ -0,0 +1,267 @@ +/* + SPDX-FileCopyrightText: 2006 Aaron Seigo + SPDX-FileCopyrightText: 2007 Ryan P. Bitanga + SPDX-FileCopyrightText: 2008 Jordi Polo + SPDX-FileCopyrightText: 2023 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#ifndef KRUNNER_RUNNERMANAGER_H +#define KRUNNER_RUNNERMANAGER_H + +#include +#include + +#include + +#include "abstractrunner.h" +#include "action.h" +#include "krunner_export.h" +#include + +class KConfigGroup; +namespace KRunner +{ +class AbstractRunnerTest; +} + +namespace KRunner +{ +class QueryMatch; +class AbstractRunner; +class RunnerContext; +class RunnerManagerPrivate; + +/** + * @class RunnerManager runnermanager.h + * + * @short The RunnerManager class decides what installed runners are runnable, + * and their ratings. It is the main proxy to the runners. + */ +class KRUNNER_EXPORT RunnerManager : public QObject +{ + Q_OBJECT + Q_PROPERTY(QStringList history READ history) + Q_PROPERTY(bool querying READ querying NOTIFY queryingChanged) + Q_PROPERTY(bool historyEnabled READ historyEnabled WRITE setHistoryEnabled NOTIFY historyEnabledChanged) + +public: + /** + * Constructs a RunnerManager with the given parameters + * @param configurationGroup Config group used for reading enabled plugins + * @param stateGroup Config group used for storing history + * @since 6.0 + */ + explicit RunnerManager(const KConfigGroup &pluginConfigGroup, const KConfigGroup &stateGroup, QObject *parent); + + /** + * Constructs a RunnerManager using the default locations for state/plugin config + */ + explicit RunnerManager(QObject *parent = nullptr); + ~RunnerManager() override; + + /** + * Finds and returns a loaded runner or a nullptr + * @param pluginId the name of the runner plugin + * @return Pointer to the runner + */ + AbstractRunner *runner(const QString &pluginId) const; + + /** + * @return the list of all currently loaded runners + */ + QList runners() const; + + /** + * Retrieves the current context + * @return pointer to the current context + */ + RunnerContext *searchContext() const; + + /** + * Retrieves all available matches found so far for the previously launched query + * @return List of matches + */ + QList matches() const; + + /** + * Runs a given match. This also respects the extra handling for the InformationalMatch. + * This also handles the history automatically + * @param match the match to be executed + * @param selectedAction the action returned by @ref QueryMatch::actions that has been selected by the user, nullptr if none + * @return if the RunnerWindow should close + * @since 6.0 + */ + bool run(const QueryMatch &match, const KRunner::Action &action = {}); + + /** + * @return the current query term set in @ref launchQuery + */ + QString query() const; + + /** + * @return History of this runner for the current activity. If the RunnerManager is not history + * aware the global entries will be returned. + * @since 5.78 + */ + QStringList history() const; + + /** + * Delete the given index from the history. + * @param historyEntry + * @since 5.78 + */ + Q_INVOKABLE void removeFromHistory(int index); + + /** + * Get the suggested history entry for the typed query. If no entry is found an empty string is returned. + * @param typedQuery + * @return completion for typedQuery + * @since 5.78 + */ + Q_INVOKABLE QString getHistorySuggestion(const QString &typedQuery) const; + + /** + * If history completion is enabled, the default value is true. + * @since 5.78 + */ + bool historyEnabled(); + + /** + * If the RunnerManager is currently querying + * @since 6.7 + */ + bool querying() const; + + /** + * Enables/disabled the history feature for the RunnerManager instance. + * The value will not be persisted and is only kept during the object's lifetime. + * + * @since 6.0 + */ + void setHistoryEnabled(bool enabled); + + /** + * Causes a reload of the current configuration + * This gets called automatically when the config in the KCM is saved + */ + void reloadConfiguration(); + + /** + * Sets a whitelist for the plugins that can be loaded by this manager. + * Runners that are disabled through the config will not be loaded. + * + * @param plugins the plugin names of allowed runners + */ + void setAllowedRunners(const QStringList &runners); + + /** + * Attempts to add the AbstractRunner plugin represented + * by the plugin info passed in. Usually one can simply let + * the configuration of plugins handle loading Runner plugins, + * but in cases where specific runners should be loaded this + * allows for that to take place + * @note Consider using @ref setAllowedRunners in case you want to only allow specific runners + * + * @param pluginMetaData the metaData to use to load the plugin + * @return the loaded runner or nullptr + */ + AbstractRunner *loadRunner(const KPluginMetaData &pluginMetaData); + + /** + * @return mime data of the specified match + */ + QMimeData *mimeDataForMatch(const QueryMatch &match) const; + + /** + * @return metadata list of all known Runner plugins + * @since 5.72 + */ + static QList runnerMetaDataList(); + +public Q_SLOTS: + /** + * Call this method when the runners should be prepared for a query session. + * Call matchSessionComplete when the query session is finished for the time + * being. + * @see matchSessionComplete + */ + void setupMatchSession(); + + /** + * Call this method when the query session is finished for the time + * being. + * @see prepareForMatchSession + */ + void matchSessionComplete(); + + /** + * Launch a query, this will create threads and return immediately. + * When the information will be available can be known using the + * matchesChanged signal. + * + * @param term the term we want to find matches for + * @param runnerId optional, if only one specific runner is to be used; + * providing an id will put the manager into single runner mode + */ + void launchQuery(const QString &term, const QString &runnerId = QString()); + + /** + * Reset the current data and stops the query + */ + void reset(); + + /** + * Set the environment identifier for recording history and launch counts + * @internal + * @since 6.0 + */ + Q_INVOKABLE void setHistoryEnvironmentIdentifier(const QString &identifier); + +Q_SIGNALS: + /** + * Emitted each time a new match is added to the list + */ + void matchesChanged(const QList &matches); + + /** + * Emitted when the launchQuery finish + */ + void queryFinished(); + + /** + * Emitted when the querying status has changed + * @since 6.7 + */ + + void queryingChanged(); + + /** + * Put the given search term in the KRunner search field + * @param term The term that should be displayed + * @param cursorPosition Where the cursor should be positioned + * @since 6.0 + */ + void requestUpdateQueryString(const QString &term, int cursorPosition); + + /** + * @see @p historyEnabled + * @since 5.78 + */ + void historyEnabledChanged(); + +private: + // exported for dbusrunnertest + KPluginMetaData convertDBusRunnerToJson(const QString &filename) const; + KRUNNER_NO_EXPORT Q_INVOKABLE void onMatchesChanged(); + + std::unique_ptr d; + + friend class RunnerManagerPrivate; + friend AbstractRunnerTest; + friend AbstractRunner; +}; + +} +#endif diff --git a/src/runnersyntax.cpp b/src/runnersyntax.cpp new file mode 100644 index 0000000..171e2ac --- /dev/null +++ b/src/runnersyntax.cpp @@ -0,0 +1,69 @@ +/* + SPDX-FileCopyrightText: 2009 Aaron Seigo + SPDX-FileCopyrightText: 2023 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#include "runnersyntax.h" + +#include + +namespace KRunner +{ +class RunnerSyntaxPrivate +{ +public: + RunnerSyntaxPrivate(const QStringList &_exampleQueries, const QString &_description) + : exampleQueries(prepareExampleQueries(_exampleQueries)) + , description(_description) + { + } + + static QStringList prepareExampleQueries(const QStringList &queries) + { + Q_ASSERT_X(!queries.isEmpty(), "KRunner::RunnerSyntax", "List of example queries must not be empty"); + QStringList exampleQueries; + for (const QString &query : queries) { + Q_ASSERT_X(!query.isEmpty(), "KRunner::RunnerSyntax", "Example query must not be empty!"); + const static QString termDescription = i18n("search term"); + const QString termDesc(QLatin1Char('<') + termDescription + QLatin1Char('>')); + exampleQueries.append(QString(query).replace(QLatin1String(":q:"), termDesc)); + } + return exampleQueries; + } + + const QStringList exampleQueries; + const QString description; +}; + +RunnerSyntax::RunnerSyntax(const QStringList &exampleQueries, const QString &description) + : d(new RunnerSyntaxPrivate(exampleQueries, description)) +{ + Q_ASSERT_X(!exampleQueries.isEmpty(), "KRunner::RunnerSyntax", "Example queries must not be empty"); +} + +RunnerSyntax::RunnerSyntax(const RunnerSyntax &other) + : d(new RunnerSyntaxPrivate(*other.d)) +{ +} + +RunnerSyntax::~RunnerSyntax() = default; + +RunnerSyntax &RunnerSyntax::operator=(const RunnerSyntax &rhs) +{ + d.reset(new RunnerSyntaxPrivate(*rhs.d)); + return *this; +} + +QStringList RunnerSyntax::exampleQueries() const +{ + return d->exampleQueries; +} + +QString RunnerSyntax::description() const +{ + return d->description; +} + +} // KRunner namespace diff --git a/src/runnersyntax.h b/src/runnersyntax.h new file mode 100644 index 0000000..dd68904 --- /dev/null +++ b/src/runnersyntax.h @@ -0,0 +1,88 @@ +/* + SPDX-FileCopyrightText: 2009 Aaron Seigo + SPDX-FileCopyrightText: 2023 Alexander Lohnau + + SPDX-License-Identifier: LGPL-2.0-or-later +*/ + +#ifndef KRUNNER_RUNNERSYNTAX_H +#define KRUNNER_RUNNERSYNTAX_H + +#include +#include + +#include "krunner_export.h" + +namespace KRunner +{ +class RunnerSyntaxPrivate; +/** + * @class RunnerSyntax runnersyntax.h + * + * Represents a query prototype that the runner accepts. These can be + * created and registered with AbstractRunner::addSyntax to + * allow applications to show to the user what the runner is currently capable of doing. + * + * Lets say the runner has a trigger word and then the user can type anything after that. In that case you could use + * ":q:" as a placeholder, which will get expanded to i18n("search term") and be put in brackets. + * @code + KRunner::RunnerSyntax syntax(QStringLiteral("sometriggerword :q:"), i18n("Description for this syntax")); + addSyntax(syntax); + * @endcode + * + * But if the query the user has to enter is sth. specific like a program, + * url or file you should use a custom placeholder to make it easier to understand. + * @code + KRunner::RunnerSyntax syntax(QStringLiteral("sometriggereword <%1>").arg(i18n("program name"))), i18n("Description for this syntax")); + addSyntax(syntax); + * @endcode + */ +class KRUNNER_EXPORT RunnerSyntax +{ +public: + /** + * Constructs a RunnerSyntax with one example query + * + * @param exampleQuery See the class description for examples and placeholder conventions. + * @param description A description of what the described syntax does from the user's point of view. + */ + explicit inline RunnerSyntax(const QString &exampleQuery, const QString &description) + : RunnerSyntax(QStringList(exampleQuery), description) + { + } + + /** + * Constructs a RunnerSyntax with multiple example queries + * + * @param exampleQueries See the class description for examples and placeholder conventions. + * @param description A description of what the described syntax does from the user's point of view. + * This description should be true for all example queries. In case they differ, consider using multiple syntaxes. + * + * @since 5.106 + */ + explicit RunnerSyntax(const QStringList &exampleQueries, const QString &description); + + ~RunnerSyntax(); + + /** + * @return the example queries associated with this Syntax object + */ + QStringList exampleQueries() const; + + /** + * @return the user visible description of what the syntax does + */ + QString description() const; + + /// @internal + RunnerSyntax &operator=(const RunnerSyntax &rhs); + /// @internal + explicit RunnerSyntax(const RunnerSyntax &other); + +private: + std::unique_ptr d; +}; + +} // namespace KRunner + +#endif // multiple inclusion guard diff --git a/templates/.clang-format b/templates/.clang-format new file mode 100644 index 0000000..885c843 --- /dev/null +++ b/templates/.clang-format @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: 2021 Alexander Lohnau +# SPDX-License-Identifier: CC0-1.0 +DisableFormat: true +SortIncludes: false diff --git a/templates/CMakeLists.txt b/templates/CMakeLists.txt new file mode 100644 index 0000000..8693d2f --- /dev/null +++ b/templates/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: KDE Contributors +# SPDX-License-Identifier: BSD-2-Clause + +set(apptemplate_DIRS + runner6 + runner6python +) + +kde_package_app_templates(TEMPLATES ${apptemplate_DIRS} INSTALL_DIR ${KDE_INSTALL_KAPPTEMPLATESDIR}) diff --git a/templates/runner6/CMakeLists.txt b/templates/runner6/CMakeLists.txt new file mode 100644 index 0000000..4fbcc6d --- /dev/null +++ b/templates/runner6/CMakeLists.txt @@ -0,0 +1,21 @@ +cmake_minimum_required(VERSION 3.16) + +project(%{APPNAMELC}) + +set(QT_MIN_VERSION "6.5.0") +set(KF_MIN_VERSION "6.0.0") + +find_package(ECM ${KF_MIN_VERSION} REQUIRED NO_MODULE) +set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH}) +find_package(Qt6 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS Core Gui) +find_package(KF6 ${KF_MIN_VERSION} REQUIRED COMPONENTS Runner I18n) + +include(KDEInstallDirs) +include(KDEClangFormat) +include(KDECMakeSettings) +include(KDECompilerSettings NO_POLICY_SCOPE) +include(FeatureSummary) + +add_subdirectory(src) + +feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/templates/runner6/LICENSES/LGPL-2.1-or-later.txt b/templates/runner6/LICENSES/LGPL-2.1-or-later.txt new file mode 100644 index 0000000..04bb156 --- /dev/null +++ b/templates/runner6/LICENSES/LGPL-2.1-or-later.txt @@ -0,0 +1,468 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. + +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the +successor of the GNU Library Public License, version 2, hence the version +number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share +and change it. By contrast, the GNU General Public Licenses are intended to +guarantee your freedom to share and change free software--to make sure the +software is free for all its users. + +This license, the Lesser General Public License, applies to some specially +designated software packages--typically libraries--of the Free Software Foundation +and other authors who decide to use it. You can use it too, but we suggest +you first think carefully about whether this license or the ordinary General +Public License is the better strategy to use in any particular case, based +on the explanations below. + +When we speak of free software, we are referring to freedom of use, 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 this service if you +wish); that you receive source code or can get it if you want it; that you +can change the software and use pieces of it in new free programs; and that +you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors +to deny you these rights or to ask you to surrender these rights. These restrictions +translate to certain responsibilities for you if you distribute copies of +the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for +a fee, you must give the recipients all the rights that we gave you. You must +make sure that they, too, receive or can get the source code. If you link +other code with the library, you must provide complete object files to the +recipients, so that they can relink them with the library after making changes +to the library and recompiling it. And you must show them these terms so they +know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, +and (2) we offer you this license, which gives you legal permission to copy, +distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no +warranty for the free library. Also, if the library is modified by someone +else and passed on, the recipients should know that what they have is not +the original version, so that the original author's reputation will not be +affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free +program. We wish to make sure that a company cannot effectively restrict the +users of a free program by obtaining a restrictive license from a patent holder. +Therefore, we insist that any patent license obtained for a version of the +library must be consistent with the full freedom of use specified in this +license. + +Most GNU software, including some libraries, is covered by the ordinary GNU +General Public License. This license, the GNU Lesser General Public License, +applies to certain designated libraries, and is quite different from the ordinary +General Public License. We use this license for certain libraries in order +to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared +library, the combination of the two is legally speaking a combined work, a +derivative of the original library. The ordinary General Public License therefore +permits such linking only if the entire combination fits its criteria of freedom. +The Lesser General Public License permits more lax criteria for linking other +code with the library. + +We call this license the "Lesser" General Public License because it does Less +to protect the user's freedom than the ordinary General Public License. It +also provides other free software developers Less of an advantage over competing +non-free programs. These disadvantages are the reason we use the ordinary +General Public License for many libraries. However, the Lesser license provides +advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the +widest possible use of a certain library, so that it becomes a de-facto standard. +To achieve this, non-free programs must be allowed to use the library. A more +frequent case is that a free library does the same job as widely used non-free +libraries. In this case, there is little to gain by limiting the free library +to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs +enables a greater number of people to use a large body of free software. For +example, permission to use the GNU C Library in non-free programs enables +many more people to use the whole GNU operating system, as well as its variant, +the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' +freedom, it does ensure that the user of a program that is linked with the +Library has the freedom and the wherewithal to run that program using a modified +version of the Library. + +The precise terms and conditions for copying, distribution and modification +follow. Pay close attention to the difference between a "work based on the +library" and a "work that uses the library". The former contains code derived +from the library, whereas the latter must be combined with the library in +order to run. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program +which contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Lesser General +Public License (also called "this License"). Each licensee is addressed as +"you". + +A "library" means a collection of software functions and/or data prepared +so as to be conveniently linked with application programs (which use some +of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has +been distributed under these terms. A "work based on the Library" means either +the Library or any derivative work under copyright law: that is to say, a +work containing the Library or a portion of it, either verbatim or with modifications +and/or translated straightforwardly into another language. (Hereinafter, translation +is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications +to it. For a library, complete source code means all the source code for all +modules it contains, plus any associated interface definition files, plus +the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered +by this License; they are outside its scope. The act of running a program +using the Library is not restricted, and output from such a program is covered +only if its contents constitute a work based on the Library (independent of +the use of the Library in a tool for writing it). Whether that is true depends +on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source +code as you receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice and disclaimer +of warranty; keep intact all the notices that refer to this License and to +the absence of any warranty; and distribute a copy of this License along with +the Library. + +You may charge a fee for the physical act of transferring a copy, and you +may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, +thus forming a work based on the Library, and copy and distribute such modifications +or work under the terms of Section 1 above, provided that you also meet all +of these conditions: + + a) The modified work must itself be a software library. + +b) You must cause the files modified to carry prominent notices stating that +you changed the files and the date of any change. + +c) You must cause the whole of the work to be licensed at no charge to all +third parties under the terms of this License. + +d) If a facility in the modified Library refers to a function or a table of +data to be supplied by an application program that uses the facility, other +than as an argument passed when the facility is invoked, then you must make +a good faith effort to ensure that, in the event an application does not supply +such function or table, the facility still operates, and performs whatever +part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose +that is entirely well-defined independent of the application. Therefore, Subsection +2d requires that any application-supplied function or table used by this function +must be optional: if the application does not supply it, the square root function +must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable +sections of that work are not derived from the Library, and can be reasonably +considered independent and separate works in themselves, then this License, +and its terms, do not apply to those sections when you distribute them as +separate works. But when you distribute the same sections as part of a whole +which is a work based on the Library, the distribution of the whole must be +on the terms of this License, whose permissions for other licensees extend +to the entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest your +rights to work written entirely by you; rather, the intent is to exercise +the right to control the distribution of derivative or collective works based +on the Library. + +In addition, mere aggregation of another work not based on the Library with +the Library (or with a work based on the Library) on a volume of a storage +or distribution medium does not bring the other work under the scope of this +License. + +3. You may opt to apply the terms of the ordinary GNU General Public License +instead of this License to a given copy of the Library. To do this, you must +alter all the notices that refer to this License, so that they refer to the +ordinary GNU General Public License, version 2, instead of to this License. +(If a newer version than version 2 of the ordinary GNU General Public License +has appeared, then you can specify that version instead if you wish.) Do not +make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, +so the ordinary GNU General Public License applies to all subsequent copies +and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library +into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of +it, under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you accompany it with the complete corresponding +machine-readable source code, which must be distributed under the terms of +Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated +place, then offering equivalent access to copy the source code from the same +place satisfies the requirement to distribute the source code, even though +third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but +is designed to work with the Library by being compiled or linked with it, +is called a "work that uses the Library". Such a work, in isolation, is not +a derivative work of the Library, and therefore falls outside the scope of +this License. + +However, linking a "work that uses the Library" with the Library creates an +executable that is a derivative of the Library (because it contains portions +of the Library), rather than a "work that uses the library". The executable +is therefore covered by this License. Section 6 states terms for distribution +of such executables. + +When a "work that uses the Library" uses material from a header file that +is part of the Library, the object code for the work may be a derivative work +of the Library even though the source code is not. Whether this is true is +especially significant if the work can be linked without the Library, or if +the work is itself a library. The threshold for this to be true is not precisely +defined by law. + +If such an object file uses only numerical parameters, data structure layouts +and accessors, and small macros and small inline functions (ten lines or less +in length), then the use of the object file is unrestricted, regardless of +whether it is legally a derivative work. (Executables containing this object +code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute +the object code for the work under the terms of Section 6. Any executables +containing that work also fall under Section 6, whether or not they are linked +directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work +that uses the Library" with the Library to produce a work containing portions +of the Library, and distribute that work under terms of your choice, provided +that the terms permit modification of the work for the customer's own use +and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library +is used in it and that the Library and its use are covered by this License. +You must supply a copy of this License. If the work during execution displays +copyright notices, you must include the copyright notice for the Library among +them, as well as a reference directing the user to the copy of this License. +Also, you must do one of these things: + +a) Accompany the work with the complete corresponding machine-readable source +code for the Library including whatever changes were used in the work (which +must be distributed under Sections 1 and 2 above); and, if the work is an +executable linked with the Library, with the complete machine-readable "work +that uses the Library", as object code and/or source code, so that the user +can modify the Library and then relink to produce a modified executable containing +the modified Library. (It is understood that the user who changes the contents +of definitions files in the Library will not necessarily be able to recompile +the application to use the modified definitions.) + +b) Use a suitable shared library mechanism for linking with the Library. A +suitable mechanism is one that (1) uses at run time a copy of the library +already present on the user's computer system, rather than copying library +functions into the executable, and (2) will operate properly with a modified +version of the library, if the user installs one, as long as the modified +version is interface-compatible with the version that the work was made with. + +c) Accompany the work with a written offer, valid for at least three years, +to give the same user the materials specified in Subsection 6a, above, for +a charge no more than the cost of performing this distribution. + +d) If distribution of the work is made by offering access to copy from a designated +place, offer equivalent access to copy the above specified materials from +the same place. + +e) Verify that the user has already received a copy of these materials or +that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must +include any data and utility programs needed for reproducing the executable +from it. However, as a special exception, the materials to be distributed +need not include anything that is normally distributed (in either source or +binary form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component itself +accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of +other proprietary libraries that do not normally accompany the operating system. +Such a contradiction means you cannot use both them and the Library together +in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side +in a single library together with other library facilities not covered by +this License, and distribute such a combined library, provided that the separate +distribution of the work based on the Library and of the other library facilities +is otherwise permitted, and provided that you do these two things: + +a) Accompany the combined library with a copy of the same work based on the +Library, uncombined with any other library facilities. This must be distributed +under the terms of the Sections above. + +b) Give prominent notice with the combined library of the fact that part of +it is a work based on the Library, and explaining where to find the accompanying +uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library +except as expressly provided under this License. Any attempt otherwise to +copy, modify, sublicense, link with, or distribute the Library is void, and +will automatically terminate your rights under this License. However, parties +who have received copies, or rights, from you under this License will not +have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed +it. However, nothing else grants you permission to modify or distribute the +Library or its derivative works. These actions are prohibited by law if you +do not accept this License. Therefore, by modifying or distributing the Library +(or any work based on the Library), you indicate your acceptance of this License +to do so, and all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), +the recipient automatically receives a license from the original licensor +to copy, distribute, link with or modify the Library subject to these terms +and conditions. You may not impose any further restrictions on the recipients' +exercise of the rights granted herein. You are not responsible for enforcing +compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement +or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your +obligations under this License and any other pertinent obligations, then as +a consequence you may not distribute the Library at all. For example, if a +patent license would not permit royalty-free redistribution of the Library +by all those who receive copies directly or indirectly through you, then the +only way you could satisfy both it and this License would be to refrain entirely +from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents +or other property right claims or to contest validity of any such claims; +this section has the sole purpose of protecting the integrity of the free +software distribution system which is implemented by public license practices. +Many people have made generous contributions to the wide range of software +distributed through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing to +distribute software through any other system and a licensee cannot impose +that choice. + +This section is intended to make thoroughly clear what is believed to be a +consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain +countries either by patents or by copyrighted interfaces, the original copyright +holder who places the Library under this License may add an explicit geographical +distribution limitation excluding those countries, so that distribution is +permitted only in or among countries not thus excluded. In such case, this +License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of +the Lesser 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 Library specifies +a version number of this License which applies to it and "any later version", +you have the option of following the terms and conditions either of that version +or of any later version published by the Free Software Foundation. If the +Library does not specify a license version number, you may choose any version +ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs +whose distribution conditions are incompatible with these, write to the author +to ask for permission. For software which is copyrighted by the Free Software +Foundation, write to the Free Software Foundation; we sometimes make exceptions +for this. Our decision will be guided by the two goals of preserving the free +status of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR +THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE +STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY +"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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE +THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH +HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible +use to the public, we recommend making it free software that everyone can +redistribute and change. You can do so by permitting redistribution under +these terms (or, alternatively, under the terms of the ordinary General Public +License). + +To apply these terms, attach the following notices to the library. It is safest +to attach them to the start of each source file to most effectively convey +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 library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free +Software Foundation; either version 2.1 of the License, or (at your option) +any later version. + +This library is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +details. + +You should have received a copy of the GNU Lesser General Public License along +with this library; if not, write to the Free Software Foundation, Inc., 51 +Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, +if any, to sign a "copyright disclaimer" for the library, if necessary. Here +is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in + +the library `Frob' (a library for tweaking knobs) written + +by James Random Hacker. + +< signature of Ty Coon > , 1 April 1990 + +Ty Coon, President of Vice + +That's all there is to it! diff --git a/templates/runner6/Messages.sh b/templates/runner6/Messages.sh new file mode 100755 index 0000000..1e782fc --- /dev/null +++ b/templates/runner6/Messages.sh @@ -0,0 +1,2 @@ +#! /usr/bin/env bash +$XGETTEXT src/*.cpp -o $podir/plasma_runner_org.kde.%{APPNAMELC}.pot diff --git a/templates/runner6/README.md b/templates/runner6/README.md new file mode 100644 index 0000000..cf7c79f --- /dev/null +++ b/templates/runner6/README.md @@ -0,0 +1,13 @@ +# %{APPNAME} + +### Build instructions + +After installing the required headers and CMake config files on your distro, the `install.sh` script can be run. + +After this the runner shows up in systemsettings: +`systemsettings kcm_plasmasearch` + +You can also launch KRunner via Alt-F2 or Alt-Space and you will find your runner. + +If you feel confident about your runner you can upload it to the KDE Store +https://store.kde.org/browse?cat=628&ord=latest. diff --git a/templates/runner6/install.sh b/templates/runner6/install.sh new file mode 100755 index 0000000..1a4de40 --- /dev/null +++ b/templates/runner6/install.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# Exit if something fails +set -e + +mkdir -p build +cd build + +cmake -DKDE_INSTALL_USE_QT_SYS_PATHS=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo .. +make -j$(nproc) +sudo make install + +# KRunner needs to be restarted for the changes to be applied +# we can just kill it and it will be started when the shortcut is invoked +kquitapp6 krunner diff --git a/templates/runner6/runner.kdevtemplate b/templates/runner6/runner.kdevtemplate new file mode 100644 index 0000000..2e8bcf7 --- /dev/null +++ b/templates/runner6/runner.kdevtemplate @@ -0,0 +1,94 @@ +# KDE Config File +[General] +Name=C++ (Qt6) +Name[ar]=سي ++ (Qt6) +Name[ast]=C++ (Qt6) +Name[bg]=C++ (Qt6) +Name[ca]=C++ (Qt6) +Name[ca@valencia]=C++ (Qt6) +Name[cs]=C++ (Qt6) +Name[de]=C++ (Qt6) +Name[el]=C++ (Qt6) +Name[en_GB]=C++ (Qt6) +Name[eo]=C++ (Qt6) +Name[es]=C++ (Qt6) +Name[eu]=C++ (Qt6) +Name[fi]=C++ (Qt6) +Name[fr]=C++ (Qt6) +Name[gl]=C++ (Qt6) +Name[he]=C++ (Qt6) +Name[hu]=C++ (Qt6) +Name[ia]=C++ (Qt6) +Name[it]=C++ (Qt6) +Name[ka]=C++ (Qt6) +Name[ko]=C++(Qt6) +Name[lt]=C++ (Qt6) +Name[lv]=C++ (Qt6) +Name[nl]=C++ (Qt6) +Name[nn]=C++ (Qt6) +Name[pa]=C++ (Qt6) +Name[pl]=C++ (Qt6) +Name[pt_BR]=C++ (Qt6) +Name[ro]=C++ (Qt6) +Name[ru]=C++ (Qt6) +Name[sa]=C++ (Qt6) +Name[sl]=C++ (Qt6) +Name[sv]=C++ (Qt6) +Name[tr]=C++ (Qt6) +Name[uk]=C++ (Qt6) +Name[x-test]=xxC++ (Qt6)xx +Name[zh_CN]=C++ (Qt6) +Name[zh_TW]=C++ (Qt6) +Comment=Plasma Runner Template. A plasma runner template +Comment[ar]=قالب «مشغّل بلازما». قالب لِ‍«مشغّل بلازما» +Comment[az]=Plasma başlatma sətri üçün uzantıların şablonu +Comment[bg]=Plasma Runner шаблон +Comment[ca]=Plantilla de Runner del Plasma. Una plantilla de «Runner» per al Plasma +Comment[ca@valencia]=Plantilla de Runner de Plasma. Una plantilla de «Runner» per a Plasma +Comment[da]=Skabelon til Plasma-runner. En skabelon til en Plasma-runner +Comment[de]=Eine Vorlage für einen Plasma-Runner +Comment[el]=Πρότυπο Plasma Runner. ένα πρότυπο εκτελεστή plasma +Comment[en_GB]=Plasma Runner Template. A plasma runner template +Comment[eo]=Plasma-rulilŝablono +Comment[es]=Plantilla para Plasma Runner. Una plantilla para Plasma Runner. +Comment[et]=Plasma Runneri mall. +Comment[eu]=Plasma «Runner» txantiloia. Plasma «runner» txantiloi bat +Comment[fi]=Plasma-suoritusohjelmamalli. +Comment[fr]=Un modèle de lanceur pour Plasma. +Comment[gl]=Modelo de executor de Plasma. Un modelo de executor de Plasma. +Comment[he]=תבנית ריצה של פלזמה. תבנית ריצה של פלזמה +Comment[hi]=प्लाज्मा रनर नमूना। एक प्लाज्मा रनर नमूना +Comment[hu]=Plasma futtatósablon. +Comment[ia]=Patrono de executor (runner) de Plasma. Un patrono de executor de Plasma +Comment[id]=Plasma Runner Template. Sebuah template pejalan plasma +Comment[it]=Modello di esecutore di Plasma. Un modello di esecutore di Plasma +Comment[ka]=Plasma-ის დამხმარე პროცესის შაბლონი. Plasma-ის დამხმარე პროცესის შაბლონი +Comment[ko]=Plasma 실행기 템플릿. Plasma 실행기 템플릿 +Comment[lt]=Plasma paleidiklio Å¡ablonas. Plasma paleidiklio Å¡ablonas +Comment[lv]=„Plasma“ palaidēja veidne. „Plasma“ palaidēja veidne +Comment[nb]=Plasma kjørermal. En Plasma-kjørermal +Comment[nl]=Sjabloon voor Plasma-runner. Een plasma-starter sjabloon +Comment[nn]=Malfil for Plasma-køyrar. +Comment[pa]=ਪਲਾਜ਼ਮਾ ਰਨਰ ਟੈਪਲੇਟ। ਇੱਕ ਪਲਾਜ਼ਮਾ ਰਨਰ ਟੈਪਲੇਟ +Comment[pl]=Szablon uruchamiania Plazmy. Szablon uruchamiania plazmy +Comment[pt]=Modelo de Execução do Plasma. Um modelo de módulo de execução do Plasma +Comment[pt_BR]=Modelo de módulo de execução do Plasma. Um modelo de módulos de execução do Plasma +Comment[ro]=Șablon de executor Plasma. Un șablon de executor Plasma +Comment[ru]=Шаблон расширения для строки запуска Plasma +Comment[sa]=प्लाज्मा धावक टेम्पलेट। एकः प्लाज्मा धावकः टेम्पलेट् +Comment[sk]=Å ablóna Plasma Runner. Å ablóna plasma runner +Comment[sl]=Plasma Runner Template. Predloga zaganjalnika Plasma +Comment[sr]=Шаблон плазма извођача. +Comment[sr@ijekavian]=Шаблон плазма извођача. +Comment[sr@ijekavianlatin]=Å ablon plasma izvođača. +Comment[sr@latin]=Å ablon plasma izvođača. +Comment[sv]=Plasma-mall för körning av program. Mall för Plasma körning av program +Comment[tg]=Қолиби иҷрокунандаи Plasma. Қолиби иҷрокунандаи Plasma +Comment[tr]=Plasma Çalıştırıcı Şablonu. Bir Plasma çalıştırıcı şablonu +Comment[uk]=Шаблон засобу запуску Плазми +Comment[vi]=Bản mẫu trình chạy Plasma. Một bản mẫu trình chạy Plasma +Comment[x-test]=xxPlasma Runner Template. A plasma runner templatexx +Comment[zh_CN]=Plasma Runner 模板。一个 Plasma Runner 模板 +Comment[zh_TW]=Plasma Runner 範本。一個 plasma runner 的範本 +Category=Plasma/KRunner +Icon=runner.png diff --git a/templates/runner6/runner.png b/templates/runner6/runner.png new file mode 100644 index 0000000..6dcd6d1 Binary files /dev/null and b/templates/runner6/runner.png differ diff --git a/templates/runner6/src/%{APPNAMELC}.cpp b/templates/runner6/src/%{APPNAMELC}.cpp new file mode 100644 index 0000000..18ca0fc --- /dev/null +++ b/templates/runner6/src/%{APPNAMELC}.cpp @@ -0,0 +1,43 @@ +/* + SPDX-FileCopyrightText: %{CURRENT_YEAR} %{AUTHOR} <%{EMAIL}> + + SPDX-License-Identifier: LGPL-2.1-or-later +*/ + +#include "%{APPNAMELC}.h" + +#include + +%{APPNAME}::%{APPNAME}(QObject *parent, const KPluginMetaData &data) + : KRunner::AbstractRunner(parent, data) +{ + // Disallow short queries + setMinLetterCount(3); + // Provide usage help for this plugin + addSyntax(QStringLiteral("sometriggerword :q:"), i18n("Description for this syntax")); +} + +void %{APPNAME}::match(KRunner::RunnerContext &context) +{ + const QString term = context.query(); + if (term.compare(QLatin1String("hello"), Qt::CaseInsensitive) == 0) { + KRunner::QueryMatch match(this); + match.setText(i18n("Hello from %{APPNAME}")); + context.addMatch(match); + } +} + +void %{APPNAME}::run(const KRunner::RunnerContext &context, const KRunner::QueryMatch &match) +{ + Q_UNUSED(context) + Q_UNUSED(match) + + // TODO +} + +K_PLUGIN_CLASS_WITH_JSON(%{APPNAME}, "%{APPNAMELC}.json") + +// needed for the QObject subclass declared as part of K_PLUGIN_CLASS_WITH_JSON +#include "%{APPNAMELC}.moc" + +#include "moc_%{APPNAMELC}.cpp" diff --git a/templates/runner6/src/%{APPNAMELC}.h b/templates/runner6/src/%{APPNAMELC}.h new file mode 100644 index 0000000..1b52da2 --- /dev/null +++ b/templates/runner6/src/%{APPNAMELC}.h @@ -0,0 +1,21 @@ +/* + SPDX-FileCopyrightText: %{CURRENT_YEAR} %{AUTHOR} <%{EMAIL}> + + SPDX-License-Identifier: LGPL-2.1-or-later +*/ + +#pragma once + +#include + +class %{APPNAME} : public KRunner::AbstractRunner +{ + Q_OBJECT + +public: + %{APPNAME}(QObject *parent, const KPluginMetaData &data); + + // KRunner::AbstractRunner API + void match(KRunner::RunnerContext &context) override; + void run(const KRunner::RunnerContext &context, const KRunner::QueryMatch &match) override; +}; diff --git a/templates/runner6/src/%{APPNAMELC}.json b/templates/runner6/src/%{APPNAMELC}.json new file mode 100644 index 0000000..c91e30a --- /dev/null +++ b/templates/runner6/src/%{APPNAMELC}.json @@ -0,0 +1,16 @@ +{ + "KPlugin": { + "Authors": [ + { + "Email": "%{EMAIL}", + "Name": "%{AUTHOR}" + } + ], + "Description": "%{APPNAME} runner", + "EnabledByDefault": true, + "Icon": "planetkde", + "License": "LGPL 2.1+", + "Name": "%{APPNAME}", + "Version": "0.1" + } +} diff --git a/templates/runner6/src/CMakeLists.txt b/templates/runner6/src/CMakeLists.txt new file mode 100644 index 0000000..67c9e2e --- /dev/null +++ b/templates/runner6/src/CMakeLists.txt @@ -0,0 +1,13 @@ +add_definitions(-DTRANSLATION_DOMAIN=\"plasma_runner_org.kde.%{APPNAMELC}\") + +kcoreaddons_add_plugin(%{APPNAMELC} INSTALL_NAMESPACE "kf6/krunner") + +target_sources(%{APPNAMELC} PRIVATE + %{APPNAMELC}.cpp +) + +target_link_libraries(%{APPNAMELC} + Qt6::Gui # QAction + KF6::Runner + KF6::I18n +) diff --git a/templates/runner6/uninstall.sh b/templates/runner6/uninstall.sh new file mode 100755 index 0000000..4f12354 --- /dev/null +++ b/templates/runner6/uninstall.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +# Exit if something fails +set -e + +cd build +sudo make uninstall + +# KRunner needs to be restarted for the changes to be applied +# we can just kill it and it will be started when the shortcut is invoked +kquitapp6 krunner diff --git a/templates/runner6python/%{APPNAMELC}.desktop b/templates/runner6python/%{APPNAMELC}.desktop new file mode 100644 index 0000000..5929877 --- /dev/null +++ b/templates/runner6python/%{APPNAMELC}.desktop @@ -0,0 +1,13 @@ +[Desktop Entry] +Name=%{APPNAME} +Comment=%{APPNAME} Runner written in Python +Type=Service +Icon=planetkde +X-KDE-PluginInfo-Author=%{AUTHOR} +X-KDE-PluginInfo-Email=%{EMAIL} +X-KDE-PluginInfo-Name=%{APPNAMELC} +X-KDE-PluginInfo-Version=1.0 +X-KDE-PluginInfo-License=LGPL +X-KDE-PluginInfo-EnabledByDefault=true +X-Plasma-API=DBus +X-Plasma-DBusRunner-Service=org.kde.%{APPNAMELC} diff --git a/templates/runner6python/README.md b/templates/runner6python/README.md new file mode 100644 index 0000000..9fa54ed --- /dev/null +++ b/templates/runner6python/README.md @@ -0,0 +1,23 @@ +### %{APPNAME} + +This plugin provides a simple template for a KRunner plugin using dbus. + +The install script copies the KRunner config file and a D-Bus activation service file to their appropriate locations. +This way the Python script gets executed when KRunner requests matches and it does not need to be autostarted. + +```bash +mkdir -p ~/.local/share/krunner/dbusplugins/ +cp %{APPNAMELC}.desktop ~/.local/share/krunner/dbusplugins/ +kquitapp6 krunner +python3 %{APPNAMELC}.py +``` + +After that you should see your runner when typing `hello` in KRunner. + +More information regarding the D-Bus API can be found here: + +* https://invent.kde.org/frameworks/krunner/-/blob/master/src/data/org.kde.krunner1.xml +* https://develop.kde.org/docs/features/d-bus/introduction_to_dbus/ + + +If you feel confident about your runner you can upload it to the KDE Store https://store.kde.org/browse?cat=628&ord=latest. diff --git a/templates/runner6python/install.sh b/templates/runner6python/install.sh new file mode 100755 index 0000000..d7e9cff --- /dev/null +++ b/templates/runner6python/install.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# Standalone install script for copying files + +set -e + +prefix="${XDG_DATA_HOME:-$HOME/.local/share}" +krunner_dbusdir="$prefix/krunner/dbusplugins" +services_dir="$prefix/dbus-1/services/" + +mkdir -p $krunner_dbusdir +mkdir -p $services_dir + +cp %{APPNAMELC}.desktop $krunner_dbusdir +printf "[D-BUS Service]\nName=org.kde.%{APPNAMELC}\nExec=\"$PWD/main.py\"" > $services_dir/org.kde.%{APPNAMELC}.service + +kquitapp6 krunner + diff --git a/templates/runner6python/krunner-plugininstallerrc b/templates/runner6python/krunner-plugininstallerrc new file mode 100644 index 0000000..9019b1e --- /dev/null +++ b/templates/runner6python/krunner-plugininstallerrc @@ -0,0 +1,3 @@ +# File for krunner-plugininstaller executable. This allows for easier installation in the "Get New Plugins" button of the config module +MetaDataFile=%{APPNAMELC}.desktop +Exec=%{PROJECTDIR}/main.py diff --git a/templates/runner6python/main.py b/templates/runner6python/main.py new file mode 100755 index 0000000..afa11cb --- /dev/null +++ b/templates/runner6python/main.py @@ -0,0 +1,37 @@ +#!/usr/bin/python3 + +import dbus.service +from dbus.mainloop.glib import DBusGMainLoop +from gi.repository import GLib + +DBusGMainLoop(set_as_default=True) + +objpath = "/runner" # Default value for X-Plasma-DBusRunner-Path metadata property +iface = "org.kde.krunner1" + + +class Runner(dbus.service.Object): + def __init__(self): + dbus.service.Object.__init__(self, dbus.service.BusName("org.kde.%{APPNAMELC}", dbus.SessionBus()), objpath) + + @dbus.service.method(iface, in_signature='s', out_signature='a(sssida{sv})') + def Match(self, query: str): + """This method is used to get the matches and it returns a list of tupels""" + if query == "hello": + # data, text, icon, type (KRunner::QueryType), relevance (0-1), properties (subtext, category, multiline(bool) and urls) + return [("Hello", "Hello from %{APPNAME}!", "document-edit", 100, 1.0, {'subtext': 'Demo Subtext'})] + return [] + + @dbus.service.method(iface, out_signature='a(sss)') + def Actions(self): + # id, text, icon + return [("id", "Tooltip", "planetkde")] + + @dbus.service.method(iface, in_signature='ss') + def Run(self, data: str, action_id: str): + print(data, action_id) + + +runner = Runner() +loop = GLib.MainLoop() +loop.run() diff --git a/templates/runner6python/runner.png b/templates/runner6python/runner.png new file mode 100644 index 0000000..626a80e Binary files /dev/null and b/templates/runner6python/runner.png differ diff --git a/templates/runner6python/runnerpy.kdevtemplate b/templates/runner6python/runnerpy.kdevtemplate new file mode 100644 index 0000000..30c1db9 --- /dev/null +++ b/templates/runner6python/runnerpy.kdevtemplate @@ -0,0 +1,85 @@ +[General] +Name=Python KRunner Plugin (Qt6) +Name[ar]=ملحقة مشغّلك لبايثون (كيوت6) +Name[bg]=Приставка на Python KRunner (Qt6) +Name[ca]=Connector Python del KRunner (Qt6) +Name[ca@valencia]=Connector en Python de KRunner (Qt6) +Name[cs]=Modul KRunneru v Pythonu (Qt6) +Name[de]=KRunner-Modul für Python (Qt6) +Name[el]=Πρόσθετο Python KRunner (Qt6) +Name[en_GB]=Python KRunner Plugin (Qt6) +Name[eo]=Python KRunner-kromprogramo (Qt6) +Name[es]=Complemento en Python para KRunner (Qt6) +Name[eu]=Python «KRunner» plugina +Name[fi]=Python-KRunner-liitännäinen (Qt6) +Name[fr]=Module externe « KRunner » pour Python (Qt6) +Name[gl]=Complemento de Python para KRunner (Qt6) +Name[he]=תוסף KRunner ב־Python‏ (Qt6) +Name[hu]=KRunner Python-bővítmény (Qt6) +Name[ia]=Plugin de KRunner de Python (Qt6) +Name[it]=Estensione Python di KRunner (Qt6) +Name[ka]=KRunner-ის Python-ის დამატება (Qt6) +Name[ko]=Python KRunner 플러그인(Qt6) +Name[lt]=Python KRunner įskiepis (Qt6) +Name[lv]=„Python“ „KRunner“ spraudnis (Qt6) +Name[nl]=Python KRunner-plug-in (Qt6) +Name[nn]=Python KRunner-tillegg (Qt6) +Name[pa]=ਪਾਈਥਨ ਕੇਰਨਰ ਪਲੱਗਇਨ (Qt6) +Name[pl]=Wtyczka Pythona dla KRunnera (Qt6) +Name[pt_BR]=Plugin Python do KRunner (Qt6) +Name[ro]=Extensie Python pentru KRunner (Qt6) +Name[ru]=Расширение KRunner на Python (Qt6) +Name[sa]=Python KRunner Plugin (Qt6) +Name[sl]=Vtičnik za Python KRunner (Qt6) +Name[sv]=Python-insticksprogram för Kör program (Qt6) +Name[tr]=Python K Çalıştır Eklentisi (Qt6) +Name[uk]=Додаток до KRunner мовою Python (Qt6) +Name[x-test]=xxPython KRunner Plugin (Qt6)xx +Name[zh_CN]=Python KRunner 插件 (Qt6) +Name[zh_TW]=Python KRunner 外掛程式 (Qt6) +Comment=Template for a KRunner Python Plugin using D-Bus +Comment[ar]=قالب لملحق بايثون لمشغلك باستخدام D-Bus +Comment[az]=D-Bus ilə istifadə olunan KRunner Python Qoşması üçün nümunə +Comment[bg]=Шаблон за KRunner Python Plugin използващ D-Bus +Comment[ca]=Plantilla per a un connector Python del KRunner usant D-Bus +Comment[ca@valencia]=Plantilla per a un connector en Python de KRunner utilitzant D-Bus +Comment[da]=Skabelon til et KRunner Python-plugin med brug af D-Bus +Comment[de]=Vorlage für ein KRunner-Modul für Python, das D-Bus verwendet +Comment[el]=Πρότυπο για ένα πρόσθετο του KRunner σε Python με χρήση D-Bus +Comment[en_GB]=Template for a KRunner Python Plugin using D-Bus +Comment[eo]=Ŝablono por KRunner Python-kromprogramo uzanta D-Bus +Comment[es]=Plantilla para un complemento en Python para KRunner que usa D-Bus +Comment[et]=D-Busi kasutav KRunneri Pythoni plugina mall +Comment[eu]=D-Bus erabiltzen duen «KRunner» Python plugin batentzako txantiloia +Comment[fi]=Malli KRunnerin Python-liitännäiseksi D-Busia käyttäen +Comment[fr]=Modèle pour le module externe « KRunner » pour Python, utilisant « D-Bus » +Comment[gl]=Modelo de complemento de Python para KRunner usando D-Bus +Comment[he]=תבנית לתוסף Python של KRunner באמצעות D-Bus +Comment[hi]=डी-बस का प्रयोग करते हुए एक केरनर पायथन प्लगइन का नमूना +Comment[hu]=Sablon a D-Bust használó KRunner Python-bővítményekhez +Comment[ia]=Patrono per un Plugin de Python de KRunner usante D-Bus +Comment[id]=Templat untuk sebuah Plugin Python KRunner menggunakan D-Bus +Comment[it]=Modello per un'estensione Python di KRunner che usa D-Bus +Comment[ka]=KRunner-ის Python-ის დამატების შაბლონი D-Bus-ის გამოყენებით +Comment[ko]=D-Bus를 사용하는 KRunner Python 플러그인 템플릿 +Comment[lt]=Å ablonas, skirtas KRunner Python įskiepiui, naudojantis D-Bus +Comment[lv]=Veidne „KRunner“ „Python“ spraudnim, izmantojot „D-Bus“ +Comment[nl]=Sjabloon voor een Python-plug-in van KRunner met gebruik van D-Bus +Comment[nn]=Mal for eit Python-basert KRunner-tillegg som brukar D-Bus +Comment[pl]=Szablon wtyczki Pythona dla KRunnera, używająca D-Bus +Comment[pt]=Modelo para um 'Plugin' em Python do KRunner que usa o D-Bus +Comment[pt_BR]=Modelo para um plugin Python do KRunner usando o D-Bus +Comment[ro]=Șablon pentru o extensie KRunner în Python folosind DBus +Comment[ru]=Шаблон расширения KRunner на Python, использующий D-Bus +Comment[sa]=D-Bus इत्यस्य उपयोगेन KRunner Python Plugin कृते Template +Comment[sk]=Å ablóna pre KRunner Python plugin využívajúci D-Bus +Comment[sl]=Predloga za vtičnik Python KRunner z uporabo D-Bus +Comment[sv]=Mall för ett Python-insticksprogram för Kör program med användning av D-Bus +Comment[tr]=D-Bus kullanan bir K Çalıştır Python Eklentisi için şablon +Comment[uk]=Шаблон для додатка Python KRunner з використанням D-Bus +Comment[vi]=Bản mẫu cho một phần cài cắm KRunner bằng Python sá»­ dụng D-Bus +Comment[x-test]=xxTemplate for a KRunner Python Plugin using D-Busxx +Comment[zh_CN]=使用 D-Bus 的 KRunner Python 插件模板 +Comment[zh_TW]=使用 D-Bus 的 KRunner Python 外掛程式的範本 +Category=Plasma/KRunner +Icon=runner.png diff --git a/templates/runner6python/uninstall.sh b/templates/runner6python/uninstall.sh new file mode 100755 index 0000000..290ad3e --- /dev/null +++ b/templates/runner6python/uninstall.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +# Exit if something fails +set -e + +prefix="${XDG_DATA_HOME:-$HOME/.local/share}" +krunner_dbusdir="$prefix/krunner/dbusplugins" + +rm $prefix/dbus-1/services/org.kde.%{APPNAMELC}.service +rm $krunner_dbusdir/%{APPNAMELC}.desktop +kquitapp6 krunner +