Advance Wayland and KDE package bring-up

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
2026-04-14 10:51:06 +01:00
parent 51f3c21121
commit cf12defd28
15214 changed files with 20594243 additions and 269 deletions
@@ -0,0 +1,4 @@
#clang-format/tidy
554f51fd377575d49d8fff50ad312b9d2fd8ae3a
bc88d2d37c8e2ea0b20b9e20a97dd23f4757d09d
1986678a3056a5788e88cb9802f57733c2d8ef39
@@ -0,0 +1,29 @@
# 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*/
/.vscode/
CMakeLists.txt.user*
*.unc-backup*
.cmake/
/.clang-format
/compile_commands.json
.clangd
.idea
/cmake-build*
.cache
@@ -0,0 +1,12 @@
# SPDX-FileCopyrightText: 2020 Volker Krause <vkrause@kde.org>
# SPDX-License-Identifier: CC0-1.0
include:
- project: sysadmin/ci-utilities
file:
- /gitlab-templates/linux-qt6.yml
- /gitlab-templates/linux-qt6-static.yml
- /gitlab-templates/android-qt6.yml
- /gitlab-templates/freebsd-qt6.yml
- /gitlab-templates/windows-qt6.yml
- /gitlab-templates/alpine-qt6.yml
@@ -0,0 +1,13 @@
Dependencies:
- 'on': ['@all']
'require':
'frameworks/extra-cmake-modules': '@same'
- 'on': ['Linux', 'FreeBSD']
'require':
'libraries/plasma-wayland-protocols': '@latest'
'third-party/wayland': '@latest'
Options:
test-before-installing: True
require-passing-tests-on: [ 'Linux', 'FreeBSD', 'Windows' ]
@@ -0,0 +1,158 @@
cmake_minimum_required(VERSION 3.16)
set(KF_VERSION "6.10.0") # handled by release scripts
project(KGuiAddons VERSION ${KF_VERSION})
include(FeatureSummary)
find_package(ECM 6.10.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(KDEGitCommitHooks)
include(ECMSetupVersion)
include(ECMGenerateHeaders)
include(ECMQtDeclareLoggingCategory)
include(ECMDeprecationSettings)
include(ECMAddQch)
include(ECMGenerateExportHeader)
include(ECMGeneratePkgConfigFile)
include(ECMMarkNonGuiExecutable)
include(ECMQmlModule)
include(CMakeDependentOption)
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)")
option(BUILD_GEO_SCHEME_HANDLER "Build the geo: URI scheme handler. Disable this if you are building two major versions for co-installability in the older variant." ON)
if(UNIX AND NOT APPLE AND NOT ANDROID AND NOT HAIKU)
option(WITH_WAYLAND "Build with support for KModifierKeyInfo, KSystemClipboard and KKeySequenceRecorder inhibiting shortcuts on Wayland" ON)
add_feature_info(WAYLAND ${WITH_WAYLAND} "KeySequenceEditor inhibiting shortcuts on Wayland")
option(WITH_X11 "Build with support for KModifierKeyInfo on X11" ON)
add_feature_info(X11 ${WITH_X11} "KeySequenceEditor inhibiting shortcuts on X11")
else()
set(WITH_WAYLAND OFF)
set(WITH_X11 OFF)
endif()
set(REQUIRED_QT_VERSION 6.6.0)
if (WITH_WAYLAND)
set(_qtgui_find_components COMPONENTS Private)
endif()
# QtGui must be found before Qt5WaylandClient
find_package(Qt6Gui ${REQUIRED_QT_VERSION} REQUIRED NO_MODULE ${_qtgui_find_components})
if (WITH_X11)
find_package(X11 REQUIRED MODULE)
find_package(XCB REQUIRED MODULE COMPONENTS XCB)
if(NOT QT_FEATURE_xcb)
message(FATAL_ERROR "Qt xcb feature is missing for compilation with X11")
endif()
endif()
if (WITH_WAYLAND)
find_package(PlasmaWaylandProtocols 1.15.0 REQUIRED)
find_package(Qt6WaylandClient ${REQUIRED_QT_VERSION} REQUIRED CONFIG)
find_package(Wayland 1.9 REQUIRED Client)
endif()
# shall we use DBus?
# enabled per default on Linux & BSD systems
set(USE_DBUS_DEFAULT OFF)
if(UNIX AND NOT APPLE AND NOT ANDROID AND NOT HAIKU)
set(USE_DBUS_DEFAULT ON)
endif()
option(USE_DBUS "Build components using DBus (get color scheme information via XDG portals)" ${USE_DBUS_DEFAULT})
if(USE_DBUS)
find_package(Qt6DBus ${REQUIRED_QT_VERSION} REQUIRED NO_MODULE)
set(WITH_DBUS ON)
endif()
if (ANDROID)
find_package(Gradle REQUIRED)
endif()
# For the Python bindings
find_package(Python3 3.10 COMPONENTS Interpreter Development)
find_package(Shiboken6)
find_package(PySide6)
set(kguiaddons_version_header "${CMAKE_CURRENT_BINARY_DIR}/src/kguiaddons_version.h")
ecm_setup_version(PROJECT VARIABLE_PREFIX KGUIADDONS
VERSION_HEADER "${kguiaddons_version_header}"
PACKAGE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/KF6GuiAddonsConfigVersion.cmake"
SOVERSION 6)
ecm_set_disabled_deprecation_versions(
QT 6.8
)
cmake_dependent_option(BUILD_PYTHON_BINDINGS "Generate Python Bindings" ON "TARGET Shiboken6::libshiboken AND TARGET PySide6::pyside6" OFF)
add_feature_info(PYTHON_BINDINGS ${BUILD_PYTHON_BINDINGS} "Python bindings")
# FreeBSD CI is missing required packages
if (CMAKE_SYSTEM_NAME MATCHES FreeBSD)
set(BUILD_PYTHON_BINDINGS OFF)
endif()
add_subdirectory(src)
if (BUILD_TESTING)
add_subdirectory(autotests)
add_subdirectory(tests)
endif()
if (BUILD_PYTHON_BINDINGS)
include(ECMGeneratePythonBindings)
add_subdirectory(python)
endif()
# create a Config.cmake and a ConfigVersion.cmake file and install them
set(CMAKECONFIG_INSTALL_DIR "${KDE_INSTALL_CMAKEPACKAGEDIR}/KF6GuiAddons")
if (BUILD_QCH)
ecm_install_qch_export(
TARGETS KF6GuiAddons_QCH
FILE KF6GuiAddonsQchTargets.cmake
DESTINATION "${CMAKECONFIG_INSTALL_DIR}"
COMPONENT Devel
)
set(PACKAGE_INCLUDE_QCHTARGETS "include(\"\${CMAKE_CURRENT_LIST_DIR}/KF6GuiAddonsQchTargets.cmake\")")
endif()
include(CMakePackageConfigHelpers)
configure_package_config_file("${CMAKE_CURRENT_SOURCE_DIR}/KF6GuiAddonsConfig.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/KF6GuiAddonsConfig.cmake"
INSTALL_DESTINATION ${CMAKECONFIG_INSTALL_DIR}
)
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/KF6GuiAddonsConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/KF6GuiAddonsConfigVersion.cmake"
DESTINATION "${CMAKECONFIG_INSTALL_DIR}"
COMPONENT Devel )
install(EXPORT KF6GuiAddonsTargets DESTINATION "${CMAKECONFIG_INSTALL_DIR}"
FILE KF6GuiAddonsTargets.cmake NAMESPACE KF6:: COMPONENT Devel)
install(FILES ${kguiaddons_version_header}
DESTINATION ${KDE_INSTALL_INCLUDEDIR_KF}/KGuiAddons COMPONENT Devel)
if (NOT WIN32)
ecm_generate_pkgconfig_file(BASE_NAME KF6GuiAddons
INCLUDE_INSTALL_DIR ${KDE_INSTALL_INCLUDEDIR_KF}/KGuiAddons
DEPS Qt6Gui
INSTALL)
endif()
include(ECMFeatureSummary)
ecm_feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
kde_configure_git_pre_commit_hook(CHECKS CLANG_FORMAT)
@@ -0,0 +1,25 @@
@PACKAGE_INIT@
# Any changes in this file will be overwritten by CMake.
include(CMakeFindDependencyMacro)
find_dependency(Qt6Gui @REQUIRED_QT_VERSION@)
if (NOT @BUILD_SHARED_LIBS@)
if (@WITH_X11@)
find_dependency(X11)
find_dependency(XCB COMPONENTS XCB)
endif()
if (@WITH_WAYLAND@)
find_dependency(Wayland REQUIRED Client)
find_dependency(Qt6WaylandClient @REQUIRED_QT_VERSION@)
find_dependency(QtWaylandScanner)
endif()
if (@WITH_DBUS@)
find_dependency(Qt6DBus @REQUIRED_QT_VERSION@)
endif()
endif()
include("${CMAKE_CURRENT_LIST_DIR}/KF6GuiAddonsTargets.cmake")
@PACKAGE_INCLUDE_QCHTARGETS@
@@ -0,0 +1,9 @@
Copyright (c) <year> <owner>
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.
@@ -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.
@@ -0,0 +1,319 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 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.
Preamble
The licenses for most software are designed to take away your freedom to share
and change it. By contrast, the GNU General Public License is intended to
guarantee your freedom to share and change free software--to make sure the
software is free for all its users. This General Public License applies to
most of the Free Software Foundation's software and to any other program whose
authors commit to using it. (Some other Free Software Foundation software
is covered by the GNU Lesser General Public License instead.) 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 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 software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or
for a fee, you must give the recipients all the rights that you have. 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.
We protect your rights with two steps: (1) copyright the software, and (2)
offer you this license which gives you legal permission to copy, distribute
and/or modify the software.
Also, for each author's protection and ours, we want to make certain that
everyone understands that there is no warranty for this free software. If
the software is modified by someone else and passed on, we want its recipients
to know that what they have is not the original, 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 redistributors of a free program will individually
obtain patent licenses, in effect making the program proprietary. To prevent
this, we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification
follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice
placed by the copyright holder saying it may be distributed under the terms
of this General Public License. The "Program", below, refers to any such program
or work, and a "work based on the Program" means either the Program or any
derivative work under copyright law: that is to say, a work containing the
Program or a portion of it, either verbatim or with modifications and/or translated
into another language. (Hereinafter, translation is included without limitation
in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered
by this License; they are outside its scope. The act of running the Program
is not restricted, and the output from the Program is covered only if its
contents constitute a work based on the Program (independent of having been
made by running the Program). Whether that is true depends on what the Program
does.
1. You may copy and distribute 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 and disclaimer of warranty;
keep intact all the notices that refer to this License and to the absence
of any warranty; and give any other recipients of the Program a copy of this
License along with the Program.
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 Program or any portion of it,
thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices stating that
you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or
in part contains or is derived from the Program or any part thereof, to be
licensed as a whole at no charge to all third parties under the terms of this
License.
c) If the modified program normally reads commands interactively when run,
you must cause it, when started running for such interactive use in the most
ordinary way, to print or display an announcement including an appropriate
copyright notice and a notice that there is no warranty (or else, saying that
you provide a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this License.
(Exception: if the Program itself is interactive but does not normally print
such an announcement, your work based on the Program is not required to print
an announcement.)
These requirements apply to the modified work as a whole. If identifiable
sections of that work are not derived from the Program, 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 Program, 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 Program.
In addition, mere aggregation of another work not based on the Program with
the Program (or with a work based on the Program) on a volume of a storage
or distribution medium does not bring the other work under the scope of this
License.
3. You may copy and distribute the Program (or a work based on it, under Section
2) in object code or executable form under the terms of Sections 1 and 2 above
provided that you also do one of the following:
a) 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; or,
b) Accompany it with a written offer, valid for at least three years, to give
any third party, for a charge no more than your cost of physically performing
source distribution, a complete machine-readable copy of the corresponding
source code, to be distributed under the terms of Sections 1 and 2 above on
a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute
corresponding source code. (This alternative is allowed only for noncommercial
distribution and only if you received the program in object code or executable
form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making
modifications to it. For an executable work, 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 executable. 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.
If distribution of executable or 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 counts as distribution of the source code,
even though third parties are not compelled to copy the source along with
the object code.
4. You may not copy, modify, sublicense, or distribute the Program except
as expressly provided under this License. Any attempt otherwise to copy, modify,
sublicense or distribute the Program 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.
5. 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
Program or its derivative works. These actions are prohibited by law if you
do not accept this License. Therefore, by modifying or distributing the Program
(or any work based on the Program), you indicate your acceptance of this License
to do so, and all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program),
the recipient automatically receives a license from the original licensor
to copy, distribute or modify the Program 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.
7. 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 Program at all. For example, if a
patent license would not permit royalty-free redistribution of the Program
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 Program.
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.
8. If the distribution and/or use of the Program is restricted in certain
countries either by patents or by copyrighted interfaces, the original copyright
holder who places the Program 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.
9. The Free Software Foundation may publish revised and/or new versions of
the 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
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
Program does not specify a version number of this License, you may choose
any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs
whose distribution conditions are different, 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
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. 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 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.
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 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 program's name and an idea of what it does.>
Copyright (C)< yyyy> <name of author>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; 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.
If the program is interactive, make it output a short notice like this when
it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be
called something other than `show w' and `show c'; they could even be mouse-clicks
or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school,
if any, to sign a "copyright disclaimer" for the program, if necessary. Here
is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision'
(which makes passes at compilers) written by James Hacker.
<signature of Ty Coon >, 1 April 1989 Ty Coon, President of Vice This 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.
@@ -0,0 +1,319 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 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.
Preamble
The licenses for most software are designed to take away your freedom to share
and change it. By contrast, the GNU General Public License is intended to
guarantee your freedom to share and change free software--to make sure the
software is free for all its users. This General Public License applies to
most of the Free Software Foundation's software and to any other program whose
authors commit to using it. (Some other Free Software Foundation software
is covered by the GNU Lesser General Public License instead.) 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 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 software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or
for a fee, you must give the recipients all the rights that you have. 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.
We protect your rights with two steps: (1) copyright the software, and (2)
offer you this license which gives you legal permission to copy, distribute
and/or modify the software.
Also, for each author's protection and ours, we want to make certain that
everyone understands that there is no warranty for this free software. If
the software is modified by someone else and passed on, we want its recipients
to know that what they have is not the original, 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 redistributors of a free program will individually
obtain patent licenses, in effect making the program proprietary. To prevent
this, we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification
follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice
placed by the copyright holder saying it may be distributed under the terms
of this General Public License. The "Program", below, refers to any such program
or work, and a "work based on the Program" means either the Program or any
derivative work under copyright law: that is to say, a work containing the
Program or a portion of it, either verbatim or with modifications and/or translated
into another language. (Hereinafter, translation is included without limitation
in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered
by this License; they are outside its scope. The act of running the Program
is not restricted, and the output from the Program is covered only if its
contents constitute a work based on the Program (independent of having been
made by running the Program). Whether that is true depends on what the Program
does.
1. You may copy and distribute 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 and disclaimer of warranty;
keep intact all the notices that refer to this License and to the absence
of any warranty; and give any other recipients of the Program a copy of this
License along with the Program.
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 Program or any portion of it,
thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices stating that
you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or
in part contains or is derived from the Program or any part thereof, to be
licensed as a whole at no charge to all third parties under the terms of this
License.
c) If the modified program normally reads commands interactively when run,
you must cause it, when started running for such interactive use in the most
ordinary way, to print or display an announcement including an appropriate
copyright notice and a notice that there is no warranty (or else, saying that
you provide a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this License.
(Exception: if the Program itself is interactive but does not normally print
such an announcement, your work based on the Program is not required to print
an announcement.)
These requirements apply to the modified work as a whole. If identifiable
sections of that work are not derived from the Program, 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 Program, 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 Program.
In addition, mere aggregation of another work not based on the Program with
the Program (or with a work based on the Program) on a volume of a storage
or distribution medium does not bring the other work under the scope of this
License.
3. You may copy and distribute the Program (or a work based on it, under Section
2) in object code or executable form under the terms of Sections 1 and 2 above
provided that you also do one of the following:
a) 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; or,
b) Accompany it with a written offer, valid for at least three years, to give
any third party, for a charge no more than your cost of physically performing
source distribution, a complete machine-readable copy of the corresponding
source code, to be distributed under the terms of Sections 1 and 2 above on
a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute
corresponding source code. (This alternative is allowed only for noncommercial
distribution and only if you received the program in object code or executable
form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making
modifications to it. For an executable work, 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 executable. 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.
If distribution of executable or 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 counts as distribution of the source code,
even though third parties are not compelled to copy the source along with
the object code.
4. You may not copy, modify, sublicense, or distribute the Program except
as expressly provided under this License. Any attempt otherwise to copy, modify,
sublicense or distribute the Program 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.
5. 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
Program or its derivative works. These actions are prohibited by law if you
do not accept this License. Therefore, by modifying or distributing the Program
(or any work based on the Program), you indicate your acceptance of this License
to do so, and all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program),
the recipient automatically receives a license from the original licensor
to copy, distribute or modify the Program 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.
7. 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 Program at all. For example, if a
patent license would not permit royalty-free redistribution of the Program
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 Program.
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.
8. If the distribution and/or use of the Program is restricted in certain
countries either by patents or by copyrighted interfaces, the original copyright
holder who places the Program 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.
9. The Free Software Foundation may publish revised and/or new versions of
the 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
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
Program does not specify a version number of this License, you may choose
any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs
whose distribution conditions are different, 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
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. 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 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.
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 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 program's name and an idea of what it does.>
Copyright (C) <yyyy> <name of author>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; 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.
If the program is interactive, make it output a short notice like this when
it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be
called something other than `show w' and `show c'; they could even be mouse-clicks
or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school,
if any, to sign a "copyright disclaimer" for the program, if necessary. Here
is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision'
(which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This 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.
@@ -0,0 +1,625 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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 <https://www.gnu.org/
licenses /why-not-lgpl.html>.
@@ -0,0 +1,175 @@
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.
GNU LIBRARY GENERAL PUBLIC LICENSE
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!
@@ -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!
@@ -0,0 +1,467 @@
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!
@@ -0,0 +1,163 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
@@ -0,0 +1,12 @@
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of
the license or (at your option) at 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 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
@@ -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.
@@ -0,0 +1,48 @@
# KDE GUI Addons
Utilities for graphical user interfaces
## Introduction
The &KDE GUI addons provide utilities for graphical user interfaces in the areas
of colors, fonts, text, images, keyboard input.
## Usage
To use KGuiAddons, you'll want to look for it using
```cmake
find_package(KF6GuiAddons)
```
or its QMake counterpart.
### Color utilities
The KColorUtils namespace contains various small utilities to work with colors. KColorCollection provides
handling of color collections ("pallettes"). KColorMimeData adds drag-and-drop and clipboard mimedata
manipulation to QColor objects
### Text utilities
KWordWrap is a special word wrapping algorithm that takes beauty into account. It can be used
directly with QPainter or can return the wrapped text in a QString.
KDateValidator is a QValidator that validates user-entered dates.
KFontUtils::adaptFontSize() is a function that calculates the biggest font size (in points)
that can be used to draw a text centered in a rectangle using word wrapping.
### Keyboard utilities
KKeySequenceRecorder is a utility that records a QKeySequence by listening to key events in a window.
This can be used to let the user modify predefined keyboard shortcuts for example.
### Icon utilities
KIconUtils contains functions to add overlays on top of a QIcon.
### Cursor utilities
KCursorSaver is used to temporarily set a mouse cursor and restore the previous one on destruction.
@@ -0,0 +1,3 @@
SPDX-FileCopyrightText: 2014 Cornelius Schumacher <schumacher@kde.org>
SPDX-FileCopyrightText: 2021 Carl Schwan <carlschwan@kde.org>
SPDX-FileCopyrightText: LGPL-2.1-or-later
@@ -0,0 +1,17 @@
find_package(Qt6 ${REQUIRED_QT_VERSION} CONFIG REQUIRED Test)
remove_definitions(-DQT_NO_CAST_FROM_ASCII)
include(ECMAddTests)
ecm_add_tests(
kwordwraptest.cpp
kcolorutilstest.cpp
kiconutilstest.cpp
kcursorsavertest.cpp
kkeysequencerecordertest.cpp
kurlhandlertest.cpp
kcountryflagemojiiconenginetest.cpp
LINK_LIBRARIES KF6::GuiAddons Qt6::Test
)
ecm_add_tests(kgeourihandlertest.cpp LINK_LIBRARIES Qt6::Test)
@@ -0,0 +1,153 @@
#include "kcolorutilstest.h"
#include <QTest>
#include "../colors/kcolorspaces.cpp" // private implementation
#include "../colors/kcolorspaces_p.h" // private header
#include <kcolorutils.h>
void tst_KColorUtils::testOverlay()
{
QColor color1(10, 10, 100);
QColor color2(10, 10, 160);
QColor blended = KColorUtils::overlayColors(color1, color2);
QCOMPARE(blended, color2); // no transparency.
QColor previous;
// check that when altering the alpha of color2 to be less and less transparent this
// means we are moving more and more towards color2
for (int i = 10; i <= 255; i += 10) {
color2.setAlpha(i);
blended = KColorUtils::overlayColors(color1, color2);
if (previous.isValid()) {
QCOMPARE(previous.red(), 10);
QCOMPARE(previous.green(), 10);
QVERIFY(previous.blue() <= blended.blue());
}
previous = blended;
}
// only the alpha of color 2 alters the output
color2.setAlpha(255); // opaque
color1.setAlpha(80); // opaque
blended = KColorUtils::overlayColors(color2, color2);
QCOMPARE(blended.red(), color2.red());
QCOMPARE(blended.green(), color2.green());
QCOMPARE(blended.blue(), color2.blue());
// merge from itself to itself gives; TADA; itself again ;)
color2.setAlpha(127);
blended = KColorUtils::overlayColors(color2, color2);
QCOMPARE(blended.red(), color2.red());
QCOMPARE(blended.green(), color2.green());
QCOMPARE(blended.blue(), color2.blue());
}
/* clang-format off */
#define compareColors(c1, c2) \
if (c1 != c2) { \
fprintf(stderr, "%08x != expected value %08x\n", c1.rgb(), c2.rgb()); \
QCOMPARE(c1, c2); \
} \
(void)0
/* clang-format on */
void tst_KColorUtils::testMix()
{
int r;
int g;
int b;
int k;
for (r = 0; r < 52; r++) {
for (g = 0; g < 52; g++) {
for (b = 0; b < 52; b++) {
QColor color(r * 5, g * 5, b * 5);
// Test blend-to-black spectrum
for (k = 5; k >= 0; k--) {
QColor result = KColorUtils::mix(Qt::black, color, k * 0.2);
compareColors(result, QColor(r * k, g * k, b * k));
}
// Test blend-to-white spectrum
for (k = 5; k >= 0; k--) {
int n = 51 * (5 - k);
QColor result = KColorUtils::mix(Qt::white, color, k * 0.2);
compareColors(result, QColor(n + r * k, n + g * k, n + b * k));
}
// Test blend-to-self across a couple bias values
for (k = 5; k >= 0; k--) {
QColor result = KColorUtils::mix(color, color, k * 0.2);
compareColors(result, color);
}
}
}
}
const auto colorA = QColor::fromRgb(255, 255, 255, 1);
const auto colorB = QColor::fromRgb(0, 0, 0, 255);
const auto mixed = KColorUtils::mix(colorA, colorB, 0.5);
QVERIFY2(mixed.redF() <= 0.01, "colorA should have little influence on colorB due to low opacity");
QVERIFY2(mixed.greenF() <= 0.01, "colorA should have little influence on colorB due to low opacity");
QVERIFY2(mixed.blueF() <= 0.01, "colorA should have little influence on colorB due to low opacity");
}
void tst_KColorUtils::testHCY()
{
int r;
int g;
int b;
for (r = 0; r < 256; r += 5) {
for (g = 0; g < 256; g += 5) {
for (b = 0; b < 256; b += 5) {
QColor color(r, g, b);
KColorSpaces::KHCY hcy(color);
compareColors(hcy.qColor(), color);
}
}
}
}
void tst_KColorUtils::testContrast()
{
QCOMPARE(KColorUtils::contrastRatio(Qt::black, Qt::white), qreal(21.0));
QCOMPARE(KColorUtils::contrastRatio(Qt::white, Qt::black), qreal(21.0));
QCOMPARE(KColorUtils::contrastRatio(Qt::black, Qt::black), qreal(1.0));
QCOMPARE(KColorUtils::contrastRatio(Qt::white, Qt::white), qreal(1.0));
// TODO better tests :-)
}
void checkIsGray(const QColor &color, int line)
{
KColorSpaces::KHCY hcy(color);
if (hcy.c != qreal(0.0)) {
fprintf(stderr, "%08x has chroma %g, expected gray!\n", color.rgb(), hcy.c);
}
QTest::qCompare(hcy.c, qreal(0.0), "hcy.c", "0.0", __FILE__, line);
}
void tst_KColorUtils::testShading()
{
const QColor testGray(128, 128, 128); // Qt::gray isn't pure gray!
// Test that KHCY gets chroma correct for white/black, grays
checkIsGray(Qt::white, __LINE__);
checkIsGray(testGray, __LINE__);
checkIsGray(Qt::black, __LINE__);
// Test that lighten/darken/shade don't change chroma for grays
checkIsGray(KColorUtils::shade(Qt::white, -0.1), __LINE__);
checkIsGray(KColorUtils::shade(Qt::black, 0.1), __LINE__);
checkIsGray(KColorUtils::darken(Qt::white, 0.1), __LINE__);
checkIsGray(KColorUtils::darken(testGray, 0.1), __LINE__);
checkIsGray(KColorUtils::darken(testGray, -0.1), __LINE__);
checkIsGray(KColorUtils::darken(Qt::black, -0.1), __LINE__);
checkIsGray(KColorUtils::lighten(Qt::black, 0.1), __LINE__);
checkIsGray(KColorUtils::lighten(testGray, 0.1), __LINE__);
checkIsGray(KColorUtils::lighten(testGray, -0.1), __LINE__);
checkIsGray(KColorUtils::lighten(Qt::white, -0.1), __LINE__);
}
QTEST_MAIN(tst_KColorUtils)
#include "moc_kcolorutilstest.cpp"
@@ -0,0 +1,17 @@
#ifndef KCOLORUTILSTEST_H
#define KCOLORUTILSTEST_H
#include <QObject>
class tst_KColorUtils : public QObject
{
Q_OBJECT
private Q_SLOTS:
void testOverlay();
void testMix();
void testHCY();
void testContrast();
void testShading();
};
#endif // KCOLORUTILSTEST_H
@@ -0,0 +1,43 @@
// SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
// SPDX-FileCopyrightText: 2023 Harald Sitter <sitter@kde.org>
#include <QTest>
#include <kcountryflagemojiiconengine.h>
using namespace Qt::Literals::StringLiterals;
class KCountryFlagEmojiIconEngineTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void testIsNull()
{
QVERIFY(KCountryFlagEmojiIconEngine(QString()).isNull());
}
void testAustria()
{
QIcon icon(new KCountryFlagEmojiIconEngine("AT"_L1));
auto pixmap = icon.pixmap(16, 16);
QVERIFY(!pixmap.isNull());
}
void testScotland()
{
QIcon icon(new KCountryFlagEmojiIconEngine("GB-SCT"_L1));
auto pixmap = icon.pixmap(16, 16);
QVERIFY(!pixmap.isNull());
}
void testNonCountry()
{
QIcon icon(new KCountryFlagEmojiIconEngine("LATAM"_L1));
auto pixmap = icon.pixmap(16, 16);
QVERIFY(!pixmap.isNull());
}
};
QTEST_MAIN(KCountryFlagEmojiIconEngineTest)
#include "kcountryflagemojiiconenginetest.moc"
@@ -0,0 +1,36 @@
/*
SPDX-License-Identifier: LGPL-2.0-or-later
SPDX-FileCopyrightText: 2020 Laurent Montel <montel@kde.org>
*/
#include "kcursorsavertest.h"
#include "util/kcursorsaver.h"
#include <QTest>
QTEST_MAIN(KCursorSaverTest)
KCursorSaverTest::KCursorSaverTest(QObject *parent)
: QObject(parent)
{
}
void KCursorSaverTest::ignoreWarning()
{
{
// Emit qwarning when we call twice restoreCursor
KCursorSaver saver(Qt::WaitCursor);
saver.restoreCursor();
QTest::ignoreMessage(QtWarningMsg, "This KCursorSaver doesn't own the cursor anymore, invalid call to restoreCursor().");
saver.restoreCursor();
}
{
// Emit qwarning when "moving A to B and then calling A::restoreCursor()"
KCursorSaver saverA(Qt::WaitCursor);
KCursorSaver saverB = std::move(saverA);
QTest::ignoreMessage(QtWarningMsg, "This KCursorSaver doesn't own the cursor anymore, invalid call to restoreCursor().");
saverA.restoreCursor();
QTest::ignoreMessage(QtWarningMsg, "This KCursorSaver doesn't own the cursor anymore, invalid call to restoreCursor().");
saverB.restoreCursor();
}
}
#include "moc_kcursorsavertest.cpp"
@@ -0,0 +1,21 @@
/*
SPDX-License-Identifier: LGPL-2.0-or-later
SPDX-FileCopyrightText: 2020 Laurent Montel <montel@kde.org>
*/
#ifndef KCURSORSAVERTEST_H
#define KCURSORSAVERTEST_H
#include <QObject>
class KCursorSaverTest : public QObject
{
Q_OBJECT
public:
explicit KCursorSaverTest(QObject *parent = nullptr);
~KCursorSaverTest() override = default;
private Q_SLOTS:
void ignoreWarning();
};
#endif // KCURSORSAVERTEST_H
@@ -0,0 +1,60 @@
/*
SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "../src/geo-scheme-handler/kgeourihandler.cpp"
#include <QTest>
class KGeoUriHandlerTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void testHandler_data()
{
QTest::addColumn<QString>("input");
QTest::addColumn<QString>("output");
QTest::newRow("empty") << QString() << QStringLiteral("https://openstreetmap.org");
QTest::newRow("incomplete-1") << QStringLiteral("geo:") << QStringLiteral("https://openstreetmap.org");
QTest::newRow("incomplete-2") << QStringLiteral("geo:46.1") << QStringLiteral("https://openstreetmap.org");
QTest::newRow("broken-1") << QStringLiteral("geo:a,b") << QStringLiteral("https://openstreetmap.org");
QTest::newRow("broken-2") << QStringLiteral("geo:46.1;7.783") << QStringLiteral("https://openstreetmap.org");
QTest::newRow("lat-out-of-range-1") << QStringLiteral("geo:91.0;-1.0") << QStringLiteral("https://openstreetmap.org");
QTest::newRow("lat-out-of-range-2") << QStringLiteral("geo:-91.0;1.0") << QStringLiteral("https://openstreetmap.org");
QTest::newRow("lon-out-of-range-1") << QStringLiteral("geo:1.0;181.0") << QStringLiteral("https://openstreetmap.org");
QTest::newRow("lon-out-of-range-2") << QStringLiteral("geo:-1.0;-181.0") << QStringLiteral("https://openstreetmap.org");
QTest::newRow("2d-coord-only") << QStringLiteral("geo:46.1,7.783") << QStringLiteral("https://www.openstreetmap.org/#map=18/46.1/7.783");
QTest::newRow("3d-coord") << QStringLiteral("geo:46.1,7.783,1600") << QStringLiteral("https://www.openstreetmap.org/#map=18/46.1/7.783");
QTest::newRow("2d-coord-with-uncertainty") << QStringLiteral("geo:46.1,7.783;u=100")
<< QStringLiteral("https://www.openstreetmap.org/#map=18/46.1/7.783");
QTest::newRow("2d-coord-with-z") << QStringLiteral("geo:46.1,7.783?z=19") << QStringLiteral("https://www.openstreetmap.org/#map=19/46.1/7.783");
QTest::newRow("negative-coord") << QStringLiteral("geo:-34.59,-58.375") << QStringLiteral("https://www.openstreetmap.org/#map=18/-34.59/-58.375");
QTest::newRow("query") << QStringLiteral("geo:0,0?q=Randa") << QStringLiteral("https://www.openstreetmap.org/search?query=Randa");
QTest::newRow("query-with-coord") << QStringLiteral("geo:46.1,7.783?q=Randa") << QStringLiteral("https://www.openstreetmap.org/search?query=Randa");
// explicit coordinate reference systems
QTest::newRow("WGS84") << QStringLiteral("geo:37.78,-122.4;u=35;crs=wgs84") << QStringLiteral("https://www.openstreetmap.org/#map=18/37.78/-122.4");
QTest::newRow("EPSG:32618") << QStringLiteral("geo:323482,4306480;crs=EPSG:32618;u=20") << QStringLiteral("https://openstreetmap.org");
QTest::newRow("moon") << QStringLiteral("geo:37.786971,-122.399677;crs=Moon-2011;u=35") << QStringLiteral("https://openstreetmap.org");
}
void testHandler()
{
QFETCH(QString, input);
QFETCH(QString, output);
KGeoUriHandler handler;
handler.setCoordinateTemplate(QStringLiteral("https://www.openstreetmap.org/#map=<Z>/<LAT>/<LON>"));
handler.setQueryTemplate(QStringLiteral("https://www.openstreetmap.org/search?query=<Q>"));
handler.setFallbackUrl(QStringLiteral("https://openstreetmap.org"));
QCOMPARE(handler.handleUri(QUrl(input)), output);
}
};
QTEST_APPLESS_MAIN(KGeoUriHandlerTest)
#include "kgeourihandlertest.moc"
@@ -0,0 +1,191 @@
/*
SPDX-FileCopyrightText: 2013 Martin Klapetek <mklapetek@kde.org>
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/
#include "kiconutilstest.h"
#include <kiconutils.h>
#include <QIcon>
#include <QPainter>
#include <QPixmap>
#include <QTest>
QTEST_MAIN(KIconUtilsTest)
void KIconUtilsTest::addOverlayTest()
{
QPixmap rectanglePixmap(32, 32);
rectanglePixmap.fill(Qt::red);
QIcon icon(rectanglePixmap);
QPixmap overlay(32, 32);
overlay.fill(Qt::blue);
QIcon overlayIcon(overlay);
QIcon iconWithOverlay = KIconUtils::addOverlay(icon, overlayIcon, Qt::BottomRightCorner);
QImage result = iconWithOverlay.pixmap(32, 32).toImage();
int bluePixels = 0;
int redPixels = 0;
// Go over the image and count red and blue pixels
for (int y = 0; y < result.height(); ++y) {
for (int x = 0; x < result.width(); ++x) {
if (qRed(result.pixel(x, y)) == 255) {
redPixels++;
} else if (qBlue(result.pixel(x, y)) == 255) {
bluePixels++;
}
}
}
// For icon of size 32x32, the overlay should be 16x16 (=256)
QCOMPARE(bluePixels, 256);
QCOMPARE(redPixels, 768);
// Try different size and position
rectanglePixmap = rectanglePixmap.scaled(96, 96);
icon = QIcon(rectanglePixmap);
overlay = overlay.scaled(96, 96);
overlayIcon = QIcon(overlay);
iconWithOverlay = KIconUtils::addOverlay(icon, overlayIcon, Qt::BottomRightCorner);
// Test if unsetting the overlay works;
// the result should have just one blue square
iconWithOverlay = KIconUtils::addOverlay(icon, QIcon(), Qt::BottomRightCorner);
iconWithOverlay = KIconUtils::addOverlay(icon, overlayIcon, Qt::TopLeftCorner);
result = iconWithOverlay.pixmap(96, 96).toImage();
bluePixels = 0;
redPixels = 0;
for (int y = 0; y < result.height(); ++y) {
for (int x = 0; x < result.width(); ++x) {
if (qRed(result.pixel(x, y)) == 255) {
redPixels++;
} else if (qBlue(result.pixel(x, y)) == 255) {
bluePixels++;
}
}
}
// 96x96 big icon will have 32x32 big overlay (=1024 blue pixels)
QCOMPARE(bluePixels, 1024);
QCOMPARE(redPixels, 8192);
// Try paint method
icon = QIcon(rectanglePixmap);
iconWithOverlay = KIconUtils::addOverlay(icon, overlayIcon, Qt::TopLeftCorner);
QPixmap a(96, 96);
QPainter p(&a);
iconWithOverlay.paint(&p, a.rect(), Qt::AlignCenter, QIcon::Normal, QIcon::Off);
result = a.toImage();
bluePixels = 0;
redPixels = 0;
for (int y = 0; y < result.height(); ++y) {
for (int x = 0; x < result.width(); ++x) {
if (qRed(result.pixel(x, y)) == 255) {
redPixels++;
} else if (qBlue(result.pixel(x, y)) == 255) {
bluePixels++;
}
}
}
// 96x96 big icon will have 32x32 big overlay (=1024 blue pixels)
QCOMPARE(bluePixels, 1024);
QCOMPARE(redPixels, 8192);
}
void KIconUtilsTest::addOverlaysTest()
{
QPixmap rectanglePixmap(32, 32);
rectanglePixmap.fill(Qt::red);
QIcon icon(rectanglePixmap);
QPixmap overlay(32, 32);
overlay.fill(Qt::blue);
QIcon overlayIcon(overlay);
QHash<Qt::Corner, QIcon> overlays;
overlays.insert(Qt::BottomRightCorner, overlayIcon);
overlays.insert(Qt::TopLeftCorner, overlayIcon);
QIcon iconWithOverlay = KIconUtils::addOverlays(icon, overlays);
QImage result = iconWithOverlay.pixmap(32, 32).toImage();
int bluePixels = 0;
int redPixels = 0;
// Go over the image and count red and blue pixels
for (int y = 0; y < result.height(); ++y) {
for (int x = 0; x < result.width(); ++x) {
if (qRed(result.pixel(x, y)) == 255) {
redPixels++;
} else if (qBlue(result.pixel(x, y)) == 255) {
bluePixels++;
}
}
}
// Two blue overlays in icon size 32x32 would intersect with 16 pixels,
// so the amount of blue pixels should be 2x256-16 = 496
QCOMPARE(bluePixels, 496);
QCOMPARE(redPixels, 528);
// Try different size
rectanglePixmap = rectanglePixmap.scaled(96, 96);
icon = QIcon(rectanglePixmap);
overlay = overlay.scaled(96, 96);
overlayIcon = QIcon(overlay);
// Clear the old sizes first
overlays.clear();
overlays.insert(Qt::BottomRightCorner, overlayIcon);
overlays.insert(Qt::TopRightCorner, overlayIcon);
overlays.insert(Qt::TopLeftCorner, overlayIcon);
// Now it will have 3 overlays
iconWithOverlay = KIconUtils::addOverlays(icon, overlays);
QPixmap a(96, 96);
QPainter p(&a);
iconWithOverlay.paint(&p, a.rect(), Qt::AlignCenter, QIcon::Normal, QIcon::Off);
result = a.toImage();
bluePixels = 0;
redPixels = 0;
for (int y = 0; y < result.height(); ++y) {
for (int x = 0; x < result.width(); ++x) {
if (qRed(result.pixel(x, y)) == 255) {
redPixels++;
} else if (qBlue(result.pixel(x, y)) == 255) {
bluePixels++;
}
}
}
// 96x96 big icon will have 32x32 big overlays (=3072 blue pixels)
QCOMPARE(bluePixels, 3072);
QCOMPARE(redPixels, 6144);
}
#include "moc_kiconutilstest.cpp"
@@ -0,0 +1,20 @@
/*
SPDX-FileCopyrightText: 2013 Martin Klapetek <mklapetek@kde.org>
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/
#ifndef KICONUTILSTEST_H
#define KICONUTILSTEST_H
#include <QObject>
class KIconUtilsTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void addOverlayTest();
void addOverlaysTest();
};
#endif // KICONUTILSTEST_H
@@ -0,0 +1,293 @@
/*
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>
*/
#include "kkeysequencerecordertest.h"
#include "kkeysequencerecorder.h"
#include <QSignalSpy>
#include <QTest>
#include <QWindow>
QTEST_MAIN(KKeySequenceRecorderTest)
void KKeySequenceRecorderTest::initTestCase()
{
m_window = new QWindow;
}
void KKeySequenceRecorderTest::cleanupTestCase()
{
delete m_window;
}
void KKeySequenceRecorderTest::testValidWindow()
{
KKeySequenceRecorder recorder(nullptr);
QSignalSpy recordingSpy(&recorder, &KKeySequenceRecorder::recordingChanged);
recorder.startRecording();
QCOMPARE(recordingSpy.count(), 0);
QVERIFY(!recorder.isRecording());
recorder.setWindow(m_window);
recorder.startRecording();
QCOMPARE(recordingSpy.count(), 2);
QVERIFY(recorder.isRecording());
}
void KKeySequenceRecorderTest::testRecording()
{
KKeySequenceRecorder recorder(m_window);
QSignalSpy recordingSpy(&recorder, &KKeySequenceRecorder::recordingChanged);
QSignalSpy sequenceSpy(&recorder, &KKeySequenceRecorder::currentKeySequenceChanged);
QSignalSpy resultSpy(&recorder, &KKeySequenceRecorder::gotKeySequence);
recorder.startRecording();
QVERIFY(recorder.isRecording());
QCOMPARE(recordingSpy.count(), 1);
QCOMPARE(sequenceSpy.count(), 1);
QTest::keyClick(m_window, Qt::Key_A, Qt::ControlModifier);
QVERIFY(recorder.isRecording());
QCOMPARE(recordingSpy.count(), 1);
QCOMPARE(sequenceSpy.count(), 4); // two key events + modifier release
QCOMPARE(resultSpy.count(), 0);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::Key_A | Qt::ControlModifier));
QTest::qWait(800);
QCOMPARE(sequenceSpy.count(), 4);
QCOMPARE(recordingSpy.count(), 2);
QVERIFY(!recorder.isRecording());
QCOMPARE(resultSpy.count(), 1);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::Key_A | Qt::ControlModifier));
QCOMPARE(resultSpy.takeFirst().at(0).value<QKeySequence>(), QKeySequence(Qt::Key_A | Qt::ControlModifier));
}
void KKeySequenceRecorderTest::testModifiers()
{
KKeySequenceRecorder recorder(m_window);
QSignalSpy recordingSpy(&recorder, &KKeySequenceRecorder::recordingChanged);
QSignalSpy sequenceSpy(&recorder, &KKeySequenceRecorder::currentKeySequenceChanged);
QSignalSpy resultSpy(&recorder, &KKeySequenceRecorder::gotKeySequence);
recorder.startRecording();
QCOMPARE(sequenceSpy.count(), 1);
QCOMPARE(recordingSpy.count(), 1);
QVERIFY(recorder.isRecording());
QTest::keyPress(m_window, Qt::Key_Control);
QCOMPARE(sequenceSpy.count(), 2);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::ControlModifier));
// Releasing a different key because when releasing Key_Meta, QTest sends a KeyRelease event
// with MetaModifier even though modifieres should be empty
QTest::keyRelease(m_window, Qt::Key_A, Qt::NoModifier);
QCOMPARE(sequenceSpy.count(), 3);
QCOMPARE(recorder.currentKeySequence(), QKeySequence());
QCOMPARE(recordingSpy.count(), 1);
QVERIFY(recorder.isRecording());
QTRY_VERIFY_WITH_TIMEOUT(recorder.isRecording(), 800);
QTest::keyPress(m_window, Qt::Key_Control);
QCOMPARE(sequenceSpy.count(), 4);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::ControlModifier));
QTest::keyPress(m_window, Qt::Key_Alt, Qt::ControlModifier);
QCOMPARE(sequenceSpy.count(), 6); // QTest sends two key events, one for each modifier
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::AltModifier | Qt::ControlModifier));
QCOMPARE(resultSpy.count(), 0); // modifierless not allowed
}
void KKeySequenceRecorderTest::testModifierless()
{
KKeySequenceRecorder recorder(m_window);
QSignalSpy resultSpy(&recorder, &KKeySequenceRecorder::gotKeySequence);
QSignalSpy sequenceSpy(&recorder, &KKeySequenceRecorder::currentKeySequenceChanged);
recorder.startRecording();
QVERIFY(recorder.isRecording());
QCOMPARE(sequenceSpy.count(), 1);
recorder.setModifierlessAllowed(false);
QTest::keyPress(m_window, Qt::Key_A);
QTRY_VERIFY_WITH_TIMEOUT(recorder.isRecording(), 800);
QCOMPARE(sequenceSpy.count(), 1);
QCOMPARE(resultSpy.count(), 0);
QCOMPARE(recorder.currentKeySequence(), QKeySequence());
recorder.setModifierlessAllowed(true);
QTest::keyClick(m_window, Qt::Key_A);
QTRY_VERIFY_WITH_TIMEOUT(!recorder.isRecording(), 800);
QCOMPARE(sequenceSpy.count(), 2);
QCOMPARE(resultSpy.count(), 1);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::Key_A));
}
void KKeySequenceRecorderTest::testModifierOnly()
{
KKeySequenceRecorder recorder(m_window);
recorder.setModifierOnlyAllowed(true);
recorder.setModifierlessAllowed(true);
QSignalSpy resultSpy(&recorder, &KKeySequenceRecorder::gotKeySequence);
QSignalSpy recordingSpy(&recorder, &KKeySequenceRecorder::recordingChanged);
QSignalSpy sequenceSpy(&recorder, &KKeySequenceRecorder::currentKeySequenceChanged);
recorder.startRecording();
QVERIFY(recorder.isRecording());
QCOMPARE(sequenceSpy.count(), 1);
QTest::keyClick(m_window, Qt::Key_Shift);
recordingSpy.wait();
QVERIFY(!recorder.isRecording());
QCOMPARE(sequenceSpy.count(), 3);
QCOMPARE(resultSpy.count(), 1);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::Key_Shift));
}
void KKeySequenceRecorderTest::testModifierOnlyMultiple()
{
KKeySequenceRecorder recorder(m_window);
recorder.setModifierOnlyAllowed(true);
recorder.setModifierlessAllowed(true);
QSignalSpy resultSpy(&recorder, &KKeySequenceRecorder::gotKeySequence);
QSignalSpy recordingSpy(&recorder, &KKeySequenceRecorder::recordingChanged);
recorder.startRecording();
QVERIFY(recorder.isRecording());
QTest::keyPress(m_window, Qt::Key_Shift);
Qt::KeyboardModifiers modifiers = Qt::ShiftModifier;
QTest::keyPress(m_window, Qt::Key_Control, modifiers);
modifiers |= Qt::ControlModifier;
modifiers |= Qt::AltModifier;
QTest::keyPress(m_window, Qt::Key_Alt, modifiers);
QTest::keyPress(m_window, Qt::Key_Meta, modifiers);
modifiers |= Qt::MetaModifier;
QTest::qWait(200);
QTest::keyRelease(m_window, Qt::Key_Control, modifiers);
modifiers &= ~Qt::ControlModifier;
QTest::qWait(10);
QTest::keyRelease(m_window, Qt::Key_Alt, modifiers);
modifiers &= ~Qt::AltModifier;
modifiers &= ~Qt::ShiftModifier;
QTest::qWait(10);
QTest::keyRelease(m_window, Qt::Key_Shift, modifiers);
QTest::qWait(10);
QTest::keyRelease(m_window, Qt::Key_Meta, modifiers);
recordingSpy.wait();
QVERIFY(!recorder.isRecording());
QCOMPARE(resultSpy.count(), 1);
QCOMPARE(resultSpy.takeFirst().at(0).value<QKeySequence>(), QKeySequence(Qt::MetaModifier | Qt::ControlModifier | Qt::AltModifier | Qt::Key_Shift));
}
void KKeySequenceRecorderTest::testModifierOnlyMultipleInterrupt()
{
KKeySequenceRecorder recorder(m_window);
recorder.setModifierOnlyAllowed(true);
recorder.setModifierlessAllowed(true);
QSignalSpy resultSpy(&recorder, &KKeySequenceRecorder::gotKeySequence);
QSignalSpy recordingSpy(&recorder, &KKeySequenceRecorder::recordingChanged);
recorder.startRecording();
QVERIFY(recorder.isRecording());
QTest::keyPress(m_window, Qt::Key_Control);
QTest::keyPress(m_window, Qt::Key_Meta, Qt::ControlModifier);
QTest::keyClick(m_window, Qt::Key_A, Qt::ControlModifier);
recordingSpy.wait();
QVERIFY(!recorder.isRecording());
QCOMPARE(resultSpy.count(), 1);
QCOMPARE(resultSpy.takeFirst().at(0).value<QKeySequence>(), QKeySequence(Qt::ControlModifier | Qt::Key_A));
}
void KKeySequenceRecorderTest::testModifierOnlyDisabled()
{
KKeySequenceRecorder recorder(m_window);
recorder.setModifierOnlyAllowed(false);
recorder.setModifierlessAllowed(true);
QSignalSpy resultSpy(&recorder, &KKeySequenceRecorder::gotKeySequence);
QSignalSpy recordingSpy(&recorder, &KKeySequenceRecorder::recordingChanged);
QSignalSpy sequenceSpy(&recorder, &KKeySequenceRecorder::currentKeySequenceChanged);
recorder.startRecording();
QVERIFY(recorder.isRecording());
QCOMPARE(sequenceSpy.count(), 1);
QTest::keyClick(m_window, Qt::Key_Shift);
recordingSpy.wait();
QVERIFY(recorder.isRecording());
recorder.cancelRecording();
QCOMPARE(sequenceSpy.count(), 3);
QCOMPARE(resultSpy.count(), 0);
QCOMPARE(recorder.currentKeySequence(), QKeySequence());
}
void KKeySequenceRecorderTest::testMultiKeyAllowed()
{
KKeySequenceRecorder recorder(m_window);
QSignalSpy recordingSpy(&recorder, &KKeySequenceRecorder::recordingChanged);
QSignalSpy resultSpy(&recorder, &KKeySequenceRecorder::gotKeySequence);
recorder.startRecording();
recorder.setMultiKeyShortcutsAllowed(true);
int keys[4] = {0};
for (int i = 0; i < 4; ++i) {
QVERIFY(recorder.isRecording());
QCOMPARE(recordingSpy.count(), 1);
QCOMPARE(resultSpy.count(), 0);
keys[i] = (Qt::Key_A | Qt::ControlModifier).toCombined();
QKeySequence result(keys[0], keys[1], keys[2], keys[3]);
QTest::keyPress(m_window, Qt::Key_A, Qt::ControlModifier);
QTest::keyRelease(m_window, Qt::Key_A, Qt::ControlModifier);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(keys[0], keys[1], keys[2], keys[3]));
}
QVERIFY(!recorder.isRecording());
QCOMPARE(recordingSpy.count(), 2);
QCOMPARE(resultSpy.count(), 1);
QCOMPARE(resultSpy.takeFirst().at(0).value<QKeySequence>(), QKeySequence(keys[0], keys[1], keys[2], keys[3]));
recorder.setMultiKeyShortcutsAllowed(false);
recorder.startRecording();
QVERIFY(recorder.isRecording());
QCOMPARE(recordingSpy.count(), 3);
QTest::keyPress(m_window, Qt::Key_A, Qt::ControlModifier);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::Key_A | Qt::ControlModifier));
QVERIFY(!recorder.isRecording());
QCOMPARE(recordingSpy.count(), 4);
QCOMPARE(resultSpy.count(), 1);
QCOMPARE(resultSpy.takeAt(0).at(0).value<QKeySequence>(), QKeySequence(Qt::Key_A | Qt::ControlModifier));
}
void KKeySequenceRecorderTest::testKeyNonLetterNoModifier()
{
KKeySequenceRecorder recorder(m_window);
QSignalSpy resultSpy(&recorder, &KKeySequenceRecorder::gotKeySequence);
QSignalSpy sequenceSpy(&recorder, &KKeySequenceRecorder::currentKeySequenceChanged);
recorder.startRecording();
QVERIFY(recorder.isRecording());
QCOMPARE(sequenceSpy.count(), 1);
recorder.setModifierlessAllowed(false);
QTest::keyPress(m_window, Qt::Key_Insert);
QTRY_VERIFY_WITH_TIMEOUT(recorder.isRecording(), 800);
QCOMPARE(sequenceSpy.count(), 2);
QCOMPARE(resultSpy.count(), 0);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::Key_Insert));
recorder.setModifierlessAllowed(true);
QTest::keyClick(m_window, Qt::Key_Insert);
QTRY_VERIFY_WITH_TIMEOUT(!recorder.isRecording(), 800);
QCOMPARE(sequenceSpy.count(), 3);
QCOMPARE(resultSpy.count(), 1);
QCOMPARE(recorder.currentKeySequence(), QKeySequence(Qt::Key_Insert, Qt::Key_Insert));
}
#include "moc_kkeysequencerecordertest.cpp"
@@ -0,0 +1,34 @@
/*
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>
*/
#ifndef KKEYSEQUENCERECORDERTEST_H
#define KKEYSEQUENCERECORDERTEST_H
#include <QObject>
class QWindow;
class KKeySequenceRecorderTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testValidWindow();
void testRecording();
void testModifiers();
void testModifierless();
void testModifierOnly();
void testModifierOnlyMultiple();
void testModifierOnlyMultipleInterrupt();
void testModifierOnlyDisabled();
void testMultiKeyAllowed();
void testKeyNonLetterNoModifier();
private:
QWindow *m_window;
};
#endif
@@ -0,0 +1,60 @@
/*
SPDX-FileCopyrightText: 2021 Ahmad Samir <a.samirh78@gmail.com>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kurlhandlertest.h"
#include "kurlhandler_p.h"
#include <QTest>
void KUrlHandlerTest::testOpeningDocsUrls_data()
{
QTest::addColumn<QString>("appname");
QTest::addColumn<QString>("helpUrl");
QTest::addColumn<QString>("expected");
const QString common = "https://docs.kde.org/index.php?branch=stable5&language=" + QLocale().name();
QTest::newRow("okular-help-handbook") << "okular"
<< "help:/" << common + "&application=okular&path=index.html";
QTest::newRow("okular-help-config-dialog") << "okular"
<< "help:/okular/configure.html" << common + "&application=okular&path=configure.html";
QTest::newRow("systemsettings-fonts") << "systemsettings"
<< "help:/kcontrol/fonts/index.html" << common + "&application=kcontrol/fonts&path=index.html";
QTest::newRow("systemsettings-clock") << "systemsettings"
<< "help:/kcontrol/clock/index.html" << common + "&application=kcontrol/clock&path=index.html";
QTest::newRow("systemsettings-powerdevil") << "systemsettings"
<< "help:/kcontrol/powerdevil/index.html#advanced-settings"
<< common + "&application=kcontrol/powerdevil&path=index.html#advanced-settings";
QTest::newRow("with-fragment") << "kinfocenter"
<< "help:/kinfocenter/index.html#kcm_memory" << common + "&application=kinfocenter&path=kcm_memory.html";
QTest::newRow("with-fragment-2") << "okular"
<< "help:/okular/signatures.html#adding_digital_signatures"
<< common + "&application=okular&path=signatures.html#adding_digital_signatures";
}
void KUrlHandlerTest::testOpeningDocsUrls()
{
QFETCH(QString, appname);
QFETCH(QString, helpUrl);
QFETCH(QString, expected);
QCoreApplication::setOrganizationDomain(QStringLiteral("kde.org"));
QCoreApplication::setApplicationName(appname);
const QUrl actual = KUrlHandler().concatDocsUrl(QUrl(helpUrl));
QCOMPARE(actual, QUrl(expected));
}
QTEST_MAIN(KUrlHandlerTest)
#include "moc_kurlhandlertest.cpp"
@@ -0,0 +1,21 @@
/*
SPDX-FileCopyrightText: 2021 Ahmad Samir <a.samirh78@gmail.com>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KURLHANDLERTEST_H
#define KURLHANDLERTEST_H
#include <QObject>
class KUrlHandlerTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void testOpeningDocsUrls_data();
void testOpeningDocsUrls();
};
#endif // KURLHANDLERTEST_H
@@ -0,0 +1,61 @@
/*
SPDX-FileCopyrightText: 2003, 2008 David Faure <faure@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include <QFontMetrics>
#include <QTest>
#include "kwordwrap.h"
#include <QObject>
class KWordWrap_UnitTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase()
{
// Qt5 TODO: how to set the dpi?
// Only found readonly QScreen::logicalDotsPerInch...
#if 0
QX11Info::setAppDpiX(0, 96);
QX11Info::setAppDpiY(0, 96);
#endif
}
void oldTruncationTest()
{
QFont font(QStringLiteral("helvetica"), 12); // let's hope we all have the same...
QFontMetrics fm(font);
QRect r(0, 0, 100, -1);
QString str = QStringLiteral("test wadabada [/foo/bar/waba] and some more text here");
KWordWrap ww = KWordWrap::formatText(fm, r, 0, str);
// qDebug() << str << " => " << ww.truncatedString();
QVERIFY(ww.truncatedString().endsWith("..."));
str = QStringLiteral("</p></p></p></p>");
for (; r.width() > 0; r.setWidth(r.width() - 10)) {
ww = KWordWrap::formatText(fm, r, 0, str);
// qDebug() << str << " => " << ww.truncatedString();
QVERIFY(ww.truncatedString().endsWith("..."));
}
}
void testWithExistingNewlines() // when the input string has \n already
{
QRect r(0, 0, 1000, -1); // very wide
QFont font(QStringLiteral("helvetica"), 12); // let's hope we all have the same...
QFontMetrics fm(font);
QString inputString = QStringLiteral("The title here\nFoo (bar)\nFoo2 (bar2)");
KWordWrap ww = KWordWrap::formatText(fm, r, 0, inputString);
QString str = ww.wrappedString();
QCOMPARE(str, inputString);
}
};
QTEST_MAIN(KWordWrap_UnitTest)
#include "kwordwraptest.moc"
@@ -0,0 +1,20 @@
maintainer:
description: Addons to QtGui
tier: 1
type: functional
platforms:
- name: Linux
- name: FreeBSD
- name: Windows
- name: macOS
- name: Android
portingAid: false
deprecated: false
release: true
libraries:
- cmake: "KF6::GuiAddons"
cmakename: KF6GuiAddons
public_lib: true
group: Frameworks
subgroup: Tier 1
@@ -0,0 +1,44 @@
# SPDX-FileCopyrightText: 2024 Manuel Alcaraz Zambrano <manuelalcarazzam@gmail.com>
# SPDX-License-Identifier: BSD-2-Clause
set(bindings_library "KGuiAddons")
set(wrapped_header ${CMAKE_CURRENT_SOURCE_DIR}/bindings.h)
set(typesystem_file ${CMAKE_CURRENT_SOURCE_DIR}/bindings.xml)
set(generated_sources
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kguiaddons_module_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kcolormimedata_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kcolorschemewatcher_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kcolorutils_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kcountryflagemojiiconengine_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kcursorsaver_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kdatevalidator_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kfontutils_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kiconutils_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kjobwindows_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kkeysequencerecorder_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kmodifierkeyinfo_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/ksystemclipboard_wrapper.cpp
${CMAKE_CURRENT_BINARY_DIR}/KGuiAddons/kwordwrap_wrapper.cpp)
ecm_generate_python_bindings(
PACKAGE_NAME ${bindings_library}
VERSION ${KF_VERSION}
WRAPPED_HEADER ${wrapped_header}
TYPESYSTEM ${typesystem_file}
GENERATED_SOURCES ${generated_sources}
DEPENDENCIES KF6::GuiAddons
QT_VERSION ${REQUIRED_QT_VERSION}
HOMEPAGE_URL "https://invent.kde.org/frameworks/kguiaddons"
ISSUES_URL "https://bugs.kde.org/describecomponents.cgi?product=frameworks-kguiaddons"
AUTHOR "The KDE Community"
README ../README.md
)
target_link_libraries(${bindings_library} PRIVATE KF6::GuiAddons)
execute_process(COMMAND ${Python_EXECUTABLE} -Esc "import sysconfig; print(sysconfig.get_path('platlib', vars={'platbase': '${CMAKE_INSTALL_PREFIX}', 'base': '${CMAKE_INSTALL_PREFIX}'}))" OUTPUT_VARIABLE sysconfig_output)
string(STRIP ${sysconfig_output} PYTHON_INSTALL_DIR)
install(TARGETS ${bindings_library} LIBRARY DESTINATION "${PYTHON_INSTALL_DIR}")
@@ -0,0 +1,24 @@
// SPDX-FileCopyrightText: 2024 Manuel Alcaraz Zambrano <manuelalcarazzam@gmail.com>
// SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
#pragma once
// Make "signals:", "slots:" visible as access specifiers
#define QT_ANNOTATE_ACCESS_SPECIFIER(a) __attribute__((annotate(#a)))
#include <QDate>
#include <KColorMimeData>
#include <KColorSchemeWatcher>
#include <KColorUtils>
#include <KCountryFlagEmojiIconEngine>
#include <KCursorSaver>
#include <KDateValidator>
#include <KFontUtils>
#include <KIconUtils>
#include <KJobWindows>
#include <KKeySequenceRecorder>
#include <KModifierKeyInfo>
#include <KSystemClipboard>
#include <KWordWrap>
#include <klocalimagecacheimpl.h>
@@ -0,0 +1,27 @@
<?xml version="1.0"?>
<typesystem package="KGuiAddons">
<!--
SPDX-FileCopyrightText: 2024 Manuel Alcaraz Zambrano <manuelalcarazzam@gmail.com>
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
-->
<load-typesystem name="typesystem_gui.xml" generate="no"/>
<namespace-type name="KColorMimeData" />
<object-type name="KColorSchemeWatcher">
<enum-type name="ColorPreference" />
</object-type>
<namespace-type name="KColorUtils" />
<object-type name="KCountryFlagEmojiIconEngine" />
<object-type name="KCursorSaver" />
<object-type name="KDateValidator" />
<namespace-type name="KFontUtils">
<enum-type name="AdaptFontSizeOption" flags="AdaptFontSizeOptions" />
</namespace-type>
<namespace-type name="KIconUtils" />
<namespace-type name="KJobWindows" />
<object-type name="KKeySequenceRecorder" />
<object-type name="KModifierKeyInfo" />
<object-type name="KSystemClipboard" />
<object-type name="KWordWrap" />
</typesystem>
@@ -0,0 +1,248 @@
configure_file(config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h)
add_library(KF6GuiAddons)
add_library(KF6::GuiAddons ALIAS KF6GuiAddons)
set_target_properties(KF6GuiAddons PROPERTIES
VERSION ${KGUIADDONS_VERSION}
SOVERSION ${KGUIADDONS_SOVERSION}
EXPORT_NAME GuiAddons
)
target_sources(KF6GuiAddons PRIVATE
colors/kcolorspaces.cpp
colors/kcolorutils.cpp
colors/kcolorcollection.cpp
colors/kcolormimedata.cpp
colors/kcolorschemewatcher.cpp
colors/kcolorschemewatcherbackend.cpp
colors/kcolorschemewatcher_qt.cpp
colors/kwindowinsetscontroller.cpp
text/kdatevalidator.cpp
text/kwordwrap.cpp
fonts/kfontutils.cpp
util/kiconutils.cpp
util/klocalimagecacheimpl.cpp
util/kmodifierkeyinfo.cpp
util/kmodifierkeyinfoprovider.cpp
util/kurlhandler_p.cpp
util/kcursorsaver.cpp
util/kcountryflagemojiiconengine.cpp
util/kjobwindows.cpp
recorder/keyboardgrabber.cpp
recorder/kkeysequencerecorder.cpp
systemclipboard/qtclipboard.cpp
systemclipboard/ksystemclipboard.cpp
colors/kcolorspaces_p.h
colors/kcolorutils.h
colors/kcolorcollection.h
colors/kcolormimedata.h
text/kdatevalidator.h
text/kwordwrap.h
fonts/kfontutils.h
util/kiconutils.h
util/klocalimagecacheimpl.h
util/kmodifierkeyinfo.h
util/kmodifierkeyinfoprovider_p.h
util/kurlhandler_p.h
util/kcursorsaver.h
util/kcountryflagemojiiconengine.h
util/kjobwindows.h
recorder/keyboardgrabber_p.h
recorder/kkeysequencerecorder.h
systemclipboard/qtclipboard_p.h
systemclipboard/ksystemclipboard.h
)
ecm_qt_declare_logging_category(KF6GuiAddons
HEADER kguiaddons_debug.h
IDENTIFIER KGUIADDONS_LOG
CATEGORY_NAME kf.guiaddons
DESCRIPTION "KGuiAddons"
EXPORT KGUIADDONS
)
if(WIN32)
target_sources(KF6GuiAddons PRIVATE colors/kcolorschemewatcher_win.cpp)
target_link_libraries(KF6GuiAddons PRIVATE advapi32)
endif()
if(APPLE)
find_library(APPKIT_LIBRARY AppKit)
target_sources(KF6GuiAddons PRIVATE colors/kcolorschemewatcher_mac.mm)
target_link_libraries(KF6GuiAddons PRIVATE ${APPKIT_LIBRARY})
endif()
if(WITH_DBUS)
target_sources(KF6GuiAddons PRIVATE colors/kcolorschemewatcher_xdg.cpp)
target_link_libraries(KF6GuiAddons PRIVATE Qt6::DBus)
endif()
if(WITH_WAYLAND)
if (Qt6_VERSION VERSION_GREATER_EQUAL "6.8.0")
set(private_code_option "PRIVATE_CODE")
endif()
qt_generate_wayland_protocol_client_sources(KF6GuiAddons
FILES
"${CMAKE_CURRENT_SOURCE_DIR}/recorder/keyboard-shortcuts-inhibit-unstable-v1.xml"
"${CMAKE_CURRENT_SOURCE_DIR}/systemclipboard/wlr-data-control-unstable-v1.xml"
"${PLASMA_WAYLAND_PROTOCOLS_DIR}/keystate.xml"
"${Wayland_DATADIR}/wayland.xml"
${private_code_option}
)
target_sources(KF6GuiAddons PRIVATE
recorder/waylandinhibition.cpp
systemclipboard/waylandclipboard.cpp
util/kmodifierkeyinfoprovider_wayland.cpp
recorder/waylandinhibition_p.h
systemclipboard/waylandclipboard_p.h
util/kmodifierkeyinfoprovider_wayland.h
)
target_compile_definitions(KF6GuiAddons PRIVATE WITH_WAYLAND)
target_link_libraries(KF6GuiAddons PRIVATE Qt6::GuiPrivate Qt6::WaylandClient Wayland::Client)
endif()
if(WITH_X11)
target_sources(KF6GuiAddons PRIVATE util/kmodifierkeyinfoprovider_xcb.cpp util/kmodifierkeyinfoprovider_xcb.h)
target_link_libraries(KF6GuiAddons PRIVATE X11::Xkb XCB::XCB)
endif()
if(ANDROID)
add_subdirectory(android)
endif()
ecm_generate_export_header(KF6GuiAddons
BASE_NAME KGuiAddons
GROUP_BASE_NAME KF
VERSION ${KF_VERSION}
USE_VERSION_HEADER
DEPRECATED_BASE_VERSION 0
DEPRECATION_VERSIONS 6.3
)
set(kguiaddons_INCLUDES
${CMAKE_CURRENT_SOURCE_DIR}/colors
${CMAKE_CURRENT_SOURCE_DIR}/fonts
${CMAKE_CURRENT_SOURCE_DIR}/text
${CMAKE_CURRENT_SOURCE_DIR}/util
${CMAKE_CURRENT_SOURCE_DIR}/recorder
${CMAKE_CURRENT_SOURCE_DIR}/systemclipboard
)
target_include_directories(KF6GuiAddons PUBLIC "$<BUILD_INTERFACE:${kguiaddons_INCLUDES}>")
target_include_directories(KF6GuiAddons INTERFACE "$<INSTALL_INTERFACE:${KDE_INSTALL_INCLUDEDIR_KF}/KGuiAddons>" )
target_compile_definitions(KF6GuiAddons INTERFACE "$<INSTALL_INTERFACE:KGUIADDONS_LIB>")
target_link_libraries(KF6GuiAddons PUBLIC Qt6::Gui)
qt_extract_metatypes(KF6GuiAddons)
ecm_generate_headers(KGuiAddons_HEADERS
HEADER_NAMES
KColorUtils
KColorCollection
KColorMimeData
KColorSchemeWatcher
KWindowInsetsController
RELATIVE colors
REQUIRED_HEADERS KGuiAddons_HEADERS
)
ecm_generate_headers(KGuiAddons_HEADERS
HEADER_NAMES
KDateValidator
KWordWrap
RELATIVE text
REQUIRED_HEADERS KGuiAddons_HEADERS
)
ecm_generate_headers(KGuiAddons_HEADERS
HEADER_NAMES
KFontUtils
RELATIVE fonts
REQUIRED_HEADERS KGuiAddons_HEADERS
)
ecm_generate_headers(KGuiAddons_HEADERS
HEADER_NAMES
KIconUtils
KImageCache
KModifierKeyInfo
KCursorSaver
KCountryFlagEmojiIconEngine
KJobWindows
RELATIVE util
REQUIRED_HEADERS KGuiAddons_HEADERS
)
ecm_generate_headers(KGuiAddons_HEADERS
HEADER_NAMES
KKeySequenceRecorder
RELATIVE recorder
REQUIRED_HEADERS KGuiAddons_HEADERS
)
#add_subdirectory(systemclipboard)
ecm_generate_headers(KGuiAddons_HEADERS
HEADER_NAMES
KSystemClipboard
RELATIVE systemclipboard
REQUIRED_HEADERS KGuiAddons_HEADERS
)
install(TARGETS KF6GuiAddons EXPORT KF6GuiAddonsTargets ${KF_INSTALL_TARGETS_DEFAULT_ARGS})
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/kguiaddons_export.h
util/kmodifierkeyinfoprovider_p.h
util/klocalimagecacheimpl.h # implementation detail, no forwarding header
${KGuiAddons_HEADERS}
DESTINATION ${KDE_INSTALL_INCLUDEDIR_KF}/KGuiAddons COMPONENT Devel
)
if(BUILD_QCH)
ecm_add_qch(
KF6GuiAddons_QCH
NAME KGuiAddons
BASE_NAME KF6GuiAddons
VERSION ${KF_VERSION}
ORG_DOMAIN org.kde
SOURCES # using only public headers, to cover only public API
${KGuiAddons_HEADERS}
MD_MAINPAGE "${CMAKE_SOURCE_DIR}/README.md"
LINK_QCHS
Qt6Gui_QCH
INCLUDE_DIRS
${CMAKE_CURRENT_BINARY_DIR}
${kguiaddons_INCLUDES}
BLANK_MACROS
KGUIADDONS_EXPORT
TAGFILE_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR}
QCH_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR}
COMPONENT Devel
)
endif()
ecm_qt_install_logging_categories(
EXPORT KGUIADDONS
FILE kguiaddons.categories
DESTINATION "${KDE_INSTALL_LOGGINGCATEGORIESDIR}"
)
if(BUILD_TESTING)
add_executable(pasteclient systemclipboard/tests/paste.cpp)
target_link_libraries(pasteclient
KF6GuiAddons
)
endif()
if (NOT ANDROID AND BUILD_GEO_SCHEME_HANDLER)
add_subdirectory(geo-scheme-handler)
endif()
if (TARGET Qt6::Qml)
add_subdirectory(qml)
endif()
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
SPDX-FileCopyrightText: 2024 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: BSD-2-Clause
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.kde.guiaddons">
</manifest>
@@ -0,0 +1,11 @@
# SPDX-FileCopyrightText: 2024 Volker Krause <vkrause@kde.org>
# SPDX-License-Identifier: BSD-2-Clause
gradle_add_aar(kguiaddons_aar BUILDFILE ${CMAKE_CURRENT_SOURCE_DIR}/build.gradle NAME KF6GuiAddons)
gradle_install_aar(kguiaddons_aar DESTINATION jar)
install(
FILES KF6GuiAddons-android-dependencies.xml
DESTINATION ${KDE_INSTALL_LIBDIR}
RENAME KF6GuiAddons_${CMAKE_ANDROID_ARCH_ABI}-android-dependencies.xml
)
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
SPDX-FileCopyrightText: 2024 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: BSD-2-Clause
-->
<rules>
<dependencies>
<lib name="KF6GuiAddons">
<depends>
<jar bundling="1" file="jar/KF6GuiAddons.aar"/>
</depends>
</lib>
</dependencies>
</rules>
@@ -0,0 +1,44 @@
/*
SPDX-FileCopyrightText: 2024 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: BSD-2-Clause
*/
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:@Gradle_ANDROID_GRADLE_PLUGIN_VERSION@'
}
}
repositories {
google()
jcenter()
}
apply plugin: 'com.android.library'
android {
compileSdkVersion @ANDROID_SDK_COMPILE_API@
buildToolsVersion '@ANDROID_SDK_BUILD_TOOLS_REVISION@'
sourceSets {
main {
manifest.srcFile '@CMAKE_CURRENT_SOURCE_DIR@/AndroidManifest.xml'
java.srcDirs = ['@CMAKE_CURRENT_SOURCE_DIR@/org']
}
}
lintOptions {
abortOnError false
}
defaultConfig {
minSdkVersion @ANDROID_API_LEVEL@
targetSdkVersion @ANDROID_SDK_COMPILE_API@
namespace "org.kde.guiaddons"
}
}
@@ -0,0 +1,76 @@
/*
SPDX-FileCopyrightText: 2024 Mathis Brüchert <mbb@kaidan.im>
SPDX-FileCopyrightText: 2024 Carl Schwan <carl@carlschwan.eu>
SPDX-FileCopyrightText: 2024 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
package org.kde.guiaddons;
import android.app.Activity;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowInsetsController;
public class KWindowInsetsController
{
public static void setStatusBarBackground(android.app.Activity activity, int color)
{
Window window = activity.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(color);
if (Build.VERSION.SDK_INT >= 30) {
if (isDark(color)) {
window.getInsetsController().setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);
} else {
window.getInsetsController().setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);
}
} else {
int visibility = window.getDecorView().getSystemUiVisibility();
if (isDark(color)) {
visibility &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
} else {
visibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
}
window.getDecorView().setSystemUiVisibility(visibility);
}
}
public static void setNavigationBarBackground(android.app.Activity activity, int color)
{
Window window = activity.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setNavigationBarColor(color);
if (Build.VERSION.SDK_INT >= 30) {
if (isDark(color)) {
window.getInsetsController().setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);
} else {
window.getInsetsController().setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS, WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);
}
} else {
int visibility = window.getDecorView().getSystemUiVisibility();
if (isDark(color)) {
visibility &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
} else {
visibility |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
}
window.getDecorView().setSystemUiVisibility(visibility);
}
}
private static double luma(int color)
{
return (0.299 * (color >> 24) + 0.587 * ((color >> 16) & 0xff) + 0.114 * ((color >> 8) & 0xff)) / 255.0;
}
private static boolean isDark(int color)
{
return luma(color) <= 0.5;
}
}
@@ -0,0 +1,245 @@
/* This file is part of the KDE libraries
SPDX-FileCopyrightText: 1999 Waldo Bastian <bastian@kde.org>
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/
// KDE color collection
#include "kcolorcollection.h"
#if KGUIADDONS_BUILD_DEPRECATED_SINCE(6, 3)
#include <QDir>
#include <QFile>
#include <QSaveFile>
#include <QSharedData>
#include <QStandardPaths>
#include <QTextStream>
// BEGIN KColorCollectionPrivate
class KColorCollectionPrivate : public QSharedData
{
public:
KColorCollectionPrivate(const QString &);
KColorCollectionPrivate(const KColorCollectionPrivate &) = default;
~KColorCollectionPrivate()
{
}
struct ColorNode {
ColorNode(const QColor &c, const QString &n)
: color(c)
, name(n)
{
}
QColor color;
QString name;
};
QList<ColorNode> colorList;
QString name;
QString desc;
KColorCollection::Editable editable;
};
KColorCollectionPrivate::KColorCollectionPrivate(const QString &_name)
: name(_name)
{
if (name.isEmpty()) {
return;
}
QString filename = QStandardPaths::locate(QStandardPaths::GenericConfigLocation, QLatin1String("colors/") + name);
if (filename.isEmpty()) {
return;
}
QFile paletteFile(filename);
if (!paletteFile.exists()) {
return;
}
if (!paletteFile.open(QIODevice::ReadOnly)) {
return;
}
// Read first line
// Expected "GIMP Palette"
QString line = QString::fromLocal8Bit(paletteFile.readLine());
if (line.contains(QLatin1String(" Palette"))) {
return;
}
while (!paletteFile.atEnd()) {
line = QString::fromLocal8Bit(paletteFile.readLine());
if (line[0] == QLatin1Char('#')) {
// This is a comment line
line.remove(0, 1); // Strip '#'
line = line.trimmed(); // Strip remaining white space..
if (!line.isEmpty()) {
desc += line + QLatin1Char('\n'); // Add comment to description
}
} else {
// This is a color line, hopefully
line = line.trimmed();
if (line.isEmpty()) {
continue;
}
int r;
int g;
int b;
int pos = 0;
if (sscanf(line.toLatin1().constData(), "%d %d %d%n", &r, &g, &b, &pos) >= 3) {
r = qBound(0, r, 255);
g = qBound(0, g, 255);
b = qBound(0, b, 255);
QString name = line.mid(pos).trimmed();
colorList.append(ColorNode(QColor(r, g, b), name));
}
}
}
}
// END KColorCollectionPrivate
QStringList KColorCollection::installedCollections()
{
const QStringList paletteDirs = QStandardPaths::locateAll(QStandardPaths::GenericConfigLocation, QStringLiteral("colors"), QStandardPaths::LocateDirectory);
QStringList paletteList;
for (const QString &dir : paletteDirs) {
paletteList += QDir(dir).entryList(QDir::Files | QDir::NoDotAndDotDot);
}
paletteList.removeDuplicates();
return paletteList;
}
KColorCollection::KColorCollection(const QString &name)
: d(new KColorCollectionPrivate(name))
{
}
KColorCollection::KColorCollection(const KColorCollection &p) = default;
// Need auto-save?
KColorCollection::~KColorCollection() = default;
bool KColorCollection::save()
{
QString filename = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QLatin1String("/colors/") + d->name;
QSaveFile sf(filename);
if (!sf.open(QIODevice::WriteOnly)) {
return false;
}
QTextStream str(&sf);
QString description = d->desc.trimmed();
description = QLatin1Char('#') + description.split(QLatin1Char('\n'), Qt::KeepEmptyParts).join(QLatin1String("\n#"));
str << QLatin1String("KDE RGB Palette\n");
str << description << QLatin1Char('\n');
for (const KColorCollectionPrivate::ColorNode &node : std::as_const(d->colorList)) {
int r;
int g;
int b;
node.color.getRgb(&r, &g, &b);
str << r << " " << g << " " << b << " " << node.name << "\n";
}
return sf.commit();
}
QString KColorCollection::description() const
{
return d->desc;
}
void KColorCollection::setDescription(const QString &desc)
{
d->desc = desc;
}
QString KColorCollection::name() const
{
return d->name;
}
void KColorCollection::setName(const QString &name)
{
d->name = name;
}
KColorCollection::Editable KColorCollection::editable() const
{
return d->editable;
}
void KColorCollection::setEditable(Editable editable)
{
d->editable = editable;
}
int KColorCollection::count() const
{
return d->colorList.count();
}
KColorCollection &KColorCollection::operator=(const KColorCollection &p) = default;
QColor KColorCollection::color(int index) const
{
if ((index < 0) || (index >= count())) {
return QColor();
}
return d->colorList[index].color;
}
int KColorCollection::findColor(const QColor &color) const
{
for (int i = 0; i < d->colorList.size(); ++i) {
if (d->colorList[i].color == color) {
return i;
}
}
return -1;
}
QString KColorCollection::name(int index) const
{
if ((index < 0) || (index >= count())) {
return QString();
}
return d->colorList[index].name;
}
QString KColorCollection::name(const QColor &color) const
{
return name(findColor(color));
}
int KColorCollection::addColor(const QColor &newColor, const QString &newColorName)
{
d->colorList.append(KColorCollectionPrivate::ColorNode(newColor, newColorName));
return count() - 1;
}
int KColorCollection::changeColor(int index, const QColor &newColor, const QString &newColorName)
{
if ((index < 0) || (index >= count())) {
return -1;
}
KColorCollectionPrivate::ColorNode &node = d->colorList[index];
node.color = newColor;
node.name = newColorName;
return index;
}
int KColorCollection::changeColor(const QColor &oldColor, const QColor &newColor, const QString &newColorName)
{
return changeColor(findColor(oldColor), newColor, newColorName);
}
#endif
@@ -0,0 +1,195 @@
/* This file is part of the KDE libraries
SPDX-FileCopyrightText: 1999 Waldo Bastian <bastian@kde.org>
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/
// KDE color collection.
#ifndef KDELIBS_KCOLORCOLLECTION_H
#define KDELIBS_KCOLORCOLLECTION_H
#include <kguiaddons_export.h>
#include <QColor>
#include <QSharedDataPointer>
#include <QString>
#include <QStringList>
#if KGUIADDONS_ENABLE_DEPRECATED_SINCE(6, 3)
/**
* @class KColorCollection kcolorcollection.h KColorCollection
*
* Class for handling color collections ("palettes").
*
* This class makes it easy to handle color collections, sometimes referred to
* as "palettes". This class can read and write collections from and to a file.
*
* This class uses the "GIMP" palette file format.
*
* @author Waldo Bastian (bastian@kde.org)
*
* @deprecated since 6.3, unused and backing data no longer available
*/
class KGUIADDONS_EXPORT KGUIADDONS_DEPRECATED_VERSION(6, 3, "unused") KColorCollection
{
public:
/**
* Query which KDE color collections are installed.
*
* @return A list with installed color collection names.
*/
static QStringList installedCollections();
/**
* KColorCollection constructor. Creates a KColorCollection from a file
* the filename is derived from the name.
* @param name The name of collection as returned by installedCollections()
*/
explicit KColorCollection(const QString &name = QString());
/**
* KColorCollection copy constructor.
*/
KColorCollection(const KColorCollection &);
/**
* KColorCollection destructor.
*/
~KColorCollection();
/**
* KColorCollection assignment operator
*/
KColorCollection &operator=(const KColorCollection &);
/**
* Save the collection
*
* @return 'true' if successful
*/
bool save();
/**
* Get the description of the collection.
* @return the description of the collection.
*/
QString description() const;
/**
* Set the description of the collection.
* @param desc the new description
*/
void setDescription(const QString &desc);
/**
* Get the name of the collection.
* @return the name of the collection
*/
QString name() const;
/**
* Set the name of the collection.
* @param name the name of the collection
*/
void setName(const QString &name);
/**
* Used to specify whether a collection may be edited.
* @see editable()
* @see setEditable()
*/
enum Editable {
Yes, ///< Collection may be edited
No, ///< Collection may not be edited
Ask, ///< Ask user before editing
};
/**
* Returns whether the collection may be edited.
* @return the state of the collection
*/
Editable editable() const;
/**
* Change whether the collection may be edited.
* @param editable the state of the collection
*/
void setEditable(Editable editable);
/**
* Return the number of colors in the collection.
* @return the number of colors
*/
int count() const;
/**
* Find color by index.
* @param index the index of the desired color
* @return The @p index -th color of the collection, null if not found.
*/
QColor color(int index) const;
/**
* Find index by @p color.
* @param color the color to find
* @return The index of the color in the collection or -1 if the
* color is not found.
*/
int findColor(const QColor &color) const;
/**
* Find color name by @p index.
* @param index the index of the color
* @return The name of the @p index -th color.
* Note that not all collections have named the colors. Null is
* returned if the color does not exist or has no name.
*/
QString name(int index) const;
/**
* Find color name by @p color.
* @return The name of color according to this collection.
* Note that not all collections have named the colors.
* Note also that each collection can give the same color
* a different name.
*/
QString name(const QColor &color) const;
/**
* Add a color.
* @param newColor The color to add.
* @param newColorName The name of the color, null to remove
* the name.
* @return The index of the added color.
*/
int addColor(const QColor &newColor, const QString &newColorName = QString());
/**
* Change a color.
* @param index Index of the color to change
* @param newColor The new color.
* @param newColorName The new color name, null to remove
* the name.
* @return The index of the new color or -1 if the color couldn't
* be changed.
*/
int changeColor(int index, const QColor &newColor, const QString &newColorName = QString());
/**
* Change a color.
* @param oldColor The original color
* @param newColor The new color.
* @param newColorName The new color name, null to remove
* the name.
* @return The index of the new color or -1 if the color couldn't
* be changed.
*/
int changeColor(const QColor &oldColor, const QColor &newColor, const QString &newColorName = QString());
private:
QSharedDataPointer<class KColorCollectionPrivate> d;
};
#endif
#endif // KDELIBS_KCOLORCOLLECTION_H
@@ -0,0 +1,61 @@
/* This file is part of the KDE libraries
SPDX-FileCopyrightText: 1999 Steffen Hansen <hansen@kde.org>
SPDX-FileCopyrightText: 2005 Joseph Wenninger <jowenn@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kcolormimedata.h"
#include <QColor>
#include <QDrag>
#include <QMimeData>
#include <QPainter>
void KColorMimeData::populateMimeData(QMimeData *mimeData, const QColor &color)
{
mimeData->setColorData(color);
mimeData->setText(color.name());
}
bool KColorMimeData::canDecode(const QMimeData *mimeData)
{
if (mimeData->hasColor()) {
return true;
}
if (mimeData->hasText()) {
const QString colorName = mimeData->text();
if ((colorName.length() >= 4) && (colorName[0] == QLatin1Char('#'))) {
return true;
}
}
return false;
}
QColor KColorMimeData::fromMimeData(const QMimeData *mimeData)
{
if (mimeData->hasColor()) {
return mimeData->colorData().value<QColor>();
}
if (canDecode(mimeData)) {
return QColor(mimeData->text());
}
return QColor();
}
QDrag *KColorMimeData::createDrag(const QColor &color, QObject *dragsource)
{
QDrag *drag = new QDrag(dragsource);
QMimeData *mime = new QMimeData;
populateMimeData(mime, color);
drag->setMimeData(mime);
QPixmap colorpix(25, 20);
colorpix.fill(color);
QPainter p(&colorpix);
p.setPen(Qt::black);
p.drawRect(0, 0, 24, 19);
p.end();
drag->setPixmap(colorpix);
drag->setHotSpot(QPoint(-5, -7));
return drag;
}
@@ -0,0 +1,55 @@
/* This file is part of the KDE libraries
SPDX-FileCopyrightText: 1999 Steffen Hansen <hansen@kde.org>
SPDX-FileCopyrightText: 2005 Joseph Wenninger <jowenn@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef _KCOLORMIMEDATA_H
#define _KCOLORMIMEDATA_H
#include <kguiaddons_export.h>
class QColor;
class QDrag;
class QMimeData;
class QObject;
/**
* Drag-and-drop and clipboard mimedata manipulation for QColor objects. The according MIME type
* is set to application/x-color.
*
* See the Qt drag'n'drop documentation.
*/
namespace KColorMimeData
{
/**
* Sets the color and text representation fields for the specified color in the mimedata object:
* application/x-color and text/plain types are set
*/
KGUIADDONS_EXPORT void populateMimeData(QMimeData *mimeData, const QColor &color);
/**
* Returns true if the MIME data @p mimeData contains a color object.
* First checks for application/x-color and if that fails, for a text/plain entry, which
* represents a color in the format \#hexnumbers
*/
KGUIADDONS_EXPORT bool canDecode(const QMimeData *mimeData);
/**
* Decodes the MIME data @p mimeData and returns the resulting color.
* First tries application/x-color and if that fails, a text/plain entry, which
* represents a color in the format \#hexnumbers. If this fails too,
* an invalid QColor object is returned, use QColor::isValid() to test it.
*/
KGUIADDONS_EXPORT QColor fromMimeData(const QMimeData *mimeData);
/**
* Creates a color drag object. Either you have to start this drag or delete it
* The drag object's mime data has the application/x-color and text/plain type set and a pixmap
* filled with the specified color, which is going to be displayed next to the mouse cursor
*/
KGUIADDONS_EXPORT QDrag *createDrag(const QColor &color, QObject *dragsource);
}
#endif // _KCOLORMIMEDATA_H
@@ -0,0 +1,65 @@
/*
* SPDX-FileCopyrightText: 2021 Nicolas Fella <nicolas.fella@gmx.de>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kcolorschemewatcher.h"
#include "kcolorschemewatcher_qt.h"
#include "kcolorschemewatcherbackend.h"
#ifdef Q_OS_WINDOWS
#include "kcolorschemewatcher_win.h"
#endif
#ifdef Q_OS_MACOS
#include "kcolorschemewatcher_mac.h"
#endif
#ifdef QT_DBUS_LIB
#include "kcolorschemewatcher_xdg.h"
#endif
class KColorSchemeWatcherPrivate
{
public:
std::unique_ptr<KColorSchemeWatcherBackend> backend;
KColorSchemeWatcherPrivate()
{
#ifdef Q_OS_WINDOWS
backend = std::make_unique<KColorSchemeWatcherWin>();
#elif defined(Q_OS_MACOS)
backend = std::make_unique<KColorSchemeWatcherMac>();
#elif defined(QT_DBUS_LIB)
backend = std::make_unique<KColorSchemeWatcherXDG>();
#else
backend = std::make_unique<KColorSchemeWatcherQt>();
#endif
}
};
KColorSchemeWatcher::KColorSchemeWatcher(QObject *parent)
: QObject(parent)
, d(new KColorSchemeWatcherPrivate)
{
if (d->backend) {
connect(d->backend.get(), &KColorSchemeWatcherBackend::systemPreferenceChanged, this, &KColorSchemeWatcher::systemPreferenceChanged);
}
}
KColorSchemeWatcher::~KColorSchemeWatcher()
{
}
KColorSchemeWatcher::ColorPreference KColorSchemeWatcher::systemPreference() const
{
if (d->backend) {
return d->backend->systemPreference();
}
return NoPreference;
}
#include "moc_kcolorschemewatcher.cpp"
@@ -0,0 +1,51 @@
/*
* SPDX-FileCopyrightText: 2021 Nicolas Fella <nicolas.fella@gmx.de>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KCOLORSCHEMEWATCHER_H
#define KCOLORSCHEMEWATCHER_H
#include "kguiaddons_export.h"
#include <QObject>
#include <memory>
class KColorSchemeWatcherPrivate;
/**
* Information about system-wide color preferences.
* @since 5.100
*/
class KGUIADDONS_EXPORT KColorSchemeWatcher : public QObject
{
Q_OBJECT
public:
enum ColorPreference {
NoPreference = 0, /** No preference available */
PreferDark, /** The user prefers a dark color scheme */
PreferLight, /** The user prefers a light color scheme */
};
Q_ENUM(ColorPreference)
KColorSchemeWatcher(QObject *parent = nullptr);
~KColorSchemeWatcher() override;
/**
* The system-wide color preference.
*/
ColorPreference systemPreference() const;
Q_SIGNALS:
/**
* Emitted when systemPreference changes.
*/
void systemPreferenceChanged();
private:
std::unique_ptr<KColorSchemeWatcherPrivate> const d;
};
#endif
@@ -0,0 +1,29 @@
/*
* SPDX-FileCopyrightText: 2022 Jyrki Gadinger <nilsding@nilsding.org>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KCOLORSCHEMEWATCHER_MAC_H
#define KCOLORSCHEMEWATCHER_MAC_H
#include "kcolorschemewatcherbackend.h"
class KColorSchemeWatcherMac : public KColorSchemeWatcherBackend
{
Q_OBJECT
public:
explicit KColorSchemeWatcherMac();
~KColorSchemeWatcherMac();
KColorSchemeWatcher::ColorPreference systemPreference() const override;
private:
// not ideal, in obj-c++ this would be an `id`, but since this header is
// included from pure C++ files the compiler will not know what to do with
// an `id`
void *m_observer;
};
#endif
@@ -0,0 +1,51 @@
/*
* SPDX-FileCopyrightText: 2022 Jyrki Gadinger <nilsding@nilsding.org>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kcolorschemewatcher_mac.h"
#import <AppKit/AppKit.h>
#include <QTimer>
KColorSchemeWatcherMac::KColorSchemeWatcherMac()
{
// subscribe to the distributed notification centre
id notificationCenter = NSDistributedNotificationCenter.defaultCenter;
m_observer = [notificationCenter addObserverForName:@"AppleInterfaceThemeChangedNotification"
object:nil
queue:nil
usingBlock:^(NSNotification *) {
// "fun" workaround to not emit the signal immediately after receiving the notification.
// for some reason NSAppearance.currentDrawingAppearance is still set to the old value here, after a short
// delay it is updated correctly
QTimer::singleShot(0, [this]() {
Q_EMIT systemPreferenceChanged();
});
}];
}
KColorSchemeWatcherMac::~KColorSchemeWatcherMac()
{
[NSDistributedNotificationCenter.defaultCenter removeObserver:static_cast<id>(m_observer)];
}
KColorSchemeWatcher::ColorPreference KColorSchemeWatcherMac::systemPreference() const
{
NSAppearance *appearance = nullptr;
if (@available(macOS 11.0, *)) {
appearance = NSAppearance.currentDrawingAppearance;
} else if (@available(macOS 10.14, *)) {
appearance = NSAppearance.currentAppearance;
} else {
// macOS < 10.14 (Mojave) does not support a light/dark mode switch, always prefer light mode
return KColorSchemeWatcher::PreferLight;
}
return appearance.name == NSAppearanceNameDarkAqua ? KColorSchemeWatcher::PreferDark : KColorSchemeWatcher::PreferLight;
}
#include "moc_kcolorschemewatcher_mac.cpp"
@@ -0,0 +1,29 @@
/*
* SPDX-FileCopyrightText: 2023 Volker Krause <vkrause@kde.org>
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kcolorschemewatcher_qt.h"
#include <QGuiApplication>
#include <QStyleHints>
KColorSchemeWatcherQt::KColorSchemeWatcherQt()
{
connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged, this, &KColorSchemeWatcherBackend::systemPreferenceChanged);
}
KColorSchemeWatcher::ColorPreference KColorSchemeWatcherQt::systemPreference() const
{
switch (QGuiApplication::styleHints()->colorScheme()) {
case Qt::ColorScheme::Unknown:
return KColorSchemeWatcher::NoPreference;
case Qt::ColorScheme::Light:
return KColorSchemeWatcher::PreferLight;
case Qt::ColorScheme::Dark:
return KColorSchemeWatcher::PreferDark;
}
return KColorSchemeWatcher::NoPreference;
}
#include "moc_kcolorschemewatcher_qt.cpp"
@@ -0,0 +1,19 @@
/*
* SPDX-FileCopyrightText: 2023 Volker Krause <vkrause@kde.org>
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KCOLORSCHEMEWATCHER_QT_H
#define KCOLORSCHEMEWATCHER_QT_H
#include "kcolorschemewatcherbackend.h"
class KColorSchemeWatcherQt : public KColorSchemeWatcherBackend
{
Q_OBJECT
public:
KColorSchemeWatcherQt();
KColorSchemeWatcher::ColorPreference systemPreference() const override;
};
#endif
@@ -0,0 +1,47 @@
/*
* SPDX-FileCopyrightText: 2020 Piyush Aggarwal <piyushaggarwal002@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kcolorschemewatcher_win.h"
#include <windows.h>
#include <QAbstractEventDispatcher>
#include <QDebug>
KColorSchemeWatcherWin::KColorSchemeWatcherWin()
{
QAbstractEventDispatcher::instance()->installNativeEventFilter(this);
m_preferDarkMode = !(m_settings.value(QStringLiteral("AppsUseLightTheme"), true).value<bool>());
}
bool KColorSchemeWatcherWin::nativeEventFilter(const QByteArray &eventType, void *message, qintptr *)
{
MSG *msg = static_cast<MSG *>(message);
switch (msg->message) {
case WM_SETTINGCHANGE: {
m_settings.sync();
const bool preferDarkModeNow = !(m_settings.value(QStringLiteral("AppsUseLightTheme"), true).value<bool>());
if (m_preferDarkMode != preferDarkModeNow) {
m_preferDarkMode = preferDarkModeNow;
Q_EMIT systemPreferenceChanged();
}
break;
}
default: {
}
}
return false;
}
KColorSchemeWatcher::ColorPreference KColorSchemeWatcherWin::systemPreference() const
{
return m_preferDarkMode ? KColorSchemeWatcher::PreferDark : KColorSchemeWatcher::PreferLight;
}
#include "moc_kcolorschemewatcher_win.cpp"
@@ -0,0 +1,29 @@
/*
* SPDX-FileCopyrightText: 2020 Piyush Aggarwal <piyushaggarwal002@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KCOLORSCHEMEWATCHER_WIN_H
#define KCOLORSCHEMEWATCHER_WIN_H
#include <QAbstractNativeEventFilter>
#include <QSettings>
#include "kcolorschemewatcherbackend.h"
class KColorSchemeWatcherWin : public KColorSchemeWatcherBackend, public QAbstractNativeEventFilter
{
Q_OBJECT
public:
KColorSchemeWatcherWin();
KColorSchemeWatcher::ColorPreference systemPreference() const override;
bool nativeEventFilter(const QByteArray &eventType, void *message, qintptr *) override;
private:
QSettings m_settings{QStringLiteral("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"), QSettings::NativeFormat};
bool m_preferDarkMode = false;
};
#endif
@@ -0,0 +1,71 @@
/*
* SPDX-FileCopyrightText: 2021 Nicolas Fella <nicolas.fella@gmx.de>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kcolorschemewatcher_xdg.h"
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusReply>
#include <QDBusVariant>
#include <QDebug>
KColorSchemeWatcherXDG::KColorSchemeWatcherXDG()
: KColorSchemeWatcherBackend()
{
QDBusConnection::sessionBus().connect(QStringLiteral("org.freedesktop.portal.Desktop"),
QStringLiteral("/org/freedesktop/portal/desktop"),
QStringLiteral("org.freedesktop.portal.Settings"),
QStringLiteral("SettingChanged"),
this,
SLOT(slotSettingChanged(QString, QString, QDBusVariant)));
QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.portal.Desktop"),
QStringLiteral("/org/freedesktop/portal/desktop"),
QStringLiteral("org.freedesktop.portal.Settings"),
QStringLiteral("Read"));
m.setArguments({QStringLiteral("org.freedesktop.appearance"), QStringLiteral("color-scheme")});
QDBusReply<QDBusVariant> reply = QDBusConnection::sessionBus().call(m);
if (reply.isValid()) {
const uint result = reply.value().variant().value<QDBusVariant>().variant().toUInt();
m_preference = fdoToInternal(result);
}
}
KColorSchemeWatcher::ColorPreference KColorSchemeWatcherXDG::systemPreference() const
{
return m_preference;
}
void KColorSchemeWatcherXDG::slotSettingChanged(QString nameSpace, QString key, QDBusVariant value)
{
if (nameSpace == QLatin1String("org.freedesktop.appearance") && key == QLatin1String("color-scheme")) {
const uint result = value.variant().toUInt();
auto newValue = fdoToInternal(result);
if (m_preference != newValue) {
m_preference = fdoToInternal(result);
Q_EMIT systemPreferenceChanged();
}
}
}
KColorSchemeWatcher::ColorPreference KColorSchemeWatcherXDG::fdoToInternal(uint value) const
{
if (value == 0) {
return KColorSchemeWatcher::NoPreference;
} else if (value == 1) {
return KColorSchemeWatcher::PreferDark;
} else if (value == 2) {
return KColorSchemeWatcher::PreferLight;
} else {
qWarning() << "Unhandled org.freedesktop.appearance color-scheme value" << value;
return KColorSchemeWatcher::NoPreference;
}
}
#include "moc_kcolorschemewatcher_xdg.cpp"
@@ -0,0 +1,29 @@
/*
* SPDX-FileCopyrightText: 2021 Nicolas Fella <nicolas.fella@gmx.de>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KCOLORSCHEMEWATCHER_XDG_H
#define KCOLORSCHEMEWATCHER_XDG_H
#include "kcolorschemewatcherbackend.h"
#include <QDBusVariant>
class KColorSchemeWatcherXDG : public KColorSchemeWatcherBackend
{
Q_OBJECT
public:
KColorSchemeWatcherXDG();
KColorSchemeWatcher::ColorPreference systemPreference() const override;
private Q_SLOTS:
void slotSettingChanged(QString, QString, QDBusVariant);
private:
KColorSchemeWatcher::ColorPreference fdoToInternal(uint value) const;
KColorSchemeWatcher::ColorPreference m_preference = KColorSchemeWatcher::NoPreference;
};
#endif
@@ -0,0 +1,9 @@
/*
* SPDX-FileCopyrightText: 2021 Nicolas Fella <nicolas.fella@gmx.de>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kcolorschemewatcherbackend.h"
#include "moc_kcolorschemewatcherbackend.cpp"
@@ -0,0 +1,24 @@
/*
* SPDX-FileCopyrightText: 2021 Nicolas Fella <nicolas.fella@gmx.de>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KCOLORSCHEMEWATCHERBACKEND_H
#define KCOLORSCHEMEWATCHERBACKEND_H
#include <QObject>
#include "kcolorschemewatcher.h"
class KColorSchemeWatcherBackend : public QObject
{
Q_OBJECT
public:
virtual KColorSchemeWatcher::ColorPreference systemPreference() const = 0;
Q_SIGNALS:
void systemPreferenceChanged();
};
#endif
@@ -0,0 +1,163 @@
/* This file is part of the KDE project
SPDX-FileCopyrightText: 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
SPDX-FileCopyrightText: 2007 Olaf Schmidt <ojschmidt@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kcolorspaces_p.h"
#include "kguiaddons_colorhelpers_p.h"
#include <QColor>
#include <math.h>
using namespace KColorSpaces;
static inline qreal wrap(qreal a, qreal d = 1.0)
{
qreal r = fmod(a, d);
return (r < 0.0 ? d + r : (r > 0.0 ? r : 0.0));
}
///////////////////////////////////////////////////////////////////////////////
// HCY color space
#define HCY_REC 709 // use 709 for now
#if HCY_REC == 601
static const qreal yc[3] = {0.299, 0.587, 0.114};
#elif HCY_REC == 709
static const qreal yc[3] = {0.2126, 0.7152, 0.0722};
#else // use Qt values
static const qreal yc[3] = {0.34375, 0.5, 0.15625};
#endif
qreal KHCY::gamma(qreal n)
{
return pow(normalize(n), 2.2);
}
qreal KHCY::igamma(qreal n)
{
return pow(normalize(n), 1.0 / 2.2);
}
qreal KHCY::lumag(qreal r, qreal g, qreal b)
{
return r * yc[0] + g * yc[1] + b * yc[2];
}
KHCY::KHCY(qreal h_, qreal c_, qreal y_, qreal a_)
{
h = h_;
c = c_;
y = y_;
a = a_;
}
KHCY::KHCY(const QColor &color)
{
qreal r = gamma(color.redF());
qreal g = gamma(color.greenF());
qreal b = gamma(color.blueF());
a = color.alphaF();
// luma component
y = lumag(r, g, b);
// hue component
qreal p = qMax(qMax(r, g), b);
qreal n = qMin(qMin(r, g), b);
qreal d = 6.0 * (p - n);
if (n == p) {
h = 0.0;
} else if (r == p) {
h = ((g - b) / d);
} else if (g == p) {
h = ((b - r) / d) + (1.0 / 3.0);
} else {
h = ((r - g) / d) + (2.0 / 3.0);
}
// chroma component
if (r == g && g == b) {
c = 0.0;
} else {
c = qMax((y - n) / y, (p - y) / (1 - y));
}
}
QColor KHCY::qColor() const
{
// start with sane component values
qreal _h = wrap(h);
qreal _c = normalize(c);
qreal _y = normalize(y);
// calculate some needed variables
qreal _hs = _h * 6.0;
qreal th;
qreal tm;
if (_hs < 1.0) {
th = _hs;
tm = yc[0] + yc[1] * th;
} else if (_hs < 2.0) {
th = 2.0 - _hs;
tm = yc[1] + yc[0] * th;
} else if (_hs < 3.0) {
th = _hs - 2.0;
tm = yc[1] + yc[2] * th;
} else if (_hs < 4.0) {
th = 4.0 - _hs;
tm = yc[2] + yc[1] * th;
} else if (_hs < 5.0) {
th = _hs - 4.0;
tm = yc[2] + yc[0] * th;
} else {
th = 6.0 - _hs;
tm = yc[0] + yc[2] * th;
}
// calculate RGB channels in sorted order
qreal tn;
qreal to;
qreal tp;
if (tm >= _y) {
tp = _y + _y * _c * (1.0 - tm) / tm;
to = _y + _y * _c * (th - tm) / tm;
tn = _y - (_y * _c);
} else {
tp = _y + (1.0 - _y) * _c;
to = _y + (1.0 - _y) * _c * (th - tm) / (1.0 - tm);
tn = _y - (1.0 - _y) * _c * tm / (1.0 - tm);
}
// return RGB channels in appropriate order
if (_hs < 1.0) {
return QColor::fromRgbF(igamma(tp), igamma(to), igamma(tn), a);
} else if (_hs < 2.0) {
return QColor::fromRgbF(igamma(to), igamma(tp), igamma(tn), a);
} else if (_hs < 3.0) {
return QColor::fromRgbF(igamma(tn), igamma(tp), igamma(to), a);
} else if (_hs < 4.0) {
return QColor::fromRgbF(igamma(tn), igamma(to), igamma(tp), a);
} else if (_hs < 5.0) {
return QColor::fromRgbF(igamma(to), igamma(tn), igamma(tp), a);
} else {
return QColor::fromRgbF(igamma(tp), igamma(tn), igamma(to), a);
}
}
qreal KHCY::hue(const QColor &color)
{
return wrap(KHCY(color).h);
}
qreal KHCY::chroma(const QColor &color)
{
return KHCY(color).c;
}
qreal KHCY::luma(const QColor &color)
{
return lumag(gamma(color.redF()), gamma(color.greenF()), gamma(color.blueF()));
}
@@ -0,0 +1,39 @@
/* This file is part of the KDE project
SPDX-FileCopyrightText: 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
/*
* If you use KColorSpaces in your own KDE code, please drop me a line at
* mw_triad@users.sourceforge.net, as I would like to track if people find it
* useful. Thanks!
*/
#ifndef KCOLORSPACES_H
#define KCOLORSPACES_H
#include <QColor>
namespace KColorSpaces
{
class KHCY
{
public:
explicit KHCY(const QColor &);
explicit KHCY(qreal h_, qreal c_, qreal y_, qreal a_ = 1.0);
QColor qColor() const;
qreal h, c, y, a;
static qreal hue(const QColor &);
static qreal chroma(const QColor &);
static qreal luma(const QColor &);
private:
static qreal gamma(qreal);
static qreal igamma(qreal);
static qreal lumag(qreal, qreal, qreal);
};
}
#endif
@@ -0,0 +1,181 @@
/* This file is part of the KDE project
SPDX-FileCopyrightText: 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
SPDX-FileCopyrightText: 2007 Thomas Zander <zander@kde.org>
SPDX-FileCopyrightText: 2007 Zack Rusin <zack@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kcolorspaces_p.h"
#include "kguiaddons_colorhelpers_p.h"
#include <kcolorutils.h>
#include <QColor>
#include <QImage>
#include <QtNumeric> // qIsNaN
#include <math.h>
// BEGIN internal helper functions
static inline qreal mixQreal(qreal a, qreal b, qreal bias)
{
return a + (b - a) * bias;
}
// END internal helper functions
qreal KColorUtils::hue(const QColor &color)
{
return KColorSpaces::KHCY::hue(color);
}
qreal KColorUtils::chroma(const QColor &color)
{
return KColorSpaces::KHCY::chroma(color);
}
qreal KColorUtils::luma(const QColor &color)
{
return KColorSpaces::KHCY::luma(color);
}
void KColorUtils::getHcy(const QColor &color, qreal *h, qreal *c, qreal *y, qreal *a)
{
if (!c || !h || !y) {
return;
}
KColorSpaces::KHCY khcy(color);
*c = khcy.c;
*h = khcy.h + (khcy.h < 0.0 ? 1.0 : 0.0);
*y = khcy.y;
if (a) {
*a = khcy.a;
}
}
QColor KColorUtils::hcyColor(qreal h, qreal c, qreal y, qreal a)
{
return KColorSpaces::KHCY(h, c, y, a).qColor();
}
static qreal contrastRatioForLuma(qreal y1, qreal y2)
{
if (y1 > y2) {
return (y1 + 0.05) / (y2 + 0.05);
} else {
return (y2 + 0.05) / (y1 + 0.05);
}
}
qreal KColorUtils::contrastRatio(const QColor &c1, const QColor &c2)
{
return contrastRatioForLuma(luma(c1), luma(c2));
}
QColor KColorUtils::lighten(const QColor &color, qreal ky, qreal kc)
{
KColorSpaces::KHCY c(color);
c.y = 1.0 - normalize((1.0 - c.y) * (1.0 - ky));
c.c = 1.0 - normalize((1.0 - c.c) * kc);
return c.qColor();
}
QColor KColorUtils::darken(const QColor &color, qreal ky, qreal kc)
{
KColorSpaces::KHCY c(color);
c.y = normalize(c.y * (1.0 - ky));
c.c = normalize(c.c * kc);
return c.qColor();
}
QColor KColorUtils::shade(const QColor &color, qreal ky, qreal kc)
{
KColorSpaces::KHCY c(color);
c.y = normalize(c.y + ky);
c.c = normalize(c.c + kc);
return c.qColor();
}
static KColorSpaces::KHCY tintHelper(const QColor &base, qreal baseLuma, const QColor &color, qreal amount)
{
KColorSpaces::KHCY result(KColorUtils::mix(base, color, pow(amount, 0.3)));
result.y = mixQreal(baseLuma, result.y, amount);
return result;
}
static qreal tintHelperLuma(const QColor &base, qreal baseLuma, const QColor &color, qreal amount)
{
qreal result(KColorUtils::luma(KColorUtils::mix(base, color, pow(amount, 0.3))));
result = mixQreal(baseLuma, result, amount);
return result;
}
QColor KColorUtils::tint(const QColor &base, const QColor &color, qreal amount)
{
if (amount <= 0.0) {
return base;
}
if (amount >= 1.0) {
return color;
}
if (qIsNaN(amount)) {
return base;
}
qreal baseLuma = luma(base); // cache value because luma call is expensive
double ri = contrastRatioForLuma(baseLuma, luma(color));
double rg = 1.0 + ((ri + 1.0) * amount * amount * amount);
double u = 1.0;
double l = 0.0;
double a = 0.5;
for (int i = 12; i; --i) {
a = 0.5 * (l + u);
qreal resultLuma = tintHelperLuma(base, baseLuma, color, a);
double ra = contrastRatioForLuma(baseLuma, resultLuma);
if (ra > rg) {
u = a;
} else {
l = a;
}
}
return tintHelper(base, baseLuma, color, a).qColor();
}
QColor KColorUtils::mix(const QColor &c1, const QColor &c2, qreal bias)
{
if (bias <= 0.0) {
return c1;
}
if (bias >= 1.0) {
return c2;
}
if (qIsNaN(bias)) {
return c1;
}
qreal a = mixQreal(c1.alphaF(), c2.alphaF(), bias);
if (a <= 0.0) {
return Qt::transparent;
}
qreal r = qBound(0.0, mixQreal(c1.redF() * c1.alphaF(), c2.redF() * c2.alphaF(), bias), 1.0) / a;
qreal g = qBound(0.0, mixQreal(c1.greenF() * c1.alphaF(), c2.greenF() * c2.alphaF(), bias), 1.0) / a;
qreal b = qBound(0.0, mixQreal(c1.blueF() * c1.alphaF(), c2.blueF() * c2.alphaF(), bias), 1.0) / a;
return QColor::fromRgbF(r, g, b, a);
}
QColor KColorUtils::overlayColors(const QColor &base, const QColor &paint, QPainter::CompositionMode comp)
{
// This isn't the fastest way, but should be "fast enough".
// It's also the only safe way to use QPainter::CompositionMode
QImage img(1, 1, QImage::Format_ARGB32_Premultiplied);
QPainter p(&img);
QColor start = base;
start.setAlpha(255); // opaque
p.fillRect(0, 0, 1, 1, start);
p.setCompositionMode(comp);
p.fillRect(0, 0, 1, 1, paint);
p.end();
return img.pixel(0, 0);
}
@@ -0,0 +1,187 @@
/* This file is part of the KDE project
SPDX-FileCopyrightText: 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
SPDX-FileCopyrightText: 2007 Thomas Zander <zander@kde.org>
SPDX-FileCopyrightText: 2007 Zack Rusin <zack@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KCOLORUTILS_H
#define KCOLORUTILS_H
#include <kguiaddons_export.h>
#include <QPainter>
class QColor;
/**
* A set of methods used to work with colors.
*/
namespace KColorUtils
{
/**
* Calculate the hue of a color. The range is from 0.0 (red) to almost 1.0 (slightly blue-ish red).
*
* The result is computed in linear (not sRGB) color space and may differ slightly from QColor::hue().
*
* @see https://en.wikipedia.org/wiki/Hue
* @since 5.68
*/
KGUIADDONS_EXPORT qreal hue(const QColor &);
/**
* Calculate the chroma of a color. The range is from 0.0 (none) to 1.0 (full).
*
* The result is computed in linear (not sRGB) color space.
*
* @see https://en.wikipedia.org/wiki/Colorfulness
* @since 5.68
*/
KGUIADDONS_EXPORT qreal chroma(const QColor &);
/**
* Calculate the luma of a color. Luma is weighted sum of gamma-adjusted
* R'G'B' components of a color. The result is similar to qGray. The range
* is from 0.0 (black) to 1.0 (white).
*
* The result is computed in linear (not sRGB) color space.
*
* KColorUtils::darken(), KColorUtils::lighten() and KColorUtils::shade()
* operate on the luma of a color.
*
* @see http://en.wikipedia.org/wiki/Luma_(video)
*/
KGUIADDONS_EXPORT qreal luma(const QColor &);
/**
* Calculate hue, chroma and luma of a color in one call.
*
* The range of hue is from 0.0 (red) to almost 1.0 (slightly blue-ish red).
* The range of chroma is from 0.0 (none) to 1.0 (full).
* The range of luma is from 0.0 (black) to 1.0 (white).
*
* The hue, chroma and luma values are computed in linear (not sRGB) color space.
*
* @since 5.0
*/
KGUIADDONS_EXPORT void getHcy(const QColor &, qreal *hue, qreal *chroma, qreal *luma, qreal *alpha = nullptr);
/**
* Return a QColor based on the given hue, chroma, luma and alpha values.
*
* The range of hue is cyclical. For example, 0.0 and 1.0 are both red while -0.166667 and 0.833333 are both magenta.
* The range of chroma is from 0.0 (none) to 1.0 (full). Out of range values will be clamped.
* The range of luma is from 0.0 (black) to 1.0 (white). Out of range values will be clamped.
*
* The hue, chroma and luma values are computed in linear (not sRGB) color space.
*
* @since 5.68
*/
KGUIADDONS_EXPORT QColor hcyColor(qreal hue, qreal chroma, qreal luma, qreal alpha = 1.0);
/**
* Calculate the contrast ratio between two colors, according to the
* W3C/WCAG2.0 algorithm, (Lmax + 0.05)/(Lmin + 0.05), where Lmax and Lmin
* are the luma values of the lighter color and the darker color,
* respectively.
*
* A contrast ration of 5:1 (result == 5.0) is the minimum for "normal"
* text to be considered readable (large text can go as low as 3:1). The
* ratio ranges from 1:1 (result == 1.0) to 21:1 (result == 21.0).
*
* @see KColorUtils::luma
*/
KGUIADDONS_EXPORT qreal contrastRatio(const QColor &, const QColor &);
/**
* Adjust the luma of a color by changing its distance from white.
*
* @li amount == 1.0 gives white
* @li amount == 0.5 results in a color whose luma is halfway between 1.0
* and that of the original color
* @li amount == 0.0 gives the original color
* @li amount == -1.0 gives a color that is 'twice as far from white' as
* the original color, that is luma(result) == 1.0 - 2*(1.0 - luma(color))
*
* @param amount factor by which to adjust the luma component of the color
* @param chromaInverseGain (optional) factor by which to adjust the chroma
* component of the color; 1.0 means no change, 0.0 maximizes chroma
* @see KColorUtils::shade
*/
KGUIADDONS_EXPORT QColor lighten(const QColor &, qreal amount = 0.5, qreal chromaInverseGain = 1.0);
/**
* Adjust the luma of a color by changing its distance from black.
*
* @li amount == 1.0 gives black
* @li amount == 0.5 results in a color whose luma is halfway between 0.0
* and that of the original color
* @li amount == 0.0 gives the original color
* @li amount == -1.0 gives a color that is 'twice as far from black' as
* the original color, that is luma(result) == 2*luma(color)
*
* @param amount factor by which to adjust the luma component of the color
* @param chromaGain (optional) factor by which to adjust the chroma
* component of the color; 1.0 means no change, 0.0 minimizes chroma
* @see KColorUtils::shade
*/
KGUIADDONS_EXPORT QColor darken(const QColor &, qreal amount = 0.5, qreal chromaGain = 1.0);
/**
* Adjust the luma and chroma components of a color. The amount is added
* to the corresponding component.
*
* @param lumaAmount amount by which to adjust the luma component of the
* color; 0.0 results in no change, -1.0 turns anything black, 1.0 turns
* anything white
* @param chromaAmount (optional) amount by which to adjust the chroma
* component of the color; 0.0 results in no change, -1.0 minimizes chroma,
* 1.0 maximizes chroma
* @see KColorUtils::luma
*/
KGUIADDONS_EXPORT QColor shade(const QColor &, qreal lumaAmount, qreal chromaAmount = 0.0);
/**
* Create a new color by tinting one color with another. This function is
* meant for creating additional colors withings the same class (background,
* foreground) from colors in a different class. Therefore when @p amount
* is low, the luma of @p base is mostly preserved, while the hue and
* chroma of @p color is mostly inherited.
*
* @param base color to be tinted
* @param color color with which to tint
* @param amount how strongly to tint the base; 0.0 gives @p base,
* 1.0 gives @p color
*/
KGUIADDONS_EXPORT QColor tint(const QColor &base, const QColor &color, qreal amount = 0.3);
/**
* Blend two colors into a new color by linear combination.
* @code
QColor lighter = KColorUtils::mix(myColor, Qt::white)
* @endcode
* @param c1 first color.
* @param c2 second color.
* @param bias weight to be used for the mix. @p bias <= 0 gives @p c1,
* @p bias >= 1 gives @p c2. @p bias == 0.5 gives a 50% blend of @p c1
* and @p c2.
*/
KGUIADDONS_EXPORT QColor mix(const QColor &c1, const QColor &c2, qreal bias = 0.5);
/**
* Blend two colors into a new color by painting the second color over the
* first using the specified composition mode.
* @code
QColor white(Qt::white);
white.setAlphaF(0.5);
QColor lighter = KColorUtils::overlayColors(myColor, white);
@endcode
* @param base the base color (alpha channel is ignored).
* @param paint the color to be overlaid onto the base color.
* @param comp the CompositionMode used to do the blending.
*/
KGUIADDONS_EXPORT QColor overlayColors(const QColor &base, const QColor &paint, QPainter::CompositionMode comp = QPainter::CompositionMode_SourceOver);
}
#endif // KCOLORUTILS_H
@@ -0,0 +1,18 @@
/* This file is part of the KDE project
SPDX-FileCopyrightText: 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
SPDX-FileCopyrightText: 2007 Olaf Schmidt <ojschmidt@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KGUIADDONS_COLORHELPERS_P_H
#define KGUIADDONS_COLORHELPERS_P_H
// normalize: like qBound(a, 0.0, 1.0) but without needing the args and with
// "safer" behavior on NaN (isnan(a) -> return 0.0)
static inline qreal normalize(qreal a)
{
return (a < 1.0 ? (a > 0.0 ? a : 0.0) : 1.0);
}
#endif // KGUIADDONS_KCOLORHELPERS_P_H
@@ -0,0 +1,82 @@
// SPDX-FileCopyrightText: 2024 Mathis Brüchert <mbb@kaidan.im>
// SPDX-FileCopyrightText: 2024 Volker Krause <vkrause@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "kwindowinsetscontroller.h"
#include <QCoreApplication>
#ifdef Q_OS_ANDROID
#include <QJniObject>
#endif
class KWindowInsetsControllerPrivate
{
public:
QColor m_statusBarColor;
QColor m_navigationBarColor;
};
KWindowInsetsController::KWindowInsetsController(QObject *parent)
: QObject(parent)
#ifdef Q_OS_ANDROID
, d(new KWindowInsetsControllerPrivate)
#endif
{
}
KWindowInsetsController::~KWindowInsetsController() = default;
QColor KWindowInsetsController::statusBarBackgroundColor() const // NOLINT readability-convert-member-functions-to-static
{
#ifdef Q_OS_ANDROID
return d->m_statusBarColor;
#else
return {};
#endif
}
void KWindowInsetsController::setStatusBarBackgroundColor(const QColor &color) // NOLINT readability-convert-member-functions-to-static
{
#ifdef Q_OS_ANDROID
d->m_statusBarColor = color;
QNativeInterface::QAndroidApplication::runOnAndroidMainThread([=]() {
QJniObject::callStaticMethod<void>("org.kde.guiaddons.KWindowInsetsController",
"setStatusBarBackground",
"(Landroid/app/Activity;I)V",
QNativeInterface::QAndroidApplication::context(),
color.rgba());
});
#else
Q_UNUSED(color)
#endif
}
QColor KWindowInsetsController::navigationBarBackgroundColor() const // NOLINT readability-convert-member-functions-to-static
{
#ifdef Q_OS_ANDROID
return d->m_navigationBarColor;
#else
return {};
#endif
}
void KWindowInsetsController::setNavigationBarBackgroundColor(const QColor &color) // NOLINT readability-convert-member-functions-to-static
{
#ifdef Q_OS_ANDROID
d->m_navigationBarColor = color;
QNativeInterface::QAndroidApplication::runOnAndroidMainThread([=]() {
QJniObject::callStaticMethod<void>("org.kde.guiaddons.KWindowInsetsController",
"setNavigationBarBackground",
"(Landroid/app/Activity;I)V",
QNativeInterface::QAndroidApplication::context(),
color.rgba());
});
#else
Q_UNUSED(color)
#endif
}
#include "moc_kwindowinsetscontroller.cpp"
@@ -0,0 +1,63 @@
// SPDX-FileCopyrightText: 2024 Mathis Brüchert <mbb@kaidan.im>
// SPDX-FileCopyrightText: 2024 Volker Krause <vkrause@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#ifndef KWINDOWINSETSCONTROLLER_H
#define KWINDOWINSETSCONTROLLER_H
#include "kguiaddons_export.h"
#include <QColor>
#include <QObject>
#include <memory>
class KWindowInsetsControllerPrivate;
/** Access to window insets colors.
*
* On most platforms this does nothing, on Android it allows
* to customize the (top) status bar and (botton) navigation bar
* background colors, e.g. to match the current window or application
* colors.
*
* Note that the foreground colors on Android are automatically
* chosen based on the background color.
*
* @code
* Component.onComplete: {
* WindowInsetsController.statusBarBackgroundColor = Kirigami.Theme.backgroundColor;
* WindowInsetsController.navigationBarBackgroundColor = Kirigami.Theme.backgroundColor;
* }
* @endcode
*
* @since 6.7
*/
class KGUIADDONS_EXPORT KWindowInsetsController : public QObject
{
Q_OBJECT
/** Background color of the status bar. */
Q_PROPERTY(QColor statusBarBackgroundColor READ statusBarBackgroundColor WRITE setStatusBarBackgroundColor NOTIFY statusBarBackgroundColorChanged)
/** Background color of the navigation bar. */
Q_PROPERTY(
QColor navigationBarBackgroundColor READ navigationBarBackgroundColor WRITE setNavigationBarBackgroundColor NOTIFY navigationBarBackgroundColorChanged)
public:
explicit KWindowInsetsController(QObject *parent = nullptr);
~KWindowInsetsController();
[[nodiscard]] QColor statusBarBackgroundColor() const;
void setStatusBarBackgroundColor(const QColor &color);
[[nodiscard]] QColor navigationBarBackgroundColor() const;
void setNavigationBarBackgroundColor(const QColor &color);
Q_SIGNALS:
void statusBarBackgroundColorChanged();
void navigationBarBackgroundColorChanged();
private:
std::unique_ptr<KWindowInsetsControllerPrivate> d;
};
#endif // KWINDOWINSETSCONTROLLER_H
@@ -0,0 +1,2 @@
#cmakedefine01 WITH_X11
#cmakedefine01 WITH_WAYLAND
@@ -0,0 +1,90 @@
/*
SPDX-FileCopyrightText: 2005, 2009, 2014 Albert Astals Cid <aacid@kde.org>
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/
#include "kfontutils.h"
#include <QPainter>
#include <qmath.h>
static bool checkFits(QPainter &painter, const QString &string, qreal width, qreal height, qreal size, KFontUtils::AdaptFontSizeOptions flags)
{
QFont f = painter.font();
f.setPointSizeF(size);
painter.setFont(f);
int qtFlags = Qt::AlignCenter | Qt::TextWordWrap;
if (flags & KFontUtils::DoNotAllowWordWrap) {
qtFlags &= ~Qt::TextWordWrap;
}
const QRectF boundingRect = painter.boundingRect(QRectF(0, 0, width, height), qtFlags, string);
if (boundingRect.width() == 0.0 || boundingRect.height() == 0.0) {
return false;
} else if (boundingRect.width() > width || boundingRect.height() > height) {
return false;
}
return true;
}
qreal KFontUtils::adaptFontSize(QPainter &painter,
const QString &string,
qreal width,
qreal height,
qreal maxFontSize,
qreal minFontSize,
AdaptFontSizeOptions flags)
{
// A invalid range is an error (-1)
if (maxFontSize < minFontSize) {
return -1;
}
// If the max font size already fits, return it
if (checkFits(painter, string, width, height, maxFontSize, flags)) {
return maxFontSize;
}
qreal fontSizeDoesNotFit = maxFontSize;
// If the min font size does not fit, try to see if a font size of 1 fits,
// if it does not return error (-1)
// if it does, we'll return a fontsize smaller than the minFontSize as documented
if (!checkFits(painter, string, width, height, minFontSize, flags)) {
fontSizeDoesNotFit = minFontSize;
minFontSize = 1;
if (!checkFits(painter, string, width, height, minFontSize, flags)) {
return -1;
}
}
qreal fontSizeFits = minFontSize;
qreal nextFontSizeToTry = (fontSizeDoesNotFit + fontSizeFits) / 2;
while (qFloor(fontSizeFits) != qFloor(nextFontSizeToTry)) {
if (checkFits(painter, string, width, height, nextFontSizeToTry, flags)) {
fontSizeFits = nextFontSizeToTry;
nextFontSizeToTry = (fontSizeDoesNotFit + fontSizeFits) / 2;
} else {
fontSizeDoesNotFit = nextFontSizeToTry;
nextFontSizeToTry = (nextFontSizeToTry + fontSizeFits) / 2;
}
}
QFont f = painter.font();
f.setPointSizeF(fontSizeFits);
painter.setFont(f);
return fontSizeFits;
}
qreal KFontUtils::adaptFontSize(QPainter &painter,
const QString &text,
const QSizeF &availableSize,
qreal maxFontSize,
qreal minFontSize,
AdaptFontSizeOptions flags)
{
return adaptFontSize(painter, text, availableSize.width(), availableSize.height(), maxFontSize, minFontSize, flags);
}
@@ -0,0 +1,74 @@
/*
SPDX-FileCopyrightText: 2005, 2009 Albert Astals Cid <aacid@kde.org>
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/
#ifndef KFONTUTILS_H
#define KFONTUTILS_H
#include <kguiaddons_export.h>
#include <qglobal.h>
class QPainter;
class QSizeF;
class QString;
/**
* @namespace KFontUtils
* Provides utility functions for font data.
*/
namespace KFontUtils
{
/**
* Modifiers for the adaptFontSize function
* @see AdaptFontSizeOptions
*/
enum AdaptFontSizeOption {
NoFlags = 0x01, ///< No modifier
DoNotAllowWordWrap = 0x02, ///< Do not use word wrapping
};
/**
* Stores a combination of #AdaptFontSizeOption values.
*/
Q_DECLARE_FLAGS(AdaptFontSizeOptions, AdaptFontSizeOption)
Q_DECLARE_OPERATORS_FOR_FLAGS(AdaptFontSizeOptions)
/** Helper function that calculates the biggest font size (in points) used
drawing a centered text using word wrapping.
@param painter The painter where the text will be painted. The font set
in the painter is used for the calculation. Note the
painter font size is modified by this call
@param text The text you want to draw
@param width The available width for drawing
@param height The available height for drawing
@param maxFontSize The maximum font size (in points) to consider
@param minFontSize The minimum font size (in points) to consider
@param flags The modifiers for how the text is painted
@return The calculated biggest font size (in points) that draws the text
in the given dimensions. Can return smaller than minFontSize,
that means the text doesn't fit in the given rectangle. Can
return -1 on error
@since 4.7
*/
qreal KGUIADDONS_EXPORT adaptFontSize(QPainter &painter,
const QString &text,
qreal width,
qreal height,
qreal maxFontSize = 28.0,
qreal minFontSize = 1.0,
AdaptFontSizeOptions flags = NoFlags);
/** Convenience function for adaptFontSize that accepts a QSizeF instead two qreals
@since 4.7
*/
qreal KGUIADDONS_EXPORT adaptFontSize(QPainter &painter,
const QString &text,
const QSizeF &availableSize,
qreal maxFontSize = 28.0,
qreal minFontSize = 1.0,
AdaptFontSizeOptions flags = NoFlags);
}
#endif
@@ -0,0 +1,22 @@
# SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
# SPDX-License-Identifier: BSD-2-Clause
add_executable(kde-geo-uri-handler
kgeourihandler.cpp
kgeourihandler_p.h
main.cpp
)
ecm_mark_nongui_executable(kde-geo-uri-handler)
target_include_directories(kde-geo-uri-handler PRIVATE "${CMAKE_BINARY_DIR}/src") # for kguiaddons_version.h
target_link_libraries(kde-geo-uri-handler PRIVATE Qt6::Gui)
install(TARGETS kde-geo-uri-handler ${KF_INSTALL_TARGETS_DEFAULT_ARGS})
install(
FILES
google-maps-geo-handler.desktop
openstreetmap-geo-handler.desktop
qwant-maps-geo-handler.desktop
wheelmap-geo-handler.desktop
DESTINATION
${KDE_INSTALL_APPDIR}
)
@@ -0,0 +1,50 @@
[Desktop Entry]
Type=Application
Exec=kde-geo-uri-handler --coordinate-template "https://www.google.com/maps/@<LAT>,<LON>,<Z>z" --query-template "https://www.google.com/maps/search/<Q>" --fallback "https://www.google.com/maps/" %u
Name=Google Maps
Name[ar]=خرائط غوغل
Name[ast]=Google Maps
Name[bg]=Google карти
Name[ca]=Google Maps
Name[ca@valencia]=Google Maps
Name[cs]=Mapy Google
Name[de]=Google Maps
Name[en_GB]=Google Maps
Name[eo]=Guglo-Mapoj
Name[es]=Google Maps
Name[eu]=Google Maps
Name[fi]=Google Maps
Name[fr]=Google Maps
Name[gl]=Google Maps
Name[he]=Google מפות
Name[hi]=गूगल मैप्स
Name[hu]=Google Térképek
Name[ia]=Google Maps (Mappas de Google)
Name[is]=Google Maps
Name[it]=Mappe di Google
Name[ka]=Google Maps
Name[ko]=Google 지도
Name[lt]=„Google“ žemėlapiai
Name[lv]=Google Maps
Name[nl]=Google Maps
Name[nn]=Google Maps
Name[pl]=Mapy Google
Name[pt]=Google Maps
Name[pt_BR]=Google Maps
Name[ro]=Hărți Google
Name[ru]=Карты Google
Name[sa]=गूगल मानचित्रम् (Google Maps)
Name[sk]=Google Maps
Name[sl]=Google Maps
Name[sv]=Google kartor
Name[ta]=கூகுள் மேப்ஸ்
Name[tr]=Google Haritalar
Name[uk]=Карти Google
Name[vi]=Google Bản đồ
Name[x-test]=xxGoogle Mapsxx
Name[zh_CN]=Google Maps
Name[zh_TW]=Google 地圖
Icon=map-globe
MimeType=x-scheme-handler/geo;
Terminal=false
NoDisplay=true
@@ -0,0 +1,2 @@
SPDX-FileCopyrightText: 2022 Florian Edelmann <florian-edelmann@online.de>
SPDX-License-Identifier: CC0-1.0
@@ -0,0 +1,69 @@
/*
SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kgeourihandler_p.h"
#include <QUrl>
#include <QUrlQuery>
void KGeoUriHandler::setCoordinateTemplate(const QString &coordTmpl)
{
m_coordTmpl = coordTmpl;
}
void KGeoUriHandler::setQueryTemplate(const QString &queryTmpl)
{
m_queryTmpl = queryTmpl;
}
void KGeoUriHandler::setFallbackUrl(const QString &fallbackUrl)
{
m_fallbackUrl = fallbackUrl;
}
static bool isValidCoordinate(double c, double limit)
{
return c != 0.0 && c >= -limit && c <= limit;
}
QString KGeoUriHandler::handleUri(const QUrl &geoUri)
{
const auto pathElems = geoUri.path().split(QLatin1Char(';'));
const auto coordElems = pathElems.isEmpty() ? QStringList() : pathElems.at(0).split(QLatin1Char(','));
const auto lat = coordElems.size() < 2 ? 0.0 : coordElems.at(0).toDouble();
const auto lon = coordElems.size() < 2 ? 0.0 : coordElems.at(1).toDouble();
const auto geoQuery = QUrlQuery(geoUri.query());
const auto query = geoQuery.queryItemValue(QStringLiteral("q"));
bool zoomValid = false;
int zoom = geoQuery.queryItemValue(QStringLiteral("z")).toInt(&zoomValid);
if (!zoomValid || zoom < 0 || zoom > 21) {
zoom = 18;
}
// unsupported coordinate reference system
if (!pathElems.isEmpty() && std::any_of(pathElems.begin() + 1, pathElems.end(), [](const auto &elem) {
return elem.startsWith(QLatin1String("crs="), Qt::CaseInsensitive) && !elem.endsWith(QLatin1String("=wgs84"), Qt::CaseInsensitive);
})) {
return m_fallbackUrl;
}
QString tmpl;
if (!query.isEmpty()) {
tmpl = m_queryTmpl;
} else if (isValidCoordinate(lat, 90.0) && isValidCoordinate(lon, 180.0)) {
tmpl = m_coordTmpl;
} else {
return m_fallbackUrl;
}
tmpl.replace(QLatin1String("<LAT>"), QString::number(lat));
tmpl.replace(QLatin1String("<LON>"), QString::number(lon));
tmpl.replace(QLatin1String("<Q>"), query);
tmpl.replace(QLatin1String("<Z>"), QString::number(zoom));
return tmpl;
}
@@ -0,0 +1,44 @@
/*
SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KGEOURIHANDLER_H
#define KGEOURIHANDLER_H
#include <QString>
class QUrl;
/** Fallback handler for geo: URIs by forwarding them to a web service.
*
* This handles three cases of geo: URIs:
* - when containing a query argument, the query URL template is used
* - when containing valid WGS-84 coordinates, the coordinate URL template is used
* - otherwise the fallback URL is returned
*
* URL templates can contain any number of the following placeholders in angle brackets:
* - @c LAT - the latitude
* - @c LON - the longitude
* - @c Q - the query string
* - @c Z - the zoom level for a Web Mercator map projection
*
* @see https://en.wikipedia.org/wiki/Geo_URI_scheme
* @see https://datatracker.ietf.org/doc/html/rfc5870
*/
class KGeoUriHandler
{
public:
void setCoordinateTemplate(const QString &coordTmpl);
void setQueryTemplate(const QString &queryTmpl);
void setFallbackUrl(const QString &fallbackUrl);
QString handleUri(const QUrl &geoUri);
private:
QString m_coordTmpl;
QString m_queryTmpl;
QString m_fallbackUrl;
};
#endif // KGEOURIHANDLER_H
@@ -0,0 +1,49 @@
/*
SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kgeourihandler_p.h"
#include <kguiaddons_version.h>
#include <QCommandLineParser>
#include <QDesktopServices>
#include <QGuiApplication>
#include <QUrl>
int main(int argc, char **argv)
{
QCoreApplication::setApplicationName(QStringLiteral("kde-geo-uri-handler"));
QCoreApplication::setOrganizationName(QStringLiteral("KDE"));
QCoreApplication::setOrganizationDomain(QStringLiteral("kde.org"));
QCoreApplication::setApplicationVersion(QStringLiteral(KGUIADDONS_VERSION_STRING));
QGuiApplication app(argc, argv);
QCommandLineParser parser;
QCommandLineOption coordTmplOpt(QStringLiteral("coordinate-template"),
QStringLiteral("URL template for coordinate-based access."),
QStringLiteral("coordinate-template"));
parser.addOption(coordTmplOpt);
QCommandLineOption queryTmplOpt(QStringLiteral("query-template"), QStringLiteral("URL template for query-based access."), QStringLiteral("query-template"));
parser.addOption(queryTmplOpt);
QCommandLineOption fallbackOpt(QStringLiteral("fallback"), QStringLiteral("URL to use in case of errors."), QStringLiteral("fallback-url"));
parser.addOption(fallbackOpt);
parser.addPositionalArgument(QStringLiteral("uri"), QStringLiteral("geo: URI to handle"));
parser.addHelpOption();
parser.addVersionOption();
parser.process(app);
KGeoUriHandler handler;
handler.setCoordinateTemplate(parser.value(coordTmplOpt));
handler.setQueryTemplate(parser.value(queryTmplOpt));
handler.setFallbackUrl(parser.value(fallbackOpt));
const auto args = parser.positionalArguments();
for (const auto &arg : args) {
const auto url = handler.handleUri(QUrl(arg));
QDesktopServices::openUrl(QUrl(url));
}
return 0;
}
@@ -0,0 +1,49 @@
[Desktop Entry]
Type=Application
Exec=kde-geo-uri-handler --coordinate-template "https://www.openstreetmap.org/#map=<Z>/<LAT>/<LON>" --query-template "https://www.openstreetmap.org/search?query=<Q>" --fallback "https://www.openstreetmap.org" %u
Name=OpenStreetMap
Name[ar]=خريطة الشّوارع المفتوحة
Name[ast]=OpenStreetMap
Name[bg]=OpenStreetMap
Name[ca]=OpenStreetMap
Name[ca@valencia]=OpenStreetMap
Name[cs]=OpenStreetMap
Name[de]=OpenStreetMap
Name[en_GB]=OpenStreetMap
Name[eo]=OpenStreetMap
Name[es]=OpenStreetMap
Name[eu]=OpenStreetMap
Name[fi]=OpenStreetMap
Name[fr]=OpenStreetMap
Name[gl]=OpenStreetMap
Name[he]=OpenStreetMap
Name[hi]=ओपनस्ट्रीटमैप
Name[hu]=OpenStreetMap
Name[ia]=OpenStreetMap
Name[is]=OpenStreetMap
Name[it]=OpenStreetMap
Name[ka]=OpenStreetMap
Name[ko]=OpenStreetMap
Name[lt]=OpenStreetMap
Name[lv]=OpenStreetMap
Name[nl]=OpenStreetMap
Name[nn]=OpenStreetMap
Name[pl]=OpenStreetMap
Name[pt]=OpenStreetMap
Name[pt_BR]=OpenStreetMap
Name[ro]=OpenStreetMap
Name[ru]=OpenStreetMap
Name[sa]=वीथिमानचित्रं उद्घाटयन्तु (OpenStreetMap)
Name[sk]=OpenStreetMap
Name[sl]=OpenStreetMap
Name[sv]=OpenStreetMap
Name[tr]=OpenStreetMap
Name[uk]=OpenStreetMap
Name[vi]=OpenStreetMap
Name[x-test]=xxOpenStreetMapxx
Name[zh_CN]=OpenStreetMap
Name[zh_TW]=OpenStreetMap 開放街圖
Icon=map-globe
MimeType=x-scheme-handler/geo;
Terminal=false
NoDisplay=true
@@ -0,0 +1,2 @@
SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: CC0-1.0
@@ -0,0 +1,49 @@
[Desktop Entry]
Type=Application
Exec=kde-geo-uri-handler --coordinate-template "https://www.qwant.com/maps/#map=<Z>/<LAT>/<LON>" --query-template "https://www.qwant.com/maps/?q=<Q>&client=opensearch" --fallback "https://www.qwant.com/maps/" %u
Name=Qwant Maps
Name[ar]=خرائط كوانت
Name[ast]=Qwant Maps
Name[bg]=Qwant Maps
Name[ca]=Qwant Maps
Name[ca@valencia]=Qwant Maps
Name[cs]=Mapy Qwant
Name[de]=Qwant Maps
Name[en_GB]=Qwant Maps
Name[eo]=Qwant-Mapoj
Name[es]=Qwant Maps
Name[eu]=Qwant Maps
Name[fi]=Qwant Maps
Name[fr]=Qwant Maps
Name[gl]=Qwant Maps
Name[he]=Qwant Maps
Name[hi]=क्वान्ट मैप्स
Name[hu]=Qwant Térképek
Name[ia]=Qwant Maps (Mappas de Qwant)
Name[is]=Qwant Maps
Name[it]=Qwant Maps
Name[ka]=Qwant Maps
Name[ko]=Qwant 지도
Name[lt]=„Qwant“ žemėlapiai
Name[lv]=Qwant Maps
Name[nl]=Qwant Maps
Name[nn]=Qwant Maps
Name[pl]=Mapy Qwant
Name[pt]=Qwant Maps
Name[pt_BR]=Qwant Maps
Name[ro]=Hărți Qwant
Name[ru]=Карты Qwant
Name[sa]=क्वान्ट मानचित्र (Qwant Maps)
Name[sk]=Qwant Maps
Name[sl]=Qwant Maps
Name[sv]=Qwant kartor
Name[tr]=Qwant Haritalar
Name[uk]=Карти Qwant
Name[vi]=Bản đồ Qwant
Name[x-test]=xxQwant Mapsxx
Name[zh_CN]=Qwant Maps
Name[zh_TW]=Qwant 地圖
Icon=map-globe
MimeType=x-scheme-handler/geo;
Terminal=false
NoDisplay=true
@@ -0,0 +1,2 @@
SPDX-FileCopyrightText: 2022 Florian Edelmann <florian-edelmann@online.de>
SPDX-License-Identifier: CC0-1.0
@@ -0,0 +1,49 @@
[Desktop Entry]
Type=Application
Exec=kde-geo-uri-handler --coordinate-template "https://wheelmap.org/?lat=<LAT>&lon=<LON>" --query-template "https://wheelmap.org/search?q=<Q>" --fallback "https://wheelmap.org" %u
Name=wheelmap.org
Name[ar]=wheelmap.org
Name[ast]=wheelmap.org
Name[bg]=wheelmap.org
Name[ca]=wheelmap.org
Name[ca@valencia]=wheelmap.org
Name[cs]=wheelmap.org
Name[de]=wheelmap.org
Name[en_GB]=wheelmap.org
Name[eo]=wheelmap.org
Name[es]=wheelmap.org
Name[eu]=wheelmap.org
Name[fi]=wheelmap.org
Name[fr]=wheelmap.org
Name[gl]=wheelmap.org
Name[he]=wheelmap.org
Name[hi]=व्हीलमैप्स.ऑर्ग
Name[hu]=wheelmap.org
Name[ia]=wheelmap.org
Name[is]=wheelmap.org
Name[it]=wheelmap.org
Name[ka]=wheelmap.org
Name[ko]=wheelmap.org
Name[lt]=wheelmap.org
Name[lv]=wheelmap.org
Name[nl]=wheelmap.org
Name[nn]=wheelmap.org
Name[pl]=wheelmap.org
Name[pt]=wheelmap.org
Name[pt_BR]=wheelmap.org
Name[ro]=wheelmap.org
Name[ru]=wheelmap.org
Name[sa]=wheelmap.org
Name[sk]=wheelmap.org
Name[sl]=wheelmap.org
Name[sv]=wheelmap.org
Name[tr]=wheelmap.org
Name[uk]=wheelmap.org
Name[vi]=wheelmap.org
Name[x-test]=xxwheelmap.orgxx
Name[zh_CN]=wheelmap.org
Name[zh_TW]=wheelmap.org
Icon=map-globe
MimeType=x-scheme-handler/geo;
Terminal=false
NoDisplay=true
@@ -0,0 +1,2 @@
SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: CC0-1.0
@@ -0,0 +1,7 @@
# SPDX-FileCopyrightText: 2024 Volker Krause <vkrause@kde.org>
# SPDX-License-Identifier: BSD-2-Clause
ecm_add_qml_module(kguiaddonsqml URI "org.kde.guiaddons" GENERATE_PLUGIN_SOURCE INSTALLED_PLUGIN_TARGET KF6::kguiaddonsqml)
target_sources(kguiaddonsqml PRIVATE types.h)
target_link_libraries(kguiaddonsqml PRIVATE KF6GuiAddons Qt6::Qml)
ecm_finalize_qml_module(kguiaddonsqml EXPORT KF6GuiAddonsTargets)
@@ -0,0 +1,19 @@
// SPDX-FileCopyrightText: 2024 Volker Krause <vkrause@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#ifndef KGUIADDONS_QML_TYPES
#define KGUIADDONS_QML_TYPES
#include <KWindowInsetsController>
#include <QQmlEngine>
class KWindowInsetsControllerForeign : public QObject
{
Q_OBJECT
QML_NAMED_ELEMENT(WindowInsetsController)
QML_FOREIGN(KWindowInsetsController)
QML_SINGLETON
};
#endif
@@ -0,0 +1,143 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="keyboard_shortcuts_inhibit_unstable_v1">
<copyright>
Copyright © 2017 Red Hat Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</copyright>
<description summary="Protocol for inhibiting the compositor keyboard shortcuts">
This protocol specifies a way for a client to request the compositor
to ignore its own keyboard shortcuts for a given seat, so that all
key events from that seat get forwarded to a surface.
Warning! The protocol described in this file is experimental and
backward incompatible changes may be made. Backward compatible
changes may be added together with the corresponding interface
version bump.
Backward incompatible changes are done by bumping the version
number in the protocol and interface names and resetting the
interface version. Once the protocol is to be declared stable,
the 'z' prefix and the version number in the protocol and
interface names are removed and the interface version number is
reset.
</description>
<interface name="zwp_keyboard_shortcuts_inhibit_manager_v1" version="1">
<description summary="context object for keyboard grab_manager">
A global interface used for inhibiting the compositor keyboard shortcuts.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the keyboard shortcuts inhibitor object">
Destroy the keyboard shortcuts inhibitor manager.
</description>
</request>
<request name="inhibit_shortcuts">
<description summary="create a new keyboard shortcuts inhibitor object">
Create a new keyboard shortcuts inhibitor object associated with
the given surface for the given seat.
If shortcuts are already inhibited for the specified seat and surface,
a protocol error "already_inhibited" is raised by the compositor.
</description>
<arg name="id" type="new_id" interface="zwp_keyboard_shortcuts_inhibitor_v1"/>
<arg name="surface" type="object" interface="wl_surface"
summary="the surface that inhibits the keyboard shortcuts behavior"/>
<arg name="seat" type="object" interface="wl_seat"
summary="the wl_seat for which keyboard shortcuts should be disabled"/>
</request>
<enum name="error">
<entry name="already_inhibited"
value="0"
summary="the shortcuts are already inhibited for this surface"/>
</enum>
</interface>
<interface name="zwp_keyboard_shortcuts_inhibitor_v1" version="1">
<description summary="context object for keyboard shortcuts inhibitor">
A keyboard shortcuts inhibitor instructs the compositor to ignore
its own keyboard shortcuts when the associated surface has keyboard
focus. As a result, when the surface has keyboard focus on the given
seat, it will receive all key events originating from the specified
seat, even those which would normally be caught by the compositor for
its own shortcuts.
The Wayland compositor is however under no obligation to disable
all of its shortcuts, and may keep some special key combo for its own
use, including but not limited to one allowing the user to forcibly
restore normal keyboard events routing in the case of an unwilling
client. The compositor may also use the same key combo to reactivate
an existing shortcut inhibitor that was previously deactivated on
user request.
When the compositor restores its own keyboard shortcuts, an
"inactive" event is emitted to notify the client that the keyboard
shortcuts inhibitor is not effectively active for the surface and
seat any more, and the client should not expect to receive all
keyboard events.
When the keyboard shortcuts inhibitor is inactive, the client has
no way to forcibly reactivate the keyboard shortcuts inhibitor.
The user can chose to re-enable a previously deactivated keyboard
shortcuts inhibitor using any mechanism the compositor may offer,
in which case the compositor will send an "active" event to notify
the client.
If the surface is destroyed, unmapped, or loses the seat's keyboard
focus, the keyboard shortcuts inhibitor becomes irrelevant and the
compositor will restore its own keyboard shortcuts but no "inactive"
event is emitted in this case.
</description>
<request name="destroy" type="destructor">
<description summary="destroy the keyboard shortcuts inhibitor object">
Remove the keyboard shortcuts inhibitor from the associated wl_surface.
</description>
</request>
<event name="active">
<description summary="shortcuts are inhibited">
This event indicates that the shortcut inhibitor is active.
The compositor sends this event every time compositor shortcuts
are inhibited on behalf of the surface. When active, the client
may receive input events normally reserved by the compositor
(see zwp_keyboard_shortcuts_inhibitor_v1).
This occurs typically when the initial request "inhibit_shortcuts"
first becomes active or when the user instructs the compositor to
re-enable and existing shortcuts inhibitor using any mechanism
offered by the compositor.
</description>
</event>
<event name="inactive">
<description summary="shortcuts are restored">
This event indicates that the shortcuts inhibitor is inactive,
normal shortcuts processing is restored by the compositor.
</description>
</event>
</interface>
</protocol>
@@ -0,0 +1,41 @@
/*
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>
*/
#include "keyboardgrabber_p.h"
#include <QWindow>
KeyboardGrabber::KeyboardGrabber(QWindow *window)
: ShortcutInhibition()
, m_grabbedWindow(window)
, m_grabbingKeyboard(false)
{
}
KeyboardGrabber::~KeyboardGrabber()
{
disableInhibition();
}
void KeyboardGrabber::enableInhibition()
{
if (m_grabbingKeyboard || !m_grabbedWindow) {
return;
}
m_grabbingKeyboard = m_grabbedWindow->setKeyboardGrabEnabled(true);
}
void KeyboardGrabber::disableInhibition()
{
if (!m_grabbingKeyboard) {
return;
}
m_grabbingKeyboard = !(m_grabbedWindow->setKeyboardGrabEnabled(false));
}
bool KeyboardGrabber::shortcutsAreInhibited() const
{
return m_grabbingKeyboard;
}
@@ -0,0 +1,25 @@
/*
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>
*/
#ifndef GRABBINGINHIBITION_H
#define GRABBINGINHIBITION_H
#include "shortcutinhibition_p.h"
class KeyboardGrabber : public ShortcutInhibition
{
public:
explicit KeyboardGrabber(QWindow *window);
~KeyboardGrabber() override;
void enableInhibition() override;
void disableInhibition() override;
bool shortcutsAreInhibited() const override;
private:
QWindow *m_grabbedWindow;
bool m_grabbingKeyboard;
};
#endif
@@ -0,0 +1,656 @@
/*
SPDX-FileCopyrightText: 1998 Mark Donohoe <donohoe@kde.org>
SPDX-FileCopyrightText: 2001 Ellis Whitehead <ellis@kde.org>
SPDX-FileCopyrightText: 2007 Andreas Hartmetz <ahartmetz@gmail.com>
SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kkeysequencerecorder.h"
#include "keyboardgrabber_p.h"
#include "kguiaddons_debug.h"
#include "shortcutinhibition_p.h"
#include "waylandinhibition_p.h"
#include <QGuiApplication>
#include <QKeyEvent>
#include <QPointer>
#include <QTimer>
#include <QWindow>
#include <array>
#include <chrono>
/// Singleton whose only purpose is to tell us about other sequence recorders getting started
class KKeySequenceRecorderGlobal : public QObject
{
Q_OBJECT
public:
static KKeySequenceRecorderGlobal *self()
{
static KKeySequenceRecorderGlobal s_self;
return &s_self;
}
Q_SIGNALS:
void sequenceRecordingStarted();
};
class KKeySequenceRecorderPrivate : public QObject
{
Q_OBJECT
public:
// Copy of QKeySequencePrivate::MaxKeyCount from private header
enum { MaxKeyCount = 4 };
KKeySequenceRecorderPrivate(KKeySequenceRecorder *qq);
void controlModifierlessTimeout();
bool eventFilter(QObject *watched, QEvent *event) override;
void handleKeyPress(QKeyEvent *event);
void handleKeyRelease(QKeyEvent *event);
void finishRecording();
void receivedRecording();
KKeySequenceRecorder *q;
QKeySequence m_currentKeySequence;
QKeySequence m_previousKeySequence;
QPointer<QWindow> m_window;
bool m_isRecording;
bool m_multiKeyShortcutsAllowed;
bool m_modifierlessAllowed;
bool m_modifierOnlyAllowed = false;
Qt::KeyboardModifiers m_currentModifiers;
QTimer m_modifierlessTimer;
std::unique_ptr<ShortcutInhibition> m_inhibition;
// For use in modifier only shortcuts
Qt::KeyboardModifiers m_lastPressedModifiers;
bool m_isReleasingModifierOnly = false;
std::chrono::nanoseconds m_modifierFirstReleaseTime;
};
constexpr Qt::KeyboardModifiers modifierMask = Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier | Qt::KeypadModifier;
// Copied here from KKeyServer
static bool isShiftAsModifierAllowed(int keyQt)
{
// remove any modifiers
keyQt &= ~Qt::KeyboardModifierMask;
// Shift only works as a modifier with certain keys. It's not possible
// to enter the SHIFT+5 key sequence for me because this is handled as
// '%' by qt on my keyboard.
// The working keys are all hardcoded here :-(
if (keyQt >= Qt::Key_F1 && keyQt <= Qt::Key_F35) {
return true;
}
if (QChar::isLetter(keyQt)) {
return true;
}
switch (keyQt) {
case Qt::Key_Return:
case Qt::Key_Space:
case Qt::Key_Backspace:
case Qt::Key_Tab:
case Qt::Key_Backtab:
case Qt::Key_Escape:
case Qt::Key_Print:
case Qt::Key_ScrollLock:
case Qt::Key_Pause:
case Qt::Key_PageUp:
case Qt::Key_PageDown:
case Qt::Key_Insert:
case Qt::Key_Delete:
case Qt::Key_Home:
case Qt::Key_End:
case Qt::Key_Up:
case Qt::Key_Down:
case Qt::Key_Left:
case Qt::Key_Right:
case Qt::Key_Enter:
case Qt::Key_SysReq:
case Qt::Key_CapsLock:
case Qt::Key_NumLock:
case Qt::Key_Help:
case Qt::Key_Back:
case Qt::Key_Forward:
case Qt::Key_Stop:
case Qt::Key_Refresh:
case Qt::Key_Favorites:
case Qt::Key_LaunchMedia:
case Qt::Key_OpenUrl:
case Qt::Key_HomePage:
case Qt::Key_Search:
case Qt::Key_VolumeDown:
case Qt::Key_VolumeMute:
case Qt::Key_VolumeUp:
case Qt::Key_BassBoost:
case Qt::Key_BassUp:
case Qt::Key_BassDown:
case Qt::Key_TrebleUp:
case Qt::Key_TrebleDown:
case Qt::Key_MediaPlay:
case Qt::Key_MediaStop:
case Qt::Key_MediaPrevious:
case Qt::Key_MediaNext:
case Qt::Key_MediaRecord:
case Qt::Key_MediaPause:
case Qt::Key_MediaTogglePlayPause:
case Qt::Key_LaunchMail:
case Qt::Key_Calculator:
case Qt::Key_Memo:
case Qt::Key_ToDoList:
case Qt::Key_Calendar:
case Qt::Key_PowerDown:
case Qt::Key_ContrastAdjust:
case Qt::Key_Standby:
case Qt::Key_MonBrightnessUp:
case Qt::Key_MonBrightnessDown:
case Qt::Key_KeyboardLightOnOff:
case Qt::Key_KeyboardBrightnessUp:
case Qt::Key_KeyboardBrightnessDown:
case Qt::Key_PowerOff:
case Qt::Key_WakeUp:
case Qt::Key_Eject:
case Qt::Key_ScreenSaver:
case Qt::Key_WWW:
case Qt::Key_Sleep:
case Qt::Key_LightBulb:
case Qt::Key_Shop:
case Qt::Key_History:
case Qt::Key_AddFavorite:
case Qt::Key_HotLinks:
case Qt::Key_BrightnessAdjust:
case Qt::Key_Finance:
case Qt::Key_Community:
case Qt::Key_AudioRewind:
case Qt::Key_BackForward:
case Qt::Key_ApplicationLeft:
case Qt::Key_ApplicationRight:
case Qt::Key_Book:
case Qt::Key_CD:
case Qt::Key_Clear:
case Qt::Key_ClearGrab:
case Qt::Key_Close:
case Qt::Key_Copy:
case Qt::Key_Cut:
case Qt::Key_Display:
case Qt::Key_DOS:
case Qt::Key_Documents:
case Qt::Key_Excel:
case Qt::Key_Explorer:
case Qt::Key_Game:
case Qt::Key_Go:
case Qt::Key_iTouch:
case Qt::Key_LogOff:
case Qt::Key_Market:
case Qt::Key_Meeting:
case Qt::Key_MenuKB:
case Qt::Key_MenuPB:
case Qt::Key_MySites:
case Qt::Key_News:
case Qt::Key_OfficeHome:
case Qt::Key_Option:
case Qt::Key_Paste:
case Qt::Key_Phone:
case Qt::Key_Reply:
case Qt::Key_Reload:
case Qt::Key_RotateWindows:
case Qt::Key_RotationPB:
case Qt::Key_RotationKB:
case Qt::Key_Save:
case Qt::Key_Send:
case Qt::Key_Spell:
case Qt::Key_SplitScreen:
case Qt::Key_Support:
case Qt::Key_TaskPane:
case Qt::Key_Terminal:
case Qt::Key_Tools:
case Qt::Key_Travel:
case Qt::Key_Video:
case Qt::Key_Word:
case Qt::Key_Xfer:
case Qt::Key_ZoomIn:
case Qt::Key_ZoomOut:
case Qt::Key_Away:
case Qt::Key_Messenger:
case Qt::Key_WebCam:
case Qt::Key_MailForward:
case Qt::Key_Pictures:
case Qt::Key_Music:
case Qt::Key_Battery:
case Qt::Key_Bluetooth:
case Qt::Key_WLAN:
case Qt::Key_UWB:
case Qt::Key_AudioForward:
case Qt::Key_AudioRepeat:
case Qt::Key_AudioRandomPlay:
case Qt::Key_Subtitle:
case Qt::Key_AudioCycleTrack:
case Qt::Key_Time:
case Qt::Key_Select:
case Qt::Key_View:
case Qt::Key_TopMenu:
case Qt::Key_Suspend:
case Qt::Key_Hibernate:
case Qt::Key_Launch0:
case Qt::Key_Launch1:
case Qt::Key_Launch2:
case Qt::Key_Launch3:
case Qt::Key_Launch4:
case Qt::Key_Launch5:
case Qt::Key_Launch6:
case Qt::Key_Launch7:
case Qt::Key_Launch8:
case Qt::Key_Launch9:
case Qt::Key_LaunchA:
case Qt::Key_LaunchB:
case Qt::Key_LaunchC:
case Qt::Key_LaunchD:
case Qt::Key_LaunchE:
case Qt::Key_LaunchF:
case Qt::Key_Shift:
case Qt::Key_Control:
case Qt::Key_Meta:
case Qt::Key_Alt:
case Qt::Key_Super_L:
case Qt::Key_Super_R:
return true;
default:
return false;
}
}
static bool isOkWhenModifierless(int key)
{
// this whole function is a hack, but especially the first line of code
if (QKeySequence(key).toString().length() == 1) {
return false;
}
switch (key) {
case Qt::Key_Return:
case Qt::Key_Space:
case Qt::Key_Tab:
case Qt::Key_Backtab: // does this ever happen?
case Qt::Key_Backspace:
case Qt::Key_Delete:
return false;
default:
return true;
}
}
static QKeySequence appendToSequence(const QKeySequence &sequence, int key)
{
if (sequence.count() >= KKeySequenceRecorderPrivate::MaxKeyCount) {
qCWarning(KGUIADDONS_LOG) << "Cannot append to a key to a sequence which is already of length" << sequence.count();
return sequence;
}
std::array<int, KKeySequenceRecorderPrivate::MaxKeyCount> keys{sequence[0].toCombined(),
sequence[1].toCombined(),
sequence[2].toCombined(),
sequence[3].toCombined()};
// When the user presses Mod(s)+Alt+Print, the SysReq event is fired only
// when the Alt key is released. Before we get the Mod(s)+SysReq event, we
// first get a Mod(s)+Alt event, which we have to ignore.
// Known limitation: only works when the Alt key is released before the Mod(s) key(s).
if ((key & ~Qt::KeyboardModifierMask) == Qt::Key_SysReq) {
key = Qt::Key_Print | (key & Qt::KeyboardModifierMask) | Qt::AltModifier;
if (sequence.count() > 0 && (sequence[sequence.count() - 1].toCombined() & ~Qt::KeyboardModifierMask) == Qt::Key_Alt) {
keys[sequence.count() - 1] = key;
return QKeySequence(keys[0], keys[1], keys[2], keys[3]);
}
}
keys[sequence.count()] = key;
return QKeySequence(keys[0], keys[1], keys[2], keys[3]);
}
KKeySequenceRecorderPrivate::KKeySequenceRecorderPrivate(KKeySequenceRecorder *qq)
: QObject(qq)
, q(qq)
{
}
void KKeySequenceRecorderPrivate::controlModifierlessTimeout()
{
if (m_currentKeySequence != 0 && !m_currentModifiers) {
// No modifier key pressed currently. Start the timeout
m_modifierlessTimer.start(600);
} else {
// A modifier is pressed. Stop the timeout
m_modifierlessTimer.stop();
}
}
bool KKeySequenceRecorderPrivate::eventFilter(QObject *watched, QEvent *event)
{
if (!m_isRecording) {
return QObject::eventFilter(watched, event);
}
if (event->type() == QEvent::ShortcutOverride || event->type() == QEvent::ContextMenu) {
event->accept();
return true;
}
if (event->type() == QEvent::KeyRelease) {
handleKeyRelease(static_cast<QKeyEvent *>(event));
return true;
}
if (event->type() == QEvent::KeyPress) {
handleKeyPress(static_cast<QKeyEvent *>(event));
return true;
}
return QObject::eventFilter(watched, event);
}
static Qt::KeyboardModifiers keyToModifier(int key)
{
switch (key) {
case Qt::Key_Meta:
case Qt::Key_Super_L:
case Qt::Key_Super_R:
// Qt doesn't properly recognize Super_L/Super_R as MetaModifier
return Qt::MetaModifier;
case Qt::Key_Shift:
return Qt::ShiftModifier;
case Qt::Key_Control:
return Qt::ControlModifier;
case Qt::Key_Alt:
return Qt::AltModifier;
default:
return Qt::NoModifier;
}
}
void KKeySequenceRecorderPrivate::handleKeyPress(QKeyEvent *event)
{
m_isReleasingModifierOnly = false;
m_currentModifiers = event->modifiers() & modifierMask;
int key = event->key();
switch (key) {
case -1:
qCWarning(KGUIADDONS_LOG) << "Got unknown key";
// Old behavior was to stop recording here instead of continuing like this
return;
case 0:
break;
case Qt::Key_AltGr:
// or else we get unicode salad
break;
case Qt::Key_Super_L:
case Qt::Key_Super_R:
case Qt::Key_Shift:
case Qt::Key_Control:
case Qt::Key_Alt:
case Qt::Key_Meta:
m_currentModifiers |= keyToModifier(key);
m_lastPressedModifiers = m_currentModifiers;
controlModifierlessTimeout();
Q_EMIT q->currentKeySequenceChanged();
break;
default:
m_lastPressedModifiers = Qt::NoModifier;
if (m_currentKeySequence.count() == 0 && !(m_currentModifiers & ~Qt::ShiftModifier)) {
// It's the first key and no modifier pressed. Check if this is allowed
if (!(isOkWhenModifierless(key) || m_modifierlessAllowed)) {
// No it's not
return;
}
}
// We now have a valid key press.
if ((key == Qt::Key_Backtab) && (m_currentModifiers & Qt::ShiftModifier)) {
key = QKeyCombination(Qt::Key_Tab).toCombined() | m_currentModifiers;
} else if (isShiftAsModifierAllowed(key)) {
key |= m_currentModifiers;
} else {
key |= (m_currentModifiers & ~Qt::ShiftModifier);
}
m_currentKeySequence = appendToSequence(m_currentKeySequence, key);
Q_EMIT q->currentKeySequenceChanged();
// Now we are in a critical region (race), where recording is still
// ongoing, but key sequence has already changed (potentially) to the
// longest. But we still want currentKeySequenceChanged to trigger
// before gotKeySequence, so there's only so much we can do about it.
if ((!m_multiKeyShortcutsAllowed) || (m_currentKeySequence.count() == MaxKeyCount)) {
finishRecording();
break;
}
controlModifierlessTimeout();
}
event->accept();
}
// Turn a bunch of modifiers into mods + key
// so that the ordering is always Meta + Ctrl + Alt + Shift
static int prettifyModifierOnly(Qt::KeyboardModifiers modifier)
{
if (modifier & Qt::ShiftModifier) {
return (Qt::Key_Shift | (modifier & ~Qt::ShiftModifier)).toCombined();
} else if (modifier & Qt::AltModifier) {
return (Qt::Key_Alt | (modifier & ~Qt::AltModifier)).toCombined();
} else if (modifier & Qt::ControlModifier) {
return (Qt::Key_Control | (modifier & ~Qt::ControlModifier)).toCombined();
} else if (modifier & Qt::MetaModifier) {
return (Qt::Key_Meta | (modifier & ~Qt::MetaModifier)).toCombined();
} else {
return Qt::Key(0);
}
}
void KKeySequenceRecorderPrivate::handleKeyRelease(QKeyEvent *event)
{
Qt::KeyboardModifiers modifiers = event->modifiers() & modifierMask;
switch (event->key()) {
case -1:
return;
case Qt::Key_Super_L:
case Qt::Key_Super_R:
case Qt::Key_Meta:
case Qt::Key_Shift:
case Qt::Key_Control:
case Qt::Key_Alt:
modifiers &= ~keyToModifier(event->key());
}
if ((modifiers & m_currentModifiers) < m_currentModifiers) {
constexpr auto releaseTimeout = std::chrono::milliseconds(200);
const auto currentTime = std::chrono::steady_clock::now().time_since_epoch();
if (!m_isReleasingModifierOnly) {
m_isReleasingModifierOnly = true;
m_modifierFirstReleaseTime = currentTime;
}
if (m_modifierOnlyAllowed && !modifiers && (currentTime - m_modifierFirstReleaseTime) < releaseTimeout) {
m_currentKeySequence = appendToSequence(m_currentKeySequence, prettifyModifierOnly(m_lastPressedModifiers));
m_lastPressedModifiers = Qt::NoModifier;
}
m_currentModifiers = modifiers;
Q_EMIT q->currentKeySequenceChanged();
if (m_currentKeySequence.count() == (m_multiKeyShortcutsAllowed ? MaxKeyCount : 1)) {
finishRecording();
}
controlModifierlessTimeout();
};
}
void KKeySequenceRecorderPrivate::receivedRecording()
{
m_modifierlessTimer.stop();
m_isRecording = false;
m_currentModifiers = Qt::NoModifier;
m_lastPressedModifiers = Qt::NoModifier;
m_isReleasingModifierOnly = false;
if (m_inhibition) {
m_inhibition->disableInhibition();
}
QObject::disconnect(KKeySequenceRecorderGlobal::self(), &KKeySequenceRecorderGlobal::sequenceRecordingStarted, q, &KKeySequenceRecorder::cancelRecording);
Q_EMIT q->recordingChanged();
}
void KKeySequenceRecorderPrivate::finishRecording()
{
receivedRecording();
Q_EMIT q->gotKeySequence(m_currentKeySequence);
}
KKeySequenceRecorder::KKeySequenceRecorder(QWindow *window, QObject *parent)
: QObject(parent)
, d(new KKeySequenceRecorderPrivate(this))
{
d->m_isRecording = false;
d->m_modifierlessAllowed = false;
d->m_multiKeyShortcutsAllowed = true;
setWindow(window);
connect(&d->m_modifierlessTimer, &QTimer::timeout, d.get(), &KKeySequenceRecorderPrivate::finishRecording);
}
KKeySequenceRecorder::~KKeySequenceRecorder() noexcept
{
if (d->m_inhibition && d->m_inhibition->shortcutsAreInhibited()) {
d->m_inhibition->disableInhibition();
}
}
void KKeySequenceRecorder::startRecording()
{
d->m_previousKeySequence = d->m_currentKeySequence;
KKeySequenceRecorderGlobal::self()->sequenceRecordingStarted();
connect(KKeySequenceRecorderGlobal::self(),
&KKeySequenceRecorderGlobal::sequenceRecordingStarted,
this,
&KKeySequenceRecorder::cancelRecording,
Qt::UniqueConnection);
if (!d->m_window) {
qCWarning(KGUIADDONS_LOG) << "Cannot record without a window";
return;
}
d->m_isRecording = true;
d->m_currentKeySequence = QKeySequence();
if (d->m_inhibition) {
d->m_inhibition->enableInhibition();
}
Q_EMIT recordingChanged();
Q_EMIT currentKeySequenceChanged();
}
void KKeySequenceRecorder::cancelRecording()
{
setCurrentKeySequence(d->m_previousKeySequence);
d->receivedRecording();
Q_ASSERT(!isRecording());
}
bool KKeySequenceRecorder::isRecording() const
{
return d->m_isRecording;
}
QKeySequence KKeySequenceRecorder::currentKeySequence() const
{
// We need a check for count() here because there's a race between the
// state of recording and a length of currentKeySequence.
if (d->m_isRecording && d->m_currentKeySequence.count() < KKeySequenceRecorderPrivate::MaxKeyCount) {
return appendToSequence(d->m_currentKeySequence, d->m_currentModifiers);
} else {
return d->m_currentKeySequence;
}
}
void KKeySequenceRecorder::setCurrentKeySequence(const QKeySequence &sequence)
{
if (d->m_currentKeySequence == sequence) {
return;
}
d->m_currentKeySequence = sequence;
Q_EMIT currentKeySequenceChanged();
}
QWindow *KKeySequenceRecorder::window() const
{
return d->m_window;
}
void KKeySequenceRecorder::setWindow(QWindow *window)
{
if (window == d->m_window) {
return;
}
if (d->m_window) {
d->m_window->removeEventFilter(d.get());
}
if (window) {
window->installEventFilter(d.get());
qCDebug(KGUIADDONS_LOG) << "listening for events in" << window;
}
if (qGuiApp->platformName() == QLatin1String("wayland")) {
#ifdef WITH_WAYLAND
d->m_inhibition.reset(new WaylandInhibition(window));
#endif
} else {
d->m_inhibition.reset(new KeyboardGrabber(window));
}
d->m_window = window;
Q_EMIT windowChanged();
}
bool KKeySequenceRecorder::multiKeyShortcutsAllowed() const
{
return d->m_multiKeyShortcutsAllowed;
}
void KKeySequenceRecorder::setMultiKeyShortcutsAllowed(bool allowed)
{
if (allowed == d->m_multiKeyShortcutsAllowed) {
return;
}
d->m_multiKeyShortcutsAllowed = allowed;
Q_EMIT multiKeyShortcutsAllowedChanged();
}
bool KKeySequenceRecorder::modifierlessAllowed() const
{
return d->m_modifierlessAllowed;
}
void KKeySequenceRecorder::setModifierlessAllowed(bool allowed)
{
if (allowed == d->m_modifierlessAllowed) {
return;
}
d->m_modifierlessAllowed = allowed;
Q_EMIT modifierlessAllowedChanged();
}
bool KKeySequenceRecorder::modifierOnlyAllowed() const
{
return d->m_modifierOnlyAllowed;
}
void KKeySequenceRecorder::setModifierOnlyAllowed(bool allowed)
{
if (allowed == d->m_modifierOnlyAllowed) {
return;
}
d->m_modifierOnlyAllowed = allowed;
Q_EMIT modifierOnlyAllowedChanged();
}
#include "kkeysequencerecorder.moc"
#include "moc_kkeysequencerecorder.cpp"
@@ -0,0 +1,156 @@
/*
SPDX-FileCopyrightText: 2001, 2002 Ellis Whitehead <ellis@kde.org>
SPDX-FileCopyrightText: 2007 Andreas Hartmetz <ahartmetz@gmail.com>
SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KKEYSEQUENCERECORDER_H
#define KKEYSEQUENCERECORDER_H
#include <kguiaddons_export.h>
#include <QKeySequence>
#include <QObject>
#include <QWindow>
#include <memory>
class KKeySequenceRecorderPrivate;
/**
* @class KKeySequenceRecorder kkeysequencerecorder.h KKeySequenceRecorder
*
* @short Record a QKeySequence by listening to key events in a window.
*
* After calling startRecording key events in the set window will be captured until a valid
* QKeySequence has been recorded and gotKeySequence is emitted. See multiKeyShortcutsAllowed and
* modifierlessAllowed for what constitutes a valid key sequence.
*
* During recording any shortcuts are inhibited and cannot be triggered. Either by using the
* <a href="https://cgit.freedesktop.org/wayland/wayland-protocols/tree/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml">
* keyboard-shortcuts-inhibit protocol </a> on Wayland or grabbing the keyboard.
*
* For graphical elements that record key sequences and can optionally perform conflict checking
* against existing shortcuts see KKeySequenceWidget and KeySequenceItem.
*
* Porting from KF5 to KF6:
*
* The class KeySequenceRecorder was renamed to KKeySequenceRecorder.
*
* @see KKeySequenceWidget, KeySequenceItem
* @since 6.0
*/
class KGUIADDONS_EXPORT KKeySequenceRecorder : public QObject
{
Q_OBJECT
/**
* Whether key events are currently recorded
*/
Q_PROPERTY(bool isRecording READ isRecording NOTIFY recordingChanged)
/**
* The recorded key sequence.
* After construction this is empty.
*
* During recording it is continuously updated with the newest user input.
*
* After recording it contains the last recorded QKeySequence
*/
Q_PROPERTY(QKeySequence currentKeySequence READ currentKeySequence WRITE setCurrentKeySequence NOTIFY currentKeySequenceChanged)
/**
* The window in which the key events are happening that should be recorded
*/
Q_PROPERTY(QWindow *window READ window WRITE setWindow NOTIFY windowChanged)
/**
* If key presses of "plain" keys without a modifier are considered to be a valid finished
* key combination.
* Plain keys include letter and symbol keys and text editing keys (Return, Space, Tab,
* Backspace, Delete). Other keys like F1, Cursor keys, Insert, PageDown will always work.
*
* By default this is `false`.
*/
Q_PROPERTY(bool modifierlessAllowed READ modifierlessAllowed WRITE setModifierlessAllowed NOTIFY modifierlessAllowedChanged)
/** Controls the amount of key combinations that are captured until recording stops and gotKeySequence
* is emitted.
* By default this is `true` and "Emacs-style" key sequences are recorded. Recording does not
* stop until four valid key combination have been recorded. Afterwards `currentKeySequence().count()`
* will be 4.
*
* Otherwise only one key combination is recorded before gotKeySequence is emitted with a
* QKeySequence with a `count()` of 1.
* @see QKeySequence
*/
Q_PROPERTY(bool multiKeyShortcutsAllowed READ multiKeyShortcutsAllowed WRITE setMultiKeyShortcutsAllowed NOTIFY multiKeyShortcutsAllowedChanged)
/**
* It makes it acceptable for the key sequence to be just a modifier (e.g. Shift or Control)
*
* By default, if only a modifier is pressed and then released, the component will remain waiting for the sequence.
* When enabled, it will take the modifier key as the key sequence.
*
* By default this is `false`.
*/
Q_PROPERTY(bool modifierOnlyAllowed READ modifierOnlyAllowed WRITE setModifierOnlyAllowed NOTIFY modifierOnlyAllowedChanged)
public:
/**
* Constructor.
*
* @par window The window whose key events will be recorded.
* @see window
*/
explicit KKeySequenceRecorder(QWindow *window, QObject *parent = nullptr);
~KKeySequenceRecorder() override;
/**
* Start recording.
* Calling startRecording when window() is `nullptr` has no effect.
*/
Q_INVOKABLE void startRecording();
bool isRecording() const;
QKeySequence currentKeySequence() const;
void setCurrentKeySequence(const QKeySequence &sequence);
QWindow *window() const;
void setWindow(QWindow *window);
bool multiKeyShortcutsAllowed() const;
void setMultiKeyShortcutsAllowed(bool allowed);
void setModifierlessAllowed(bool allowed);
bool modifierlessAllowed() const;
void setModifierOnlyAllowed(bool allowed);
bool modifierOnlyAllowed() const;
public Q_SLOTS:
/**
* Stops the recording session
*/
void cancelRecording();
Q_SIGNALS:
/**
* This signal is emitted when a key sequence has been recorded.
*
* Compared to currentKeySequenceChanged and currentKeySequence this is signal is not emitted
* continuously during recording but only after recording has finished.
*/
void gotKeySequence(const QKeySequence &keySequence);
void recordingChanged();
void windowChanged();
void currentKeySequenceChanged();
void multiKeyShortcutsAllowedChanged();
void modifierlessAllowedChanged();
void modifierOnlyAllowedChanged();
private:
friend class KKeySequenceRecorderPrivate;
std::unique_ptr<KKeySequenceRecorderPrivate> const d;
};
#endif
@@ -0,0 +1,22 @@
/*
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>
*/
#ifndef SHORTCUTINHIBITION_H
#define SHORTCUTINHIBITION_H
class QWindow;
class ShortcutInhibition
{
public:
virtual ~ShortcutInhibition()
{
}
virtual void enableInhibition() = 0;
virtual void disableInhibition() = 0;
virtual bool shortcutsAreInhibited() const = 0;
};
#endif
@@ -0,0 +1,139 @@
/*
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>
*/
#include "waylandinhibition_p.h"
#include "kguiaddons_debug.h"
#include <QDebug>
#include <QGuiApplication>
#include <QSharedPointer>
#include <QWaylandClientExtensionTemplate>
#include <QWindow>
#include <qpa/qplatformwindow_p.h>
#include "qwayland-keyboard-shortcuts-inhibit-unstable-v1.h"
class ShortcutsInhibitor : public QtWayland::zwp_keyboard_shortcuts_inhibitor_v1
{
public:
ShortcutsInhibitor(::zwp_keyboard_shortcuts_inhibitor_v1 *id)
: QtWayland::zwp_keyboard_shortcuts_inhibitor_v1(id)
{
}
~ShortcutsInhibitor() override
{
destroy();
}
void zwp_keyboard_shortcuts_inhibitor_v1_active() override
{
m_active = true;
}
void zwp_keyboard_shortcuts_inhibitor_v1_inactive() override
{
m_active = false;
}
bool isActive() const
{
return m_active;
}
private:
bool m_active = false;
};
class ShortcutsInhibitManager : public QWaylandClientExtensionTemplate<ShortcutsInhibitManager>, public QtWayland::zwp_keyboard_shortcuts_inhibit_manager_v1
{
public:
ShortcutsInhibitManager()
: QWaylandClientExtensionTemplate<ShortcutsInhibitManager>(1)
{
initialize();
}
~ShortcutsInhibitManager() override
{
if (isInitialized()) {
destroy();
}
}
void startInhibition(QWindow *window)
{
if (m_inhibitions.contains(window)) {
return;
}
auto waylandApp = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();
auto waylandWindow = window->nativeInterface<QNativeInterface::Private::QWaylandWindow>();
if (!waylandApp || !waylandWindow) {
return;
}
auto seat = waylandApp->lastInputSeat();
auto surface = waylandWindow->surface();
if (!seat || !surface) {
return;
}
m_inhibitions[window].reset(new ShortcutsInhibitor(inhibit_shortcuts(surface, seat)));
}
bool isInhibited(QWindow *window) const
{
return m_inhibitions.contains(window);
}
void stopInhibition(QWindow *window)
{
m_inhibitions.remove(window);
}
QHash<QWindow *, QSharedPointer<ShortcutsInhibitor>> m_inhibitions;
};
static std::shared_ptr<ShortcutsInhibitManager> theManager()
{
static std::weak_ptr<ShortcutsInhibitManager> managerInstance;
std::shared_ptr<ShortcutsInhibitManager> ret = managerInstance.lock();
if (!ret) {
ret = std::make_shared<ShortcutsInhibitManager>();
managerInstance = ret;
}
return ret;
}
WaylandInhibition::WaylandInhibition(QWindow *window)
: ShortcutInhibition()
, m_window(window)
, m_manager(theManager())
{
}
WaylandInhibition::~WaylandInhibition() = default;
bool WaylandInhibition::shortcutsAreInhibited() const
{
return m_manager->isInhibited(m_window);
}
void WaylandInhibition::enableInhibition()
{
if (!m_manager->isActive()) {
qCInfo(KGUIADDONS_LOG) << "The compositor does not support the keyboard-shortcuts-inhibit-unstable-v1 protocol. Inhibiting shortcuts will not work.";
return;
}
m_manager->startInhibition(m_window);
}
void WaylandInhibition::disableInhibition()
{
if (!m_manager->isActive()) {
return;
}
m_manager->stopInhibition(m_window);
}
@@ -0,0 +1,30 @@
/*
SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>
*/
#ifndef WAYLANDSHORTCUTINHIBITOR_H
#define WAYLANDSHORTCUTINHIBITOR_H
#include "shortcutinhibition_p.h"
#include <memory>
class ShortcutsInhibitManager;
class ShortcutsInhibitor;
class WaylandInhibition : public ShortcutInhibition
{
public:
explicit WaylandInhibition(QWindow *window);
~WaylandInhibition() override;
bool shortcutsAreInhibited() const override;
void enableInhibition() override;
void disableInhibition() override;
private:
QWindow *const m_window;
std::shared_ptr<ShortcutsInhibitManager> m_manager;
};
#endif
@@ -0,0 +1,60 @@
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "ksystemclipboard.h"
#include "kguiaddons_debug.h"
#include "qtclipboard_p.h"
#include "waylandclipboard_p.h"
#include <QDebug>
#include <QGuiApplication>
#include <QMimeData>
KSystemClipboard *KSystemClipboard::instance()
{
if (!qGuiApp || qGuiApp->closingDown()) {
return nullptr;
}
static KSystemClipboard *systemClipboard = nullptr;
#ifdef WITH_WAYLAND
static bool s_waylandChecked = false;
if (!systemClipboard && qGuiApp->platformName() == QLatin1String("wayland") && !s_waylandChecked) {
WaylandClipboard *waylandClipboard = new WaylandClipboard(qApp);
s_waylandChecked = true;
if (waylandClipboard->isValid()) {
systemClipboard = waylandClipboard;
} else {
delete waylandClipboard;
qCWarning(KGUIADDONS_LOG) << "Could not init WaylandClipboard, falling back to QtClipboard.";
}
}
#endif
if (!systemClipboard) {
systemClipboard = new QtClipboard(qApp);
}
return systemClipboard;
}
QString KSystemClipboard::text(QClipboard::Mode mode)
{
const QMimeData *data = mimeData(mode);
if (data) {
return data->text();
}
return QString();
}
KSystemClipboard::KSystemClipboard(QObject *parent)
: QObject(parent)
{
}
#include "moc_ksystemclipboard.cpp"
@@ -0,0 +1,63 @@
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KSYSTEMCLIPBOARD_H
#define KSYSTEMCLIPBOARD_H
#include <kguiaddons_export.h>
#include <QClipboard>
#include <QObject>
class QMimeData;
/**
* This class mimics QClipboard but unlike QClipboard it will continue
* to get updates even when our window does not have focus.
*
* This may require extra access permissions
*
* @since 5.89
*/
class KGUIADDONS_EXPORT KSystemClipboard : public QObject
{
Q_OBJECT
public:
/**
* Returns a shared global SystemClipboard instance
*/
static KSystemClipboard *instance();
/**
* Sets the clipboard to the new contents
* The clipboard takes ownership of mime
*/
virtual void setMimeData(QMimeData *mime, QClipboard::Mode mode) = 0;
/**
* Clears the current clipboard
*/
virtual void clear(QClipboard::Mode mode) = 0;
/**
* Returns the current mime data received by the clipboard
*/
virtual const QMimeData *mimeData(QClipboard::Mode mode) const = 0;
/**
* Returns the text content of the Clipboard
*
* Similar to QClipboard::text(QClipboard::Mode mode)
*/
QString text(QClipboard::Mode mode);
Q_SIGNALS:
/**
* Emitted when the clipboard changes similar to QClipboard::changed
*/
void changed(QClipboard::Mode mode);
protected:
KSystemClipboard(QObject *parent);
};
#endif
@@ -0,0 +1,31 @@
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "qtclipboard_p.h"
#include <QClipboard>
#include <QGuiApplication>
QtClipboard::QtClipboard(QObject *parent)
: KSystemClipboard(parent)
{
connect(qGuiApp->clipboard(), &QClipboard::changed, this, &QtClipboard::changed);
}
void QtClipboard::setMimeData(QMimeData *mime, QClipboard::Mode mode)
{
qGuiApp->clipboard()->setMimeData(mime, mode);
}
void QtClipboard::clear(QClipboard::Mode mode)
{
qGuiApp->clipboard()->clear(mode);
}
const QMimeData *QtClipboard::mimeData(QClipboard::Mode mode) const
{
return qGuiApp->clipboard()->mimeData(mode);
}
@@ -0,0 +1,21 @@
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef QTCLIPBOARD_H
#define QTCLIPBOARD_H
#include "ksystemclipboard.h"
class QtClipboard : public KSystemClipboard
{
public:
explicit QtClipboard(QObject *parent);
void setMimeData(QMimeData *mime, QClipboard::Mode mode) override;
void clear(QClipboard::Mode mode) override;
const QMimeData *mimeData(QClipboard::Mode mode) const override;
};
#endif
@@ -0,0 +1,44 @@
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <QDebug>
#include <QGuiApplication>
#include <QImage>
#include <QMimeData>
#include "../systemclipboard/ksystemclipboard.h"
int main(int argc, char **argv)
{
QGuiApplication app(argc, argv);
auto clip = KSystemClipboard::instance();
QObject::connect(clip, &KSystemClipboard::changed, &app, [clip](QClipboard::Mode mode) {
if (mode != QClipboard::Clipboard) {
return;
}
auto dbg = qDebug();
dbg << "New clipboard content: ";
const QMimeData *mime = clip->mimeData(QClipboard::Clipboard);
if (mime) {
if (mime->hasText()) {
dbg << "text data:" << mime->text();
} else if (mime->hasImage()) {
const QImage image = qvariant_cast<QImage>(mime->imageData());
dbg << "image data: " << image.size();
} else {
dbg << "data: " << mime->formats();
}
} else {
dbg << "[empty]";
}
});
qDebug() << "Watching for new clipboard content...";
return app.exec();
}
@@ -0,0 +1,706 @@
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-FileCopyrightText: 2021 Méven Car <meven.car@enioka.com>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "waylandclipboard_p.h"
#include <QBuffer>
#include <QFile>
#include <QGuiApplication>
#include <QImageReader>
#include <QImageWriter>
#include <QMimeData>
#include <QPointer>
#include <QWaylandClientExtension>
#include <QWindow>
#include <QtWaylandClientVersion>
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include "qwayland-wayland.h"
#include "qwayland-wlr-data-control-unstable-v1.h"
static inline QString applicationQtXImageLiteral()
{
return QStringLiteral("application/x-qt-image");
}
// copied from https://code.woboq.org/qt5/qtbase/src/gui/kernel/qinternalmimedata.cpp.html
static QString utf8Text()
{
return QStringLiteral("text/plain;charset=utf-8");
}
static QStringList imageMimeFormats(const QList<QByteArray> &imageFormats)
{
QStringList formats;
formats.reserve(imageFormats.size());
for (const auto &format : imageFormats)
formats.append(QLatin1String("image/") + QLatin1String(format.toLower()));
// put png at the front because it is best
int pngIndex = formats.indexOf(QLatin1String("image/png"));
if (pngIndex != -1 && pngIndex != 0)
formats.move(pngIndex, 0);
return formats;
}
static inline QStringList imageReadMimeFormats()
{
return imageMimeFormats(QImageReader::supportedImageFormats());
}
static inline QStringList imageWriteMimeFormats()
{
return imageMimeFormats(QImageWriter::supportedImageFormats());
}
// end copied
class DataControlDeviceManager : public QWaylandClientExtensionTemplate<DataControlDeviceManager>, public QtWayland::zwlr_data_control_manager_v1
{
Q_OBJECT
public:
DataControlDeviceManager()
: QWaylandClientExtensionTemplate<DataControlDeviceManager>(2)
{
}
void instantiate()
{
initialize();
}
~DataControlDeviceManager()
{
if (isInitialized()) {
destroy();
}
}
};
class DataControlOffer : public QMimeData, public QtWayland::zwlr_data_control_offer_v1
{
Q_OBJECT
public:
DataControlOffer(struct ::zwlr_data_control_offer_v1 *id)
: QtWayland::zwlr_data_control_offer_v1(id)
{
}
~DataControlOffer()
{
destroy();
}
QStringList formats() const override
{
return m_receivedFormats;
}
bool containsImageData() const
{
if (m_receivedFormats.contains(applicationQtXImageLiteral())) {
return true;
}
const auto formats = imageReadMimeFormats();
for (const auto &receivedFormat : m_receivedFormats) {
if (formats.contains(receivedFormat)) {
return true;
}
}
return false;
}
bool hasFormat(const QString &mimeType) const override
{
if (mimeType == QStringLiteral("text/plain") && m_receivedFormats.contains(utf8Text())) {
return true;
}
if (m_receivedFormats.contains(mimeType)) {
return true;
}
// If we have image data
if (containsImageData()) {
// is the requested output mimeType supported ?
const QStringList imageFormats = imageWriteMimeFormats();
for (const QString &imageFormat : imageFormats) {
if (imageFormat == mimeType) {
return true;
}
}
if (mimeType == applicationQtXImageLiteral()) {
return true;
}
}
return false;
}
protected:
void zwlr_data_control_offer_v1_offer(const QString &mime_type) override
{
if (!m_receivedFormats.contains(mime_type)) {
m_receivedFormats << mime_type;
}
}
QVariant retrieveData(const QString &mimeType, QMetaType type) const override;
private:
/** reads data from a file descriptor with a timeout of 1 second
* true if data is read successfully
*/
static bool readData(int fd, QByteArray &data);
QStringList m_receivedFormats;
mutable QHash<QString, QVariant> m_data;
};
QVariant DataControlOffer::retrieveData(const QString &mimeType, QMetaType type) const
{
Q_UNUSED(type);
auto it = m_data.constFind(mimeType);
if (it != m_data.constEnd())
return *it;
QString mime;
if (!m_receivedFormats.contains(mimeType)) {
if (mimeType == QStringLiteral("text/plain") && m_receivedFormats.contains(utf8Text())) {
mime = utf8Text();
} else if (mimeType == applicationQtXImageLiteral()) {
const auto writeFormats = imageWriteMimeFormats();
for (const auto &receivedFormat : m_receivedFormats) {
if (writeFormats.contains(receivedFormat)) {
mime = receivedFormat;
break;
}
}
if (mime.isEmpty()) {
// default exchange format
mime = QStringLiteral("image/png");
}
}
if (mime.isEmpty()) {
return QVariant();
}
} else {
mime = mimeType;
}
int pipeFds[2];
if (pipe(pipeFds) != 0) {
return QVariant();
}
auto t = const_cast<DataControlOffer *>(this);
t->receive(mime, pipeFds[1]);
close(pipeFds[1]);
/*
* Ideally we need to introduce a non-blocking QMimeData object
* Or a non-blocking constructor to QMimeData with the mimetypes that are relevant
*
* However this isn't actually any worse than X.
*/
auto waylandApp = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();
auto display = waylandApp->display();
wl_display_flush(display);
QFile readPipe;
if (readPipe.open(pipeFds[0], QIODevice::ReadOnly)) {
QByteArray data;
if (readData(pipeFds[0], data)) {
close(pipeFds[0]);
if (mimeType == applicationQtXImageLiteral()) {
QImage img = QImage::fromData(data, mime.mid(mime.indexOf(QLatin1Char('/')) + 1).toLatin1().toUpper().data());
if (!img.isNull()) {
m_data.insert(mimeType, img);
return img;
}
} else if (data.size() > 1 && mimeType == u"text/uri-list") {
const auto urls = data.split('\n');
QVariantList list;
list.reserve(urls.size());
for (const QByteArray &s : urls) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
if (QUrl url(QUrl::fromEncoded(QByteArrayView(s).trimmed())); url.isValid()) {
#else
if (QUrl url(QUrl::fromEncoded(QByteArrayView(s).trimmed().toByteArray())); url.isValid()) {
#endif
list.emplace_back(std::move(url));
}
}
m_data.insert(mimeType, list);
return list;
}
m_data.insert(mimeType, data);
return data;
}
close(pipeFds[0]);
}
return QVariant();
}
bool DataControlOffer::readData(int fd, QByteArray &data)
{
pollfd pfds[1];
pfds[0].fd = fd;
pfds[0].events = POLLIN;
while (true) {
const int ready = poll(pfds, 1, 1000);
if (ready < 0) {
if (errno != EINTR) {
qWarning("DataControlOffer: poll() failed: %s", strerror(errno));
return false;
}
} else if (ready == 0) {
qWarning("DataControlOffer: timeout reading from pipe");
return false;
} else {
char buf[4096];
int n = read(fd, buf, sizeof buf);
if (n < 0) {
qWarning("DataControlOffer: read() failed: %s", strerror(errno));
return false;
} else if (n == 0) {
return true;
} else if (n > 0) {
data.append(buf, n);
}
}
}
}
class DataControlSource : public QObject, public QtWayland::zwlr_data_control_source_v1
{
Q_OBJECT
public:
DataControlSource(struct ::zwlr_data_control_source_v1 *id, QMimeData *mimeData);
DataControlSource() = default;
~DataControlSource()
{
destroy();
}
QMimeData *mimeData()
{
return m_mimeData.get();
}
std::unique_ptr<QMimeData> releaseMimeData()
{
return std::move(m_mimeData);
}
Q_SIGNALS:
void cancelled();
protected:
void zwlr_data_control_source_v1_send(const QString &mime_type, int32_t fd) override;
void zwlr_data_control_source_v1_cancelled() override;
private:
std::unique_ptr<QMimeData> m_mimeData;
};
DataControlSource::DataControlSource(struct ::zwlr_data_control_source_v1 *id, QMimeData *mimeData)
: QtWayland::zwlr_data_control_source_v1(id)
, m_mimeData(mimeData)
{
const auto formats = mimeData->formats();
for (const QString &format : formats) {
offer(format);
}
if (mimeData->hasText()) {
// ensure GTK applications get this mimetype to avoid them discarding the offer
offer(QStringLiteral("text/plain;charset=utf-8"));
}
if (mimeData->hasImage()) {
const QStringList imageFormats = imageWriteMimeFormats();
for (const QString &imageFormat : imageFormats) {
if (!formats.contains(imageFormat)) {
offer(imageFormat);
}
}
}
}
void DataControlSource::zwlr_data_control_source_v1_send(const QString &mime_type, int32_t fd)
{
QString send_mime_type = mime_type;
if (send_mime_type == QStringLiteral("text/plain;charset=utf-8")) {
// if we get a request on the fallback mime, send the data from the original mime type
send_mime_type = QStringLiteral("text/plain");
}
QByteArray ba;
if (m_mimeData->hasImage()) {
// adapted from QInternalMimeData::renderDataHelper
if (mime_type == applicationQtXImageLiteral()) {
QImage image = qvariant_cast<QImage>(m_mimeData->imageData());
QBuffer buf(&ba);
buf.open(QBuffer::WriteOnly);
// would there not be PNG ??
image.save(&buf, "PNG");
} else if (mime_type.startsWith(QLatin1String("image/"))) {
QImage image = qvariant_cast<QImage>(m_mimeData->imageData());
QBuffer buf(&ba);
buf.open(QBuffer::WriteOnly);
image.save(&buf, mime_type.mid(mime_type.indexOf(QLatin1Char('/')) + 1).toLatin1().toUpper().data());
}
// end adapted
} else {
ba = m_mimeData->data(send_mime_type);
}
// Create a sigpipe handler that does nothing, or clients may be forced to terminate
// if the pipe is closed in the other end.
struct sigaction action, oldAction;
action.sa_handler = SIG_IGN;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGPIPE, &action, &oldAction);
write(fd, ba.constData(), ba.size());
sigaction(SIGPIPE, &oldAction, nullptr);
close(fd);
}
void DataControlSource::zwlr_data_control_source_v1_cancelled()
{
Q_EMIT cancelled();
}
class DataControlDevice : public QObject, public QtWayland::zwlr_data_control_device_v1
{
Q_OBJECT
public:
DataControlDevice(struct ::zwlr_data_control_device_v1 *id)
: QtWayland::zwlr_data_control_device_v1(id)
{
}
~DataControlDevice()
{
destroy();
}
void setSelection(std::unique_ptr<DataControlSource> selection);
QMimeData *receivedSelection()
{
return m_receivedSelection.get();
}
QMimeData *selection()
{
return m_selection ? m_selection->mimeData() : nullptr;
}
void setPrimarySelection(std::unique_ptr<DataControlSource> selection);
QMimeData *receivedPrimarySelection()
{
return m_receivedPrimarySelection.get();
}
QMimeData *primarySelection()
{
return m_primarySelection ? m_primarySelection->mimeData() : nullptr;
}
Q_SIGNALS:
void receivedSelectionChanged();
void selectionChanged();
void receivedPrimarySelectionChanged();
void primarySelectionChanged();
protected:
void zwlr_data_control_device_v1_data_offer(struct ::zwlr_data_control_offer_v1 *id) override
{
// this will become memory managed when we retrieve the selection event
// a compositor calling data_offer without doing that would be a bug
new DataControlOffer(id);
}
void zwlr_data_control_device_v1_selection(struct ::zwlr_data_control_offer_v1 *id) override
{
if (!id) {
m_receivedSelection.reset();
} else {
auto derivated = QtWayland::zwlr_data_control_offer_v1::fromObject(id);
auto offer = dynamic_cast<DataControlOffer *>(derivated); // dynamic because of the dual inheritance
m_receivedSelection.reset(offer);
}
Q_EMIT receivedSelectionChanged();
}
void zwlr_data_control_device_v1_primary_selection(struct ::zwlr_data_control_offer_v1 *id) override
{
if (!id) {
m_receivedPrimarySelection.reset();
} else {
auto derivated = QtWayland::zwlr_data_control_offer_v1::fromObject(id);
auto offer = dynamic_cast<DataControlOffer *>(derivated); // dynamic because of the dual inheritance
m_receivedPrimarySelection.reset(offer);
}
Q_EMIT receivedPrimarySelectionChanged();
}
private:
std::unique_ptr<DataControlSource> m_selection; // selection set locally
std::unique_ptr<DataControlOffer> m_receivedSelection; // latest selection set from externally to here
std::unique_ptr<DataControlSource> m_primarySelection; // selection set locally
std::unique_ptr<DataControlOffer> m_receivedPrimarySelection; // latest selection set from externally to here
friend WaylandClipboard;
};
void DataControlDevice::setSelection(std::unique_ptr<DataControlSource> selection)
{
m_selection = std::move(selection);
connect(m_selection.get(), &DataControlSource::cancelled, this, [this]() {
m_selection.reset();
});
set_selection(m_selection->object());
Q_EMIT selectionChanged();
}
void DataControlDevice::setPrimarySelection(std::unique_ptr<DataControlSource> selection)
{
m_primarySelection = std::move(selection);
connect(m_primarySelection.get(), &DataControlSource::cancelled, this, [this]() {
m_primarySelection.reset();
});
if (zwlr_data_control_device_v1_get_version(object()) >= ZWLR_DATA_CONTROL_DEVICE_V1_SET_PRIMARY_SELECTION_SINCE_VERSION) {
set_primary_selection(m_primarySelection->object());
Q_EMIT primarySelectionChanged();
}
}
class Keyboard;
// We are binding to Seat/Keyboard manually because we want to react to gaining focus but inside Qt the events are Qt and arrive to late
class KeyboardFocusWatcher : public QWaylandClientExtensionTemplate<KeyboardFocusWatcher>, public QtWayland::wl_seat
{
Q_OBJECT
public:
KeyboardFocusWatcher()
: QWaylandClientExtensionTemplate(5)
{
initialize();
auto waylandApp = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();
auto display = waylandApp->display();
// so we get capabilities
wl_display_roundtrip(display);
}
~KeyboardFocusWatcher() override
{
if (isActive()) {
release();
}
}
void seat_capabilities(uint32_t capabilities) override
{
const bool hasKeyboard = capabilities & capability_keyboard;
if (hasKeyboard && !m_keyboard) {
m_keyboard = std::make_unique<Keyboard>(get_keyboard(), *this);
} else if (!hasKeyboard && m_keyboard) {
m_keyboard.reset();
}
}
bool hasFocus() const
{
return m_focus;
}
Q_SIGNALS:
void keyboardEntered();
private:
friend Keyboard;
bool m_focus = false;
std::unique_ptr<Keyboard> m_keyboard;
};
class Keyboard : public QtWayland::wl_keyboard
{
public:
Keyboard(::wl_keyboard *keyboard, KeyboardFocusWatcher &seat)
: wl_keyboard(keyboard)
, m_seat(seat)
{
}
~Keyboard()
{
release();
}
private:
void keyboard_enter([[maybe_unused]] uint32_t serial, [[maybe_unused]] wl_surface *surface, [[maybe_unused]] wl_array *keys) override
{
m_seat.m_focus = true;
Q_EMIT m_seat.keyboardEntered();
}
void keyboard_leave([[maybe_unused]] uint32_t serial, [[maybe_unused]] wl_surface *surface) override
{
m_seat.m_focus = false;
}
KeyboardFocusWatcher &m_seat;
};
WaylandClipboard::WaylandClipboard(QObject *parent)
: KSystemClipboard(parent)
, m_keyboardFocusWatcher(new KeyboardFocusWatcher)
, m_manager(new DataControlDeviceManager)
{
connect(m_manager.get(), &DataControlDeviceManager::activeChanged, this, [this]() {
if (m_manager->isActive()) {
auto waylandApp = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();
if (!waylandApp) {
return;
}
auto seat = waylandApp->seat();
if (!seat) {
return;
}
m_device.reset(new DataControlDevice(m_manager->get_data_device(seat)));
connect(m_device.get(), &DataControlDevice::receivedSelectionChanged, this, [this]() {
// When our source is still valid, so the offer is for setting it or we emit changed when it is cancelled
if (!m_device->selection()) {
Q_EMIT changed(QClipboard::Clipboard);
}
});
connect(m_device.get(), &DataControlDevice::selectionChanged, this, [this]() {
Q_EMIT changed(QClipboard::Clipboard);
});
connect(m_device.get(), &DataControlDevice::receivedPrimarySelectionChanged, this, [this]() {
// When our source is still valid, so the offer is for setting it or we emit changed when it is cancelled
if (!m_device->primarySelection()) {
Q_EMIT changed(QClipboard::Selection);
}
});
connect(m_device.get(), &DataControlDevice::primarySelectionChanged, this, [this]() {
Q_EMIT changed(QClipboard::Selection);
});
} else {
m_device.reset();
}
});
m_manager->instantiate();
}
WaylandClipboard::~WaylandClipboard() = default;
bool WaylandClipboard::isValid()
{
return m_manager && m_manager->isInitialized();
}
void WaylandClipboard::setMimeData(QMimeData *mime, QClipboard::Mode mode)
{
if (!m_device) {
return;
}
// roundtrip to have accurate focus state when losing focus but setting mime data before processing wayland events.
auto waylandApp = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();
auto display = waylandApp->display();
wl_display_roundtrip(display);
// If the application is focused, use the normal mechanism so a future paste will not deadlock itselfs
if (m_keyboardFocusWatcher->hasFocus()) {
QGuiApplication::clipboard()->setMimeData(mime, mode);
// if we short-circuit the wlr_data_device, when we receive the data
// we cannot identify ourselves as the owner
// because of that we act like it's a synchronous action to not confuse klipper.
wl_display_roundtrip(display);
return;
}
// If not, set the clipboard once the app receives focus to avoid the deadlock
connect(m_keyboardFocusWatcher.get(), &KeyboardFocusWatcher::keyboardEntered, this, &WaylandClipboard::gainedFocus, Qt::UniqueConnection);
auto source = std::make_unique<DataControlSource>(m_manager->create_data_source(), mime);
if (mode == QClipboard::Clipboard) {
m_device->setSelection(std::move(source));
} else if (mode == QClipboard::Selection) {
m_device->setPrimarySelection(std::move(source));
}
}
void WaylandClipboard::gainedFocus()
{
disconnect(m_keyboardFocusWatcher.get(), &KeyboardFocusWatcher::keyboardEntered, this, nullptr);
// QClipboard takes ownership of the QMimeData so we need to transfer and unset our selections
if (auto &selection = m_device->m_selection) {
std::unique_ptr<QMimeData> data = selection->releaseMimeData();
selection.reset();
QGuiApplication::clipboard()->setMimeData(data.release(), QClipboard::Clipboard);
}
if (auto &primarySelection = m_device->m_primarySelection) {
std::unique_ptr<QMimeData> data = primarySelection->releaseMimeData();
primarySelection.reset();
QGuiApplication::clipboard()->setMimeData(data.release(), QClipboard::Selection);
}
}
void WaylandClipboard::clear(QClipboard::Mode mode)
{
if (!m_device) {
return;
}
if (mode == QClipboard::Clipboard) {
m_device->set_selection(nullptr);
m_device->m_selection.reset();
} else if (mode == QClipboard::Selection) {
if (zwlr_data_control_device_v1_get_version(m_device->object()) >= ZWLR_DATA_CONTROL_DEVICE_V1_SET_PRIMARY_SELECTION_SINCE_VERSION) {
m_device->set_primary_selection(nullptr);
m_device->m_primarySelection.reset();
}
}
}
const QMimeData *WaylandClipboard::mimeData(QClipboard::Mode mode) const
{
if (!m_device) {
return nullptr;
}
// return our locally set selection if it's not cancelled to avoid copying data to ourselves
if (mode == QClipboard::Clipboard) {
if (m_device->selection()) {
return m_device->selection();
}
// This application owns the clipboard via the regular data_device, use it so we don't block ourselves
if (QGuiApplication::clipboard()->ownsClipboard()) {
return QGuiApplication::clipboard()->mimeData(mode);
}
return m_device->receivedSelection();
} else if (mode == QClipboard::Selection) {
if (m_device->primarySelection()) {
return m_device->primarySelection();
}
// This application owns the primary selection via the regular primary_selection_device, use it so we don't block ourselves
if (QGuiApplication::clipboard()->ownsSelection()) {
return QGuiApplication::clipboard()->mimeData(mode);
}
return m_device->receivedPrimarySelection();
}
return nullptr;
}
#include "waylandclipboard.moc"
@@ -0,0 +1,36 @@
/*
SPDX-FileCopyrightText: 2020 David Edmundson <davidedmundson@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef WAYLANDCLIPBOARD_H
#define WAYLANDCLIPBOARD_H
#include "ksystemclipboard.h"
#include <memory>
class DataControlDevice;
class DataControlDeviceManager;
class KeyboardFocusWatcher;
class WaylandClipboard : public KSystemClipboard
{
public:
WaylandClipboard(QObject *parent);
~WaylandClipboard();
void setMimeData(QMimeData *mime, QClipboard::Mode mode) override;
void clear(QClipboard::Mode mode) override;
const QMimeData *mimeData(QClipboard::Mode mode) const override;
bool isValid();
private:
void gainedFocus();
std::unique_ptr<KeyboardFocusWatcher> m_keyboardFocusWatcher;
std::unique_ptr<DataControlDeviceManager> m_manager;
std::unique_ptr<DataControlDevice> m_device;
};
#endif
@@ -0,0 +1,278 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="wlr_data_control_unstable_v1">
<copyright>
Copyright © 2018 Simon Ser
Copyright © 2019 Ivan Molodetskikh
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
the copyright holders not be used in advertising or publicity
pertaining to distribution of the software without specific,
written prior permission. The copyright holders make no
representations about the suitability of this software for any
purpose. It is provided "as is" without express or implied
warranty.
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
</copyright>
<description summary="control data devices">
This protocol allows a privileged client to control data devices. In
particular, the client will be able to manage the current selection and take
the role of a clipboard manager.
Warning! The protocol described in this file is experimental and
backward incompatible changes may be made. Backward compatible changes
may be added together with the corresponding interface version bump.
Backward incompatible changes are done by bumping the version number in
the protocol and interface names and resetting the interface version.
Once the protocol is to be declared stable, the 'z' prefix and the
version number in the protocol and interface names are removed and the
interface version number is reset.
</description>
<interface name="zwlr_data_control_manager_v1" version="2">
<description summary="manager to control data devices">
This interface is a manager that allows creating per-seat data device
controls.
</description>
<request name="create_data_source">
<description summary="create a new data source">
Create a new data source.
</description>
<arg name="id" type="new_id" interface="zwlr_data_control_source_v1"
summary="data source to create"/>
</request>
<request name="get_data_device">
<description summary="get a data device for a seat">
Create a data device that can be used to manage a seat's selection.
</description>
<arg name="id" type="new_id" interface="zwlr_data_control_device_v1"/>
<arg name="seat" type="object" interface="wl_seat"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy the manager">
All objects created by the manager will still remain valid, until their
appropriate destroy request has been called.
</description>
</request>
</interface>
<interface name="zwlr_data_control_device_v1" version="2">
<description summary="manage a data device for a seat">
This interface allows a client to manage a seat's selection.
When the seat is destroyed, this object becomes inert.
</description>
<request name="set_selection">
<description summary="copy data to the selection">
This request asks the compositor to set the selection to the data from
the source on behalf of the client.
The given source may not be used in any further set_selection or
set_primary_selection requests. Attempting to use a previously used
source is a protocol error.
To unset the selection, set the source to NULL.
</description>
<arg name="source" type="object" interface="zwlr_data_control_source_v1"
allow-null="true"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy this data device">
Destroys the data device object.
</description>
</request>
<event name="data_offer">
<description summary="introduce a new wlr_data_control_offer">
The data_offer event introduces a new wlr_data_control_offer object,
which will subsequently be used in either the
wlr_data_control_device.selection event (for the regular clipboard
selections) or the wlr_data_control_device.primary_selection event (for
the primary clipboard selections). Immediately following the
wlr_data_control_device.data_offer event, the new data_offer object
will send out wlr_data_control_offer.offer events to describe the MIME
types it offers.
</description>
<arg name="id" type="new_id" interface="zwlr_data_control_offer_v1"/>
</event>
<event name="selection">
<description summary="advertise new selection">
The selection event is sent out to notify the client of a new
wlr_data_control_offer for the selection for this device. The
wlr_data_control_device.data_offer and the wlr_data_control_offer.offer
events are sent out immediately before this event to introduce the data
offer object. The selection event is sent to a client when a new
selection is set. The wlr_data_control_offer is valid until a new
wlr_data_control_offer or NULL is received. The client must destroy the
previous selection wlr_data_control_offer, if any, upon receiving this
event.
The first selection event is sent upon binding the
wlr_data_control_device object.
</description>
<arg name="id" type="object" interface="zwlr_data_control_offer_v1"
allow-null="true"/>
</event>
<event name="finished">
<description summary="this data control is no longer valid">
This data control object is no longer valid and should be destroyed by
the client.
</description>
</event>
<!-- Version 2 additions -->
<event name="primary_selection" since="2">
<description summary="advertise new primary selection">
The primary_selection event is sent out to notify the client of a new
wlr_data_control_offer for the primary selection for this device. The
wlr_data_control_device.data_offer and the wlr_data_control_offer.offer
events are sent out immediately before this event to introduce the data
offer object. The primary_selection event is sent to a client when a
new primary selection is set. The wlr_data_control_offer is valid until
a new wlr_data_control_offer or NULL is received. The client must
destroy the previous primary selection wlr_data_control_offer, if any,
upon receiving this event.
If the compositor supports primary selection, the first
primary_selection event is sent upon binding the
wlr_data_control_device object.
</description>
<arg name="id" type="object" interface="zwlr_data_control_offer_v1"
allow-null="true"/>
</event>
<request name="set_primary_selection" since="2">
<description summary="copy data to the primary selection">
This request asks the compositor to set the primary selection to the
data from the source on behalf of the client.
The given source may not be used in any further set_selection or
set_primary_selection requests. Attempting to use a previously used
source is a protocol error.
To unset the primary selection, set the source to NULL.
The compositor will ignore this request if it does not support primary
selection.
</description>
<arg name="source" type="object" interface="zwlr_data_control_source_v1"
allow-null="true"/>
</request>
<enum name="error" since="2">
<entry name="used_source" value="1"
summary="source given to set_selection or set_primary_selection was already used before"/>
</enum>
</interface>
<interface name="zwlr_data_control_source_v1" version="1">
<description summary="offer to transfer data">
The wlr_data_control_source object is the source side of a
wlr_data_control_offer. It is created by the source client in a data
transfer and provides a way to describe the offered data and a way to
respond to requests to transfer the data.
</description>
<enum name="error">
<entry name="invalid_offer" value="1"
summary="offer sent after wlr_data_control_device.set_selection"/>
</enum>
<request name="offer">
<description summary="add an offered MIME type">
This request adds a MIME type to the set of MIME types advertised to
targets. Can be called several times to offer multiple types.
Calling this after wlr_data_control_device.set_selection is a protocol
error.
</description>
<arg name="mime_type" type="string"
summary="MIME type offered by the data source"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy this source">
Destroys the data source object.
</description>
</request>
<event name="send">
<description summary="send the data">
Request for data from the client. Send the data as the specified MIME
type over the passed file descriptor, then close it.
</description>
<arg name="mime_type" type="string" summary="MIME type for the data"/>
<arg name="fd" type="fd" summary="file descriptor for the data"/>
</event>
<event name="cancelled">
<description summary="selection was cancelled">
This data source is no longer valid. The data source has been replaced
by another data source.
The client should clean up and destroy this data source.
</description>
</event>
</interface>
<interface name="zwlr_data_control_offer_v1" version="1">
<description summary="offer to transfer data">
A wlr_data_control_offer represents a piece of data offered for transfer
by another client (the source client). The offer describes the different
MIME types that the data can be converted to and provides the mechanism
for transferring the data directly from the source client.
</description>
<request name="receive">
<description summary="request that the data is transferred">
To transfer the offered data, the client issues this request and
indicates the MIME type it wants to receive. The transfer happens
through the passed file descriptor (typically created with the pipe
system call). The source client writes the data in the MIME type
representation requested and then closes the file descriptor.
The receiving client reads from the read end of the pipe until EOF and
then closes its end, at which point the transfer is complete.
This request may happen multiple times for different MIME types.
</description>
<arg name="mime_type" type="string"
summary="MIME type desired by receiver"/>
<arg name="fd" type="fd" summary="file descriptor for data transfer"/>
</request>
<request name="destroy" type="destructor">
<description summary="destroy this offer">
Destroys the data offer object.
</description>
</request>
<event name="offer">
<description summary="advertise offered MIME type">
Sent immediately after creating the wlr_data_control_offer object.
One event per offered MIME type.
</description>
<arg name="mime_type" type="string" summary="offered MIME type"/>
</event>
</interface>
</protocol>
@@ -0,0 +1,66 @@
/* -*- C++ -*-
This file is part of the KDE libraries
SPDX-FileCopyrightText: 1997 Tim D. Gilman <tdgilman@best.org>
SPDX-FileCopyrightText: 1998-2001 Mirko Boehm <mirko@kde.org>
SPDX-FileCopyrightText: 2007 John Layt <john@layt.net>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "kdatevalidator.h"
#include <QDate>
#include <QLocale>
class KDateValidatorPrivate
{
public:
KDateValidatorPrivate(KDateValidator *qq)
: q(qq)
{
}
~KDateValidatorPrivate()
{
}
KDateValidator *const q;
};
KDateValidator::KDateValidator(QObject *parent)
: QValidator(parent)
{
}
KDateValidator::~KDateValidator() = default;
QValidator::State KDateValidator::validate(QString &text, int &unused) const
{
Q_UNUSED(unused);
QDate temp;
// ----- everything is tested in date():
return date(text, temp);
}
QValidator::State KDateValidator::date(const QString &text, QDate &d) const
{
QLocale::FormatType formats[] = {QLocale::LongFormat, QLocale::ShortFormat, QLocale::NarrowFormat};
QLocale locale;
for (int i = 0; i < 3; i++) {
QDate tmp = locale.toDate(text, formats[i]);
if (tmp.isValid()) {
d = tmp;
return Acceptable;
}
}
return QValidator::Intermediate;
}
void KDateValidator::fixup(QString &) const
{
}
#include "moc_kdatevalidator.cpp"

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