Full Code of moverest/wl-kbptr for AI

main 6191d1725515 cached
42 files
240.4 KB
61.4k tokens
279 symbols
1 requests
Download .txt
Showing preview only (253K chars total). Download the full file or copy to clipboard to get everything.
Repository: moverest/wl-kbptr
Branch: main
Commit: 6191d1725515
Files: 42
Total size: 240.4 KB

Directory structure:
gitextract_pvjsi8rp/

├── .clang-format
├── .github/
│   └── ISSUE_TEMPLATE/
│       └── bug_report.md
├── .gitignore
├── LICENSE
├── README.md
├── config.example
├── helpers/
│   └── wl-kbptr-sway-active-win
├── meson.build
├── meson.options
├── protocol/
│   ├── fractional-scale-v1.xml
│   ├── meson.build
│   ├── wlr-layer-shell-unstable-v1.xml
│   ├── wlr-screencopy-unstable-v1.xml
│   └── wlr-virtual-pointer-unstable-v1.xml
├── share/
│   └── wl-kbptr.desktop
└── src/
    ├── config.c
    ├── config.h
    ├── label.c
    ├── label.h
    ├── log.h
    ├── main.c
    ├── mode.c
    ├── mode.h
    ├── mode_bisect.c
    ├── mode_click.c
    ├── mode_floating.c
    ├── mode_split.c
    ├── mode_tile.c
    ├── screencopy.c
    ├── screencopy.h
    ├── state.h
    ├── surface_buffer.c
    ├── surface_buffer.h
    ├── target_detection.cpp
    ├── target_detection.h
    ├── test_label.c
    ├── utils.c
    ├── utils.h
    ├── utils_cairo.c
    ├── utils_cairo.h
    ├── utils_wayland.c
    └── utils_wayland.h

================================================
FILE CONTENTS
================================================

================================================
FILE: .clang-format
================================================
---
Language:        Cpp
AlignAfterOpenBracket: BlockIndent
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
  Enabled:         true
  AcrossEmptyLines: false
  AcrossComments:  true
  AlignCompound:   true
  PadOperators:    true
AlignConsecutiveBitFields:
  Enabled:         false
  AcrossEmptyLines: false
  AcrossComments:  false
  AlignCompound:   false
  PadOperators:    false
AlignConsecutiveDeclarations:
  Enabled:         true
  AcrossEmptyLines: false
  AcrossComments:  true
  AlignCompound:   true
  PadOperators:    true
AlignConsecutiveMacros:
  Enabled:         true
  AcrossEmptyLines: false
  AcrossComments:  true
  AlignCompound:   true
  PadOperators:    true
AlignEscapedNewlines: Left
AlignOperands:   Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortEnumsOnASingleLine: true
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AttributeMacros:
  - __capability
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
  AfterCaseLabel:  false
  AfterClass:      false
  AfterControlStatement: Never
  AfterEnum:       false
  AfterFunction:   false
  AfterNamespace:  false
  AfterObjCDeclaration: false
  AfterStruct:     true
  AfterUnion:      false
  AfterExternBlock: false
  BeforeCatch:     false
  BeforeElse:      false
  BeforeLambdaBody: false
  BeforeWhile:     false
  IndentBraces:    false
  SplitEmptyFunction: true
  SplitEmptyRecord: true
  SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit:     80
CommentPragmas:  '^ IWYU pragma:'
QualifierAlignment: Leave
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat:   false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
PackConstructorInitializers: BinPack
BasedOnStyle:    ''
ConstructorInitializerAllOnOneLineOrOnePerLine: false
AllowAllConstructorInitializersOnNextLine: true
FixNamespaceComments: true
ForEachMacros:
  - foreach
  - wl_list_for_each
  - wl_list_for_each_safe
IncludeBlocks:   Regroup
IncludeCategories:
  - Regex:           '^"(llvm|llvm-c|clang|clang-c)/'
    Priority:        2
    SortPriority:    0
    CaseSensitive:   false
  - Regex:           '^(<|"(gtest|gmock|isl|json)/)'
    Priority:        3
    SortPriority:    0
    CaseSensitive:   false
  - Regex:           '.*'
    Priority:        1
    SortPriority:    0
    CaseSensitive:   false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseLabels: false
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentExternBlock: AfterExternBlock
IndentRequiresClause: true
IndentWidth:     4
IndentWrappedFunctionNames: false
InsertBraces:    true
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
LambdaBodyIndentation: Signature
MacroBlockBegin: ''
MacroBlockEnd:   ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PenaltyIndentedWhitespace: 0
PointerAlignment: Right
PPIndentWidth:   -1
ReferenceAlignment: Pointer
ReflowComments:  true
RemoveBracesLLVM: false
RequiresClausePosition: OwnLine
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SortIncludes:    CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
  AfterControlStatements: true
  AfterForeachMacros: true
  AfterFunctionDefinitionName: false
  AfterFunctionDeclarationName: false
  AfterIfMacros:   true
  AfterOverloadedOperator: false
  AfterRequiresInClause: false
  AfterRequiresInExpression: false
  BeforeNonEmptyParentheses: false
SpaceAroundPointerQualifiers: Default
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles:  Never
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInLineCommentPrefix:
  Minimum:         1
  Maximum:         -1
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
BitFieldColonSpacing: Both
Standard:        Latest
StatementAttributeLikeMacros:
  - Q_EMIT
StatementMacros:
  - Q_UNUSED
  - QT_REQUIRE_VERSION
TabWidth:        8
UseCRLF:         false
UseTab:          Never
WhitespaceSensitiveMacros:
  - STRINGIZE
  - PP_STRINGIZE
  - BOOST_PP_STRINGIZE
  - NS_SWIFT_NAME
  - CF_SWIFT_NAME
...



================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''

---

First describe the bug.

You should be able to answer the following questions:
 - How to reproduce the bug?
 - What is going wrong?
 - What is the expected behaviour?

It is helpful to provide screenshots and screencasts.

Then give the following information:

- **Version** of `wl-kbptr` used. Use `wl-kbptr --version` to get this. Ideally, check if the issue is present in `main` and use the commit hash as the version and state the enabled features.
- **Compositor** used and its version. This is important as compositors have their own implementation of the Wayland compositor even if they can share code or use the same library.
- **Distribution** used. Whilst it might not always be relevant, distributions can package the program differently or apply patches.
- You **display settings** (optional). Sometimes some bug only happen with some display settings. You can get this information with `wlr-randr` on `wlroots` compositors.

If you are not sure about something (e.g. how to get a piece of information, or how to reproduce the bug), don't worry just state what you are able to provide and we'll try to investigate together.


================================================
FILE: .gitignore
================================================
.cache
*.gch


================================================
FILE: LICENSE
================================================
                    GNU 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.

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


================================================
FILE: README.md
================================================
# wl-kbptr

`wl-kbptr` &mdash; short for Wayland Keyboard Pointer &mdash; is a utility to help move the mouse pointer with the keyboard.

See [Supported compositors](#supported-compositors) section for compatibility.

## Modes

To enable to select a target and click, it has four different modes:
- [`floating`](#floating-mode) &mdash; which uses arbitrary areas either given by the user or detected,
- [`tile`](#tile-mode) &mdash; which uses a grid to select areas,
- [`bisect`](#bisect-mode) &mdash; which enables to bisect an area,
- [`split`](#split-mode) &mdash; which enables to successively split an area,
- and [`click`](#click-mode) &mdash; which triggers a click in the middle of an area.

These are set with the `modes` configuration field and can be chained, e.g. `wl-kbptr -o modes=tile,bisect`.

Note that if you make a mistake &mdash; e.g. select the wrong area &mdash; you can always go back on step by pressing the `Backspace` key. This even works between modes.

### Floating mode
[Floating Mode Demo](https://github.com/user-attachments/assets/1598128b-e03b-4d06-b47a-bc8a0021f4da)

The `floating` mode uses arbitrary selection areas that can be passed by the user through the standard input. Each input line represents an area defined with the `wxh+x+y` format.

#### Auto-detection
The areas can also be automatically detected with `mode_floating.source` configuration set to `detect`, e.g. `wl-kbptr -o modes=floating,click -o mode_floating.source=detect`.

This requires the `wl-kbptr` binary to be built with the `opencv` feature and the compositor to support the [`wlr-screencopy-unstable-v1`](https://wayland.app/protocols/wlr-screencopy-unstable-v1) protocol &mdash; see the [supported compositors](#supported-compositors) section and [build instructions](#from-sources) for details. Whilst it doesn't noticeably change the size of the program itself, OpenCV is a 100 MB+ dependency which is not ideal if you want a very small system which is why this is an optional feature.

Most distributions will package the program with the option enabled. If not, they will usually provide two packages. You can check if the binary you have has been built with it with `wl-kbptr --version` &mdash; it should print `opencv` if supported.

### Tile mode
[Tile Mode Demo](https://github.com/user-attachments/assets/d8c9c8dc-2733-4835-9d82-d0f5b093c382)

The `tile` mode displays a grid. To select an area, simply type the label associated with the tile you want to select.

### Bisect mode
[Bisect Mode Demo](https://github.com/user-attachments/assets/8f8f7fb4-1bb9-4180-9eda-78ee1ff14181)

The `bisect` mode enables to bisect a given area. At any point the cursor can be moved at the location marked by the red marker by pressing `Enter` or `Space`.

A left, right and middle click can be made by pressing the `g`, `h` and `b` keys respectively on a QWERTY keyboard layout. Note that other layout will use the same keys positions, e.g. `i`, `d`, and `x` with a Dvorak keyboard layout.

### Split mode
[Split Mode Demo](https://github.com/user-attachments/assets/760fa154-ce50-47b4-8f9a-26c5ac79a55b)

The `split` mode enables to successively split an area with the arrow keys.

Just like the `bisect` mode, a left, right and middle click can be made by pressing the `g`, `h` and `b` keys respectively on a QWERTY keyboard layout.

### Click mode

The `click` mode simply triggers a click in the middle of the selection area.

## Supported compositors

For `wl-kbptr` to work, it requires the following protocols:
 - [`wlr-layer-shell-unstable-v1`](https://wayland.app/protocols/wlr-layer-shell-unstable-v1) for the program to display on top,
 - [`wlr-virtual-pointer-unstable-v1`](https://wayland.app/protocols/wlr-virtual-pointer-unstable-v1) to control the mouse pointer,
 - and [`wlr-screencopy-unstable-v1`](https://wayland.app/protocols/wlr-screencopy-unstable-v1) (optional) to capture the screen for target detection in the `floating` mode.

Here are the compositors with which it has been tested:

| Compositor |     | Notes |
| ---------- | --- | ----- |
| [Sway](https://swaywm.org) | ✅ | - |
| [Hyprland](https://hyprland.org) | ✅ | - |
| [niri](https://github.com/YaLTeR/niri) | ✅ | - |
| [dwl](https://codeberg.org/dwl/dwl) | ✅ | - |
| [labwc](https://labwc.github.io) | ✅ | - |
| [Wayfire](https://wayfire.org) | ✅ | The pointer doesn't move to the right location with multiple display outputs. See [#56](https://github.com/moverest/wl-kbptr/issues/56#issuecomment-3087922040). |
| [KWin](https://github.com/KDE/kwin) | ❗ | The compositor doesn't support the [`wlr-virtual-pointer-unstable-v1`](https://wayland.app/protocols/wlr-virtual-pointer-unstable-v1) and [`wlr-screencopy-unstable-v1`](https://wayland.app/protocols/wlr-screencopy-unstable-v1) protocols. It can still work with the `--print-only` option and the mouse pointer can then be moved with `ydotool` or similar. |
| [Mutter](https://mutter.gnome.org) | ❌ | The compositor doesn't support any of the required protocols. |

## Installation

### Arch Linux

If you are using Arch Linux, you can install the [`wl-kbptr` AUR package](https://aur.archlinux.org/packages/wl-kbptr).

Recommended way to build and install the package directly from the AUR (gets all required files):
```bash
git clone https://aur.archlinux.org/wl-kbptr.git
cd wl-kbptr
makepkg -si
```

Alternatively, if you only want the `PKGBUILD`:
```bash
curl -L 'https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=wl-kbptr' -o PKGBUILD
makepkg -si
```

### NixOS

If you are using NixOS, you can install the [`wl-kbptr` package](https://search.nixos.org/packages?query=wl-kbptr). Nix can also be used to install `wl-kbptr` on other distributions.

### Chimera Linux

If you are using Chimera Linux, you can install the [`wl-kbptr` package](https://pkgs.chimera-linux.org/package/current/contrib/x86_64/wl-kbptr) which is available in the [contrib repository](https://chimera-linux.org/docs/apk#repositories).

```bash
apk add chimera-repo-contrib
apk add wl-kbptr
```
### Fedora

As of now there is no official package through dnf. So you will need to install the dependencies and then run the steps described in the **From sources** section.

```bash
sudo dnf install -y \
    meson \
    wayland-protocols-devel \
    gcc \
    libwayland-client  \
    cmake \
    wayland-devel \
    libxkbcommon-devel \
    cairo-devel
```

### From sources

You can build from sources with:

```bash
meson setup build --buildtype=release
meson compile -C build
```

If you want to build the target detection feature (see [floating mode](#floating-mode)), you need to enable the `opencv` feature:

```bash
meson setup build --buildtype=release -Dopencv=enabled
meson compile -C build
```

Then install with:

```bash
meson install -C build
```

## Setting the bindings

### Sway

```
mode Mouse {
    bindsym a mode default, exec 'wl-kbptr-sway-active-win; swaymsg mode Mouse'
    bindsym Shift+a mode default, exec 'wl-kbptr; swaymsg mode Mouse'

    # Mouse move
    bindsym h seat seat0 cursor move -15 0
    bindsym j seat seat0 cursor move 0 15
    bindsym k seat seat0 cursor move 0 -15
    bindsym l seat seat0 cursor move 15 0

    # Left button
    bindsym s seat seat0 cursor press button1
    bindsym --release s seat seat0 cursor release button1

    # Middle button
    bindsym d seat seat0 cursor press button2
    bindsym --release d seat seat0 cursor release button2

    # Right button
    bindsym f seat seat0 cursor press button3
    bindsym --release f seat seat0 cursor release button3

    bindsym Escape mode default
}

bindsym $mod+g exec wl-kbptr-sway-active-win -o modes=floating','click -o mode_floating.source=detect
bindsym $mod+Shift+g mode Mouse
```

### Hyprland

```
# Cursor submap (similar to the Mouse mode in Sway)
submap=cursor

# Jump cursor to a position
bind=,a,exec,hyprctl dispatch submap reset && wl-kbptr && hyprctl dispatch submap cursor

# Cursor movement
binde=,j,exec,wlrctl pointer move 0 10
binde=,k,exec,wlrctl pointer move 0 -10
binde=,l,exec,wlrctl pointer move 10 0
binde=,h,exec,wlrctl pointer move -10 0

# Left button
bind=,s,exec,wlrctl pointer click left
# Middle button
bind=,d,exec,wlrctl pointer click middle
# Right button
bind=,f,exec,wlrctl pointer click right

# Scroll up and down
binde=,e,exec,wlrctl pointer scroll 10 0
binde=,r,exec,wlrctl pointer scroll -10 0

# Scroll left and right
binde=,t,exec,wlrctl pointer scroll 0 -10
binde=,g,exec,wlrctl pointer scroll 0 10

# Exit cursor submap
# If you do not use cursor timeout or cursor:hide_on_key_press, you can delete its respective calls.
bind=,escape,exec,hyprctl keyword cursor:inactive_timeout 3; hyprctl keyword cursor:hide_on_key_press true; hyprctl dispatch submap reset 

submap = reset

# Entrypoint
# If you do not use cursor timeout or cursor:hide_on_key_press, you can delete its respective calls.
bind=$mainMod,g,exec,hyprctl keyword cursor:inactive_timeout 0; hyprctl keyword cursor:hide_on_key_press false; hyprctl dispatch submap cursor
```

## Configuration

`wl-kbptr` can be configured with a configuration file. See [`config.example`](./config.example) for an example and run `wl-kbptr --help-config` for help.

## Dependencies

- [`xkbcommon`](https://xkbcommon.org)
- [`cairo`](https://cairographics.org)
- [`wayland`](https://wayland.freedesktop.org)
- [`wayland-protocols`](https://gitlab.freedesktop.org/wayland/wayland-protocols)
- With the `opencv` feature enabled:
  - C++ compiler
  - [`OpenCV`](https://opencv.org)
  - [`Pixman`](https://www.pixman.org)


## License

[GPL-3.0](./LICENSE)


================================================
FILE: config.example
================================================
# wl-kbptr can be configured with a configuration file.
# The file location can be passed with the -c parameter.
# Othewise the `$XDG_CONFIG_HOME/wl-kbptr/config` file will
# be loaded if it exits. Below is the default configuration.

[general]
home_row_keys=
modes=tile,bisect
cancellation_status_code=0

[mode_tile]
label_color=#fffd
label_select_color=#fd0d
unselectable_bg_color=#2226
selectable_bg_color=#0304
selectable_border_color=#040c
label_font_family=sans-serif
label_font_size=8 50% 100
label_symbols=abcdefghijklmnopqrstuvwxyz

[mode_floating]
source=stdin
label_color=#fffd
label_select_color=#fd0d
unselectable_bg_color=#2226
selectable_bg_color=#1718
selectable_border_color=#040c
label_font_family=sans-serif
label_font_size=12 50% 100
label_symbols=abcdefghijklmnopqrstuvwxyz

[mode_bisect]
label_color=#fffd
label_font_size=20
label_font_family=sans-serif
label_padding=12
pointer_size=20
pointer_color=#e22d
unselectable_bg_color=#2226
even_area_bg_color=#0304
even_area_border_color=#0408
odd_area_bg_color=#0034
odd_area_border_color=#0048
history_border_color=#3339

[mode_split]
pointer_size=20
pointer_color=#e22d
bg_color=#2226
area_bg_color=#11111188
vertical_color=#8888ffcc
horizontal_color=#008800cc
history_border_color=#3339

[mode_click]
button=left


================================================
FILE: helpers/wl-kbptr-sway-active-win
================================================
#!/bin/sh

active_area=$(swaymsg -t get_tree | jq --raw-output \
	'.. | (.nodes? + .floating_nodes? // empty)[] | select (.focused) | .rect | "\(.width)x\(.height)+\(.x)+\(.y)"')
wl-kbptr --restrict "$active_area" $@


================================================
FILE: meson.build
================================================
project(
  'wl-kbptr',
  'c',
  meson_version: '>=1.1',
  default_options: ['c_std=c11'],
  license: 'GPL-3.0',
  version: '0.4.1',
)

use_opencv = get_option('opencv').enabled()
version_suffix = ''

if get_option('buildtype') == 'debug'
  add_project_arguments('-DDEBUG', language: ['c', 'cpp'])
  version_suffix = '-debug'
endif

add_project_arguments(
  '-D_GNU_SOURCE=200809L',
  '-DVERSION="@0@@1@"'.format(meson.project_version(), version_suffix),
  language: 'c',
)

cc = meson.get_compiler('c')

if use_opencv
  add_project_arguments('-DOPENCV_ENABLED=1', language: ['c', 'cpp'])
  add_languages('cpp', native: false)
  opencv = dependency('opencv4')
  pixman = dependency('pixman-1')
endif

wayland_client = dependency('wayland-client')
wayland_protos = dependency('wayland-protocols')
xkbcommon = dependency('xkbcommon')
cairo = dependency('cairo')
math = cc.find_library('m')

subdir('protocol')

dependencies = [
  wayland_client,
  xkbcommon,
  cairo,
  math,
]

sources = [
  'src/main.c',
  'src/surface_buffer.c',
  'src/mode.c',
  'src/mode_tile.c',
  'src/mode_floating.c',
  'src/mode_bisect.c',
  'src/mode_split.c',
  'src/mode_click.c',
  'src/utils.c',
  'src/utils_cairo.c',
  'src/utils_wayland.c',
  'src/config.c',
  'src/label.c',
  protos_src,
]

if use_opencv
  sources += [
    'src/screencopy.c',
    'src/target_detection.cpp',
  ]
  dependencies += [opencv, pixman]
endif

executable(
  'wl-kbptr',
  sources,
  dependencies: dependencies,
  install: true,
)

label_test_exec = executable(
  'test_label',
  [
    'src/test_label.c',
    'src/label.c',
    'src/utils.c',
  ],
)

test('test_label', label_test_exec)

install_data(
  'share/wl-kbptr.desktop',
  rename: 'wl-kbptr.desktop',
  install_dir: 'share/applications',
)


================================================
FILE: meson.options
================================================
option('opencv', type: 'feature', value: 'disabled')


================================================
FILE: protocol/fractional-scale-v1.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="fractional_scale_v1">
  <copyright>
    Copyright © 2022 Kenny Levinsen

    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 requesting fractional surface scales">
    This protocol allows a compositor to suggest for surfaces to render at
    fractional scales.

    A client can submit scaled content by utilizing wp_viewport. This is done by
    creating a wp_viewport object for the surface and setting the destination
    rectangle to the surface size before the scale factor is applied.

    The buffer size is calculated by multiplying the surface size by the
    intended scale.

    The wl_surface buffer scale should remain set to 1.

    If a surface has a surface-local size of 100 px by 50 px and wishes to
    submit buffers with a scale of 1.5, then a buffer of 150px by 75 px should
    be used and the wp_viewport destination rectangle should be 100 px by 50 px.

    For toplevel surfaces, the size is rounded halfway away from zero. The
    rounding algorithm for subsurface position and size is not defined.
  </description>

  <interface name="wp_fractional_scale_manager_v1" version="1">
    <description summary="fractional surface scale information">
      A global interface for requesting surfaces to use fractional scales.
    </description>

    <request name="destroy" type="destructor">
      <description summary="unbind the fractional surface scale interface">
        Informs the server that the client will not be using this protocol
        object anymore. This does not affect any other objects,
        wp_fractional_scale_v1 objects included.
      </description>
    </request>

    <enum name="error">
      <entry name="fractional_scale_exists" value="0"
        summary="the surface already has a fractional_scale object associated"/>
    </enum>

    <request name="get_fractional_scale">
      <description summary="extend surface interface for scale information">
        Create an add-on object for the the wl_surface to let the compositor
        request fractional scales. If the given wl_surface already has a
        wp_fractional_scale_v1 object associated, the fractional_scale_exists
        protocol error is raised.
      </description>
      <arg name="id" type="new_id" interface="wp_fractional_scale_v1"
           summary="the new surface scale info interface id"/>
      <arg name="surface" type="object" interface="wl_surface"
           summary="the surface"/>
    </request>
  </interface>

  <interface name="wp_fractional_scale_v1" version="1">
    <description summary="fractional scale interface to a wl_surface">
      An additional interface to a wl_surface object which allows the compositor
      to inform the client of the preferred scale.
    </description>

    <request name="destroy" type="destructor">
      <description summary="remove surface scale information for surface">
        Destroy the fractional scale object. When this object is destroyed,
        preferred_scale events will no longer be sent.
      </description>
    </request>

    <event name="preferred_scale">
      <description summary="notify of new preferred scale">
        Notification of a new preferred scale for this surface that the
        compositor suggests that the client should use.

        The sent scale is the numerator of a fraction with a denominator of 120.
      </description>
      <arg name="scale" type="uint" summary="the new preferred scale"/>
    </event>
  </interface>
</protocol>


================================================
FILE: protocol/meson.build
================================================
wayland_scanner_dep = dependency('wayland-scanner', native: true)
wayland_scanner = find_program(
  wayland_scanner_dep.get_variable('wayland_scanner'), native: true,
)

wl_protocol_dir = wayland_protos.get_variable('pkgdatadir')

wayland_scanner_code = generator(
  wayland_scanner, output: '@BASENAME@-protocol.c',
  arguments: ['private-code', '@INPUT@', '@OUTPUT@'],
)

wayland_scanner_header = generator(
  wayland_scanner, output: '@BASENAME@-client-protocol.h',
  arguments: ['client-header', '@INPUT@', '@OUTPUT@'],
)

client_protocols = [
  wl_protocol_dir / 'stable/xdg-shell/xdg-shell.xml',
  wl_protocol_dir / 'unstable/xdg-output/xdg-output-unstable-v1.xml',
  wl_protocol_dir / 'stable/viewporter/viewporter.xml',
  'wlr-layer-shell-unstable-v1.xml',
  'wlr-virtual-pointer-unstable-v1.xml',
  'wlr-screencopy-unstable-v1.xml',
  'fractional-scale-v1.xml',
]

protos_src = []
foreach xml : client_protocols
	protos_src += wayland_scanner_code.process(xml)
	protos_src += wayland_scanner_header.process(xml)
endforeach


================================================
FILE: protocol/wlr-layer-shell-unstable-v1.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="wlr_layer_shell_unstable_v1">
  <copyright>
    Copyright © 2017 Drew DeVault

    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>

  <interface name="zwlr_layer_shell_v1" version="4">
    <description summary="create surfaces that are layers of the desktop">
      Clients can use this interface to assign the surface_layer role to
      wl_surfaces. Such surfaces are assigned to a "layer" of the output and
      rendered with a defined z-depth respective to each other. They may also be
      anchored to the edges and corners of a screen and specify input handling
      semantics. This interface should be suitable for the implementation of
      many desktop shell components, and a broad number of other applications
      that interact with the desktop.
    </description>

    <request name="get_layer_surface">
      <description summary="create a layer_surface from a surface">
        Create a layer surface for an existing surface. This assigns the role of
        layer_surface, or raises a protocol error if another role is already
        assigned.

        Creating a layer surface from a wl_surface which has a buffer attached
        or committed is a client error, and any attempts by a client to attach
        or manipulate a buffer prior to the first layer_surface.configure call
        must also be treated as errors.

        After creating a layer_surface object and setting it up, the client
        must perform an initial commit without any buffer attached.
        The compositor will reply with a layer_surface.configure event.
        The client must acknowledge it and is then allowed to attach a buffer
        to map the surface.

        You may pass NULL for output to allow the compositor to decide which
        output to use. Generally this will be the one that the user most
        recently interacted with.

        Clients can specify a namespace that defines the purpose of the layer
        surface.
      </description>
      <arg name="id" type="new_id" interface="zwlr_layer_surface_v1"/>
      <arg name="surface" type="object" interface="wl_surface"/>
      <arg name="output" type="object" interface="wl_output" allow-null="true"/>
      <arg name="layer" type="uint" enum="layer" summary="layer to add this surface to"/>
      <arg name="namespace" type="string" summary="namespace for the layer surface"/>
    </request>

    <enum name="error">
      <entry name="role" value="0" summary="wl_surface has another role"/>
      <entry name="invalid_layer" value="1" summary="layer value is invalid"/>
      <entry name="already_constructed" value="2" summary="wl_surface has a buffer attached or committed"/>
    </enum>

    <enum name="layer">
      <description summary="available layers for surfaces">
        These values indicate which layers a surface can be rendered in. They
        are ordered by z depth, bottom-most first. Traditional shell surfaces
        will typically be rendered between the bottom and top layers.
        Fullscreen shell surfaces are typically rendered at the top layer.
        Multiple surfaces can share a single layer, and ordering within a
        single layer is undefined.
      </description>

      <entry name="background" value="0"/>
      <entry name="bottom" value="1"/>
      <entry name="top" value="2"/>
      <entry name="overlay" value="3"/>
    </enum>

    <!-- Version 3 additions -->

    <request name="destroy" type="destructor" since="3">
      <description summary="destroy the layer_shell object">
        This request indicates that the client will not use the layer_shell
        object any more. Objects that have been created through this instance
        are not affected.
      </description>
    </request>
  </interface>

  <interface name="zwlr_layer_surface_v1" version="4">
    <description summary="layer metadata interface">
      An interface that may be implemented by a wl_surface, for surfaces that
      are designed to be rendered as a layer of a stacked desktop-like
      environment.

      Layer surface state (layer, size, anchor, exclusive zone,
      margin, interactivity) is double-buffered, and will be applied at the
      time wl_surface.commit of the corresponding wl_surface is called.

      Attaching a null buffer to a layer surface unmaps it.

      Unmapping a layer_surface means that the surface cannot be shown by the
      compositor until it is explicitly mapped again. The layer_surface
      returns to the state it had right after layer_shell.get_layer_surface.
      The client can re-map the surface by performing a commit without any
      buffer attached, waiting for a configure event and handling it as usual.
    </description>

    <request name="set_size">
      <description summary="sets the size of the surface">
        Sets the size of the surface in surface-local coordinates. The
        compositor will display the surface centered with respect to its
        anchors.

        If you pass 0 for either value, the compositor will assign it and
        inform you of the assignment in the configure event. You must set your
        anchor to opposite edges in the dimensions you omit; not doing so is a
        protocol error. Both values are 0 by default.

        Size is double-buffered, see wl_surface.commit.
      </description>
      <arg name="width" type="uint"/>
      <arg name="height" type="uint"/>
    </request>

    <request name="set_anchor">
      <description summary="configures the anchor point of the surface">
        Requests that the compositor anchor the surface to the specified edges
        and corners. If two orthogonal edges are specified (e.g. 'top' and
        'left'), then the anchor point will be the intersection of the edges
        (e.g. the top left corner of the output); otherwise the anchor point
        will be centered on that edge, or in the center if none is specified.

        Anchor is double-buffered, see wl_surface.commit.
      </description>
      <arg name="anchor" type="uint" enum="anchor"/>
    </request>

    <request name="set_exclusive_zone">
      <description summary="configures the exclusive geometry of this surface">
        Requests that the compositor avoids occluding an area with other
        surfaces. The compositor's use of this information is
        implementation-dependent - do not assume that this region will not
        actually be occluded.

        A positive value is only meaningful if the surface is anchored to one
        edge or an edge and both perpendicular edges. If the surface is not
        anchored, anchored to only two perpendicular edges (a corner), anchored
        to only two parallel edges or anchored to all edges, a positive value
        will be treated the same as zero.

        A positive zone is the distance from the edge in surface-local
        coordinates to consider exclusive.

        Surfaces that do not wish to have an exclusive zone may instead specify
        how they should interact with surfaces that do. If set to zero, the
        surface indicates that it would like to be moved to avoid occluding
        surfaces with a positive exclusive zone. If set to -1, the surface
        indicates that it would not like to be moved to accommodate for other
        surfaces, and the compositor should extend it all the way to the edges
        it is anchored to.

        For example, a panel might set its exclusive zone to 10, so that
        maximized shell surfaces are not shown on top of it. A notification
        might set its exclusive zone to 0, so that it is moved to avoid
        occluding the panel, but shell surfaces are shown underneath it. A
        wallpaper or lock screen might set their exclusive zone to -1, so that
        they stretch below or over the panel.

        The default value is 0.

        Exclusive zone is double-buffered, see wl_surface.commit.
      </description>
      <arg name="zone" type="int"/>
    </request>

    <request name="set_margin">
      <description summary="sets a margin from the anchor point">
        Requests that the surface be placed some distance away from the anchor
        point on the output, in surface-local coordinates. Setting this value
        for edges you are not anchored to has no effect.

        The exclusive zone includes the margin.

        Margin is double-buffered, see wl_surface.commit.
      </description>
      <arg name="top" type="int"/>
      <arg name="right" type="int"/>
      <arg name="bottom" type="int"/>
      <arg name="left" type="int"/>
    </request>

    <enum name="keyboard_interactivity">
      <description summary="types of keyboard interaction possible for a layer shell surface">
        Types of keyboard interaction possible for layer shell surfaces. The
        rationale for this is twofold: (1) some applications are not interested
        in keyboard events and not allowing them to be focused can improve the
        desktop experience; (2) some applications will want to take exclusive
        keyboard focus.
      </description>

      <entry name="none" value="0">
        <description summary="no keyboard focus is possible">
          This value indicates that this surface is not interested in keyboard
          events and the compositor should never assign it the keyboard focus.

          This is the default value, set for newly created layer shell surfaces.

          This is useful for e.g. desktop widgets that display information or
          only have interaction with non-keyboard input devices.
        </description>
      </entry>
      <entry name="exclusive" value="1">
        <description summary="request exclusive keyboard focus">
          Request exclusive keyboard focus if this surface is above the shell surface layer.

          For the top and overlay layers, the seat will always give
          exclusive keyboard focus to the top-most layer which has keyboard
          interactivity set to exclusive. If this layer contains multiple
          surfaces with keyboard interactivity set to exclusive, the compositor
          determines the one receiving keyboard events in an implementation-
          defined manner. In this case, no guarantee is made when this surface
          will receive keyboard focus (if ever).

          For the bottom and background layers, the compositor is allowed to use
          normal focus semantics.

          This setting is mainly intended for applications that need to ensure
          they receive all keyboard events, such as a lock screen or a password
          prompt.
        </description>
      </entry>
      <entry name="on_demand" value="2" since="4">
        <description summary="request regular keyboard focus semantics">
          This requests the compositor to allow this surface to be focused and
          unfocused by the user in an implementation-defined manner. The user
          should be able to unfocus this surface even regardless of the layer
          it is on.

          Typically, the compositor will want to use its normal mechanism to
          manage keyboard focus between layer shell surfaces with this setting
          and regular toplevels on the desktop layer (e.g. click to focus).
          Nevertheless, it is possible for a compositor to require a special
          interaction to focus or unfocus layer shell surfaces (e.g. requiring
          a click even if focus follows the mouse normally, or providing a
          keybinding to switch focus between layers).

          This setting is mainly intended for desktop shell components (e.g.
          panels) that allow keyboard interaction. Using this option can allow
          implementing a desktop shell that can be fully usable without the
          mouse.
        </description>
      </entry>
    </enum>

    <request name="set_keyboard_interactivity">
      <description summary="requests keyboard events">
        Set how keyboard events are delivered to this surface. By default,
        layer shell surfaces do not receive keyboard events; this request can
        be used to change this.

        This setting is inherited by child surfaces set by the get_popup
        request.

        Layer surfaces receive pointer, touch, and tablet events normally. If
        you do not want to receive them, set the input region on your surface
        to an empty region.

        Keyboard interactivity is double-buffered, see wl_surface.commit.
      </description>
      <arg name="keyboard_interactivity" type="uint" enum="keyboard_interactivity"/>
    </request>

    <request name="get_popup">
      <description summary="assign this layer_surface as an xdg_popup parent">
        This assigns an xdg_popup's parent to this layer_surface.  This popup
        should have been created via xdg_surface::get_popup with the parent set
        to NULL, and this request must be invoked before committing the popup's
        initial state.

        See the documentation of xdg_popup for more details about what an
        xdg_popup is and how it is used.
      </description>
      <arg name="popup" type="object" interface="xdg_popup"/>
    </request>

    <request name="ack_configure">
      <description summary="ack a configure event">
        When a configure event is received, if a client commits the
        surface in response to the configure event, then the client
        must make an ack_configure request sometime before the commit
        request, passing along the serial of the configure event.

        If the client receives multiple configure events before it
        can respond to one, it only has to ack the last configure event.

        A client is not required to commit immediately after sending
        an ack_configure request - it may even ack_configure several times
        before its next surface commit.

        A client may send multiple ack_configure requests before committing, but
        only the last request sent before a commit indicates which configure
        event the client really is responding to.
      </description>
      <arg name="serial" type="uint" summary="the serial from the configure event"/>
    </request>

    <request name="destroy" type="destructor">
      <description summary="destroy the layer_surface">
        This request destroys the layer surface.
      </description>
    </request>

    <event name="configure">
      <description summary="suggest a surface change">
        The configure event asks the client to resize its surface.

        Clients should arrange their surface for the new states, and then send
        an ack_configure request with the serial sent in this configure event at
        some point before committing the new surface.

        The client is free to dismiss all but the last configure event it
        received.

        The width and height arguments specify the size of the window in
        surface-local coordinates.

        The size is a hint, in the sense that the client is free to ignore it if
        it doesn't resize, pick a smaller size (to satisfy aspect ratio or
        resize in steps of NxM pixels). If the client picks a smaller size and
        is anchored to two opposite anchors (e.g. 'top' and 'bottom'), the
        surface will be centered on this axis.

        If the width or height arguments are zero, it means the client should
        decide its own window dimension.
      </description>
      <arg name="serial" type="uint"/>
      <arg name="width" type="uint"/>
      <arg name="height" type="uint"/>
    </event>

    <event name="closed">
      <description summary="surface should be closed">
        The closed event is sent by the compositor when the surface will no
        longer be shown. The output may have been destroyed or the user may
        have asked for it to be removed. Further changes to the surface will be
        ignored. The client should destroy the resource after receiving this
        event, and create a new surface if they so choose.
      </description>
    </event>

    <enum name="error">
      <entry name="invalid_surface_state" value="0" summary="provided surface state is invalid"/>
      <entry name="invalid_size" value="1" summary="size is invalid"/>
      <entry name="invalid_anchor" value="2" summary="anchor bitfield is invalid"/>
      <entry name="invalid_keyboard_interactivity" value="3" summary="keyboard interactivity is invalid"/>
    </enum>

    <enum name="anchor" bitfield="true">
      <entry name="top" value="1" summary="the top edge of the anchor rectangle"/>
      <entry name="bottom" value="2" summary="the bottom edge of the anchor rectangle"/>
      <entry name="left" value="4" summary="the left edge of the anchor rectangle"/>
      <entry name="right" value="8" summary="the right edge of the anchor rectangle"/>
    </enum>

    <!-- Version 2 additions -->

    <request name="set_layer" since="2">
      <description summary="change the layer of the surface">
        Change the layer that the surface is rendered on.

        Layer is double-buffered, see wl_surface.commit.
      </description>
      <arg name="layer" type="uint" enum="zwlr_layer_shell_v1.layer" summary="layer to move this surface to"/>
    </request>
  </interface>
</protocol>


================================================
FILE: protocol/wlr-screencopy-unstable-v1.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="wlr_screencopy_unstable_v1">
  <copyright>
    Copyright © 2018 Simon Ser
    Copyright © 2019 Andri Yngvason

    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="screen content capturing on client buffers">
    This protocol allows clients to ask the compositor to copy part of the
    screen content to a client buffer.

    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_screencopy_manager_v1" version="3">
    <description summary="manager to inform clients and begin capturing">
      This object is a manager which offers requests to start capturing from a
      source.
    </description>

    <request name="capture_output">
      <description summary="capture an output">
        Capture the next frame of an entire output.
      </description>
      <arg name="frame" type="new_id" interface="zwlr_screencopy_frame_v1"/>
      <arg name="overlay_cursor" type="int"
        summary="composite cursor onto the frame"/>
      <arg name="output" type="object" interface="wl_output"/>
    </request>

    <request name="capture_output_region">
      <description summary="capture an output's region">
        Capture the next frame of an output's region.

        The region is given in output logical coordinates, see
        xdg_output.logical_size. The region will be clipped to the output's
        extents.
      </description>
      <arg name="frame" type="new_id" interface="zwlr_screencopy_frame_v1"/>
      <arg name="overlay_cursor" type="int"
        summary="composite cursor onto the frame"/>
      <arg name="output" type="object" interface="wl_output"/>
      <arg name="x" type="int"/>
      <arg name="y" type="int"/>
      <arg name="width" type="int"/>
      <arg name="height" type="int"/>
    </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_screencopy_frame_v1" version="3">
    <description summary="a frame ready for copy">
      This object represents a single frame.

      When created, a series of buffer events will be sent, each representing a
      supported buffer type. The "buffer_done" event is sent afterwards to
      indicate that all supported buffer types have been enumerated. The client
      will then be able to send a "copy" request. If the capture is successful,
      the compositor will send a "flags" followed by a "ready" event.

      For objects version 2 or lower, wl_shm buffers are always supported, ie.
      the "buffer" event is guaranteed to be sent.

      If the capture failed, the "failed" event is sent. This can happen anytime
      before the "ready" event.

      Once either a "ready" or a "failed" event is received, the client should
      destroy the frame.
    </description>

    <event name="buffer">
      <description summary="wl_shm buffer information">
        Provides information about wl_shm buffer parameters that need to be
        used for this frame. This event is sent once after the frame is created
        if wl_shm buffers are supported.
      </description>
      <arg name="format" type="uint" enum="wl_shm.format" summary="buffer format"/>
      <arg name="width" type="uint" summary="buffer width"/>
      <arg name="height" type="uint" summary="buffer height"/>
      <arg name="stride" type="uint" summary="buffer stride"/>
    </event>

    <request name="copy">
      <description summary="copy the frame">
        Copy the frame to the supplied buffer. The buffer must have a the
        correct size, see zwlr_screencopy_frame_v1.buffer and
        zwlr_screencopy_frame_v1.linux_dmabuf. The buffer needs to have a
        supported format.

        If the frame is successfully copied, a "flags" and a "ready" events are
        sent. Otherwise, a "failed" event is sent.
      </description>
      <arg name="buffer" type="object" interface="wl_buffer"/>
    </request>

    <enum name="error">
      <entry name="already_used" value="0"
        summary="the object has already been used to copy a wl_buffer"/>
      <entry name="invalid_buffer" value="1"
        summary="buffer attributes are invalid"/>
    </enum>

    <enum name="flags" bitfield="true">
      <entry name="y_invert" value="1" summary="contents are y-inverted"/>
    </enum>

    <event name="flags">
      <description summary="frame flags">
        Provides flags about the frame. This event is sent once before the
        "ready" event.
      </description>
      <arg name="flags" type="uint" enum="flags" summary="frame flags"/>
    </event>

    <event name="ready">
      <description summary="indicates frame is available for reading">
        Called as soon as the frame is copied, indicating it is available
        for reading. This event includes the time at which presentation happened
        at.

        The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples,
        each component being an unsigned 32-bit value. Whole seconds are in
        tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo,
        and the additional fractional part in tv_nsec as nanoseconds. Hence,
        for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part
        may have an arbitrary offset at start.

        After receiving this event, the client should destroy the object.
      </description>
      <arg name="tv_sec_hi" type="uint"
           summary="high 32 bits of the seconds part of the timestamp"/>
      <arg name="tv_sec_lo" type="uint"
           summary="low 32 bits of the seconds part of the timestamp"/>
      <arg name="tv_nsec" type="uint"
           summary="nanoseconds part of the timestamp"/>
    </event>

    <event name="failed">
      <description summary="frame copy failed">
        This event indicates that the attempted frame copy has failed.

        After receiving this event, the client should destroy the object.
      </description>
    </event>

    <request name="destroy" type="destructor">
      <description summary="delete this object, used or not">
        Destroys the frame. This request can be sent at any time by the client.
      </description>
    </request>

    <!-- Version 2 additions -->
    <request name="copy_with_damage" since="2">
      <description summary="copy the frame when it's damaged">
        Same as copy, except it waits until there is damage to copy.
      </description>
      <arg name="buffer" type="object" interface="wl_buffer"/>
    </request>

    <event name="damage" since="2">
      <description summary="carries the coordinates of the damaged region">
        This event is sent right before the ready event when copy_with_damage is
        requested. It may be generated multiple times for each copy_with_damage
        request.

        The arguments describe a box around an area that has changed since the
        last copy request that was derived from the current screencopy manager
        instance.

        The union of all regions received between the call to copy_with_damage
        and a ready event is the total damage since the prior ready event.
      </description>
      <arg name="x" type="uint" summary="damaged x coordinates"/>
      <arg name="y" type="uint" summary="damaged y coordinates"/>
      <arg name="width" type="uint" summary="current width"/>
      <arg name="height" type="uint" summary="current height"/>
    </event>

    <!-- Version 3 additions -->
    <event name="linux_dmabuf" since="3">
      <description summary="linux-dmabuf buffer information">
        Provides information about linux-dmabuf buffer parameters that need to
        be used for this frame. This event is sent once after the frame is
        created if linux-dmabuf buffers are supported.
      </description>
      <arg name="format" type="uint" summary="fourcc pixel format"/>
      <arg name="width" type="uint" summary="buffer width"/>
      <arg name="height" type="uint" summary="buffer height"/>
    </event>

    <event name="buffer_done" since="3">
      <description summary="all buffer types reported">
        This event is sent once after all buffer events have been sent.

        The client should proceed to create a buffer of one of the supported
        types, and send a "copy" request.
      </description>
    </event>
  </interface>
</protocol>


================================================
FILE: protocol/wlr-virtual-pointer-unstable-v1.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="wlr_virtual_pointer_unstable_v1">
  <copyright>
    Copyright © 2019 Josef Gajdusek

    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>

  <interface name="zwlr_virtual_pointer_v1" version="2">
    <description summary="virtual pointer">
      This protocol allows clients to emulate a physical pointer device. The
      requests are mostly mirror opposites of those specified in wl_pointer.
    </description>

    <enum name="error">
      <entry name="invalid_axis" value="0"
        summary="client sent invalid axis enumeration value" />
      <entry name="invalid_axis_source" value="1"
        summary="client sent invalid axis source enumeration value" />
    </enum>

    <request name="motion">
      <description summary="pointer relative motion event">
        The pointer has moved by a relative amount to the previous request.

        Values are in the global compositor space.
      </description>
      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
      <arg name="dx" type="fixed" summary="displacement on the x-axis"/>
      <arg name="dy" type="fixed" summary="displacement on the y-axis"/>
    </request>

    <request name="motion_absolute">
      <description summary="pointer absolute motion event">
        The pointer has moved in an absolute coordinate frame.

        Value of x can range from 0 to x_extent, value of y can range from 0
        to y_extent.
      </description>
      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
      <arg name="x" type="uint" summary="position on the x-axis"/>
      <arg name="y" type="uint" summary="position on the y-axis"/>
      <arg name="x_extent" type="uint" summary="extent of the x-axis"/>
      <arg name="y_extent" type="uint" summary="extent of the y-axis"/>
    </request>

    <request name="button">
      <description summary="button event">
        A button was pressed or released.
      </description>
      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
      <arg name="button" type="uint" summary="button that produced the event"/>
      <arg name="state" type="uint" enum="wl_pointer.button_state" summary="physical state of the button"/>
    </request>

    <request name="axis">
      <description summary="axis event">
        Scroll and other axis requests.
      </description>
      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
      <arg name="axis" type="uint" enum="wl_pointer.axis" summary="axis type"/>
      <arg name="value" type="fixed" summary="length of vector in touchpad coordinates"/>
    </request>

    <request name="frame">
      <description summary="end of a pointer event sequence">
        Indicates the set of events that logically belong together.
      </description>
    </request>

    <request name="axis_source">
      <description summary="axis source event">
        Source information for scroll and other axis.
      </description>
      <arg name="axis_source" type="uint" enum="wl_pointer.axis_source" summary="source of the axis event"/>
    </request>

    <request name="axis_stop">
      <description summary="axis stop event">
        Stop notification for scroll and other axes.
      </description>
      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
      <arg name="axis" type="uint" enum="wl_pointer.axis" summary="the axis stopped with this event"/>
    </request>

    <request name="axis_discrete">
      <description summary="axis click event">
        Discrete step information for scroll and other axes.

        This event allows the client to extend data normally sent using the axis
        event with discrete value.
      </description>
      <arg name="time" type="uint" summary="timestamp with millisecond granularity"/>
      <arg name="axis" type="uint" enum="wl_pointer.axis" summary="axis type"/>
      <arg name="value" type="fixed" summary="length of vector in touchpad coordinates"/>
      <arg name="discrete" type="int" summary="number of steps"/>
    </request>

    <request name="destroy" type="destructor" since="1">
      <description summary="destroy the virtual pointer object"/>
    </request>
  </interface>

  <interface name="zwlr_virtual_pointer_manager_v1" version="2">
    <description summary="virtual pointer manager">
      This object allows clients to create individual virtual pointer objects.
    </description>

    <request name="create_virtual_pointer">
      <description summary="Create a new virtual pointer">
        Creates a new virtual pointer. The optional seat is a suggestion to the
        compositor.
      </description>
      <arg name="seat" type="object" interface="wl_seat" allow-null="true"/>
      <arg name="id" type="new_id" interface="zwlr_virtual_pointer_v1"/>
    </request>

    <request name="destroy" type="destructor" since="1">
      <description summary="destroy the virtual pointer manager"/>
    </request>

    <!-- Version 2 additions -->
    <request name="create_virtual_pointer_with_output" since="2">
      <description summary="Create a new virtual pointer">
        Creates a new virtual pointer. The seat and the output arguments are
        optional. If the seat argument is set, the compositor should assign the
        input device to the requested seat. If the output argument is set, the
        compositor should map the input device to the requested output.
      </description>
      <arg name="seat" type="object" interface="wl_seat" allow-null="true"/>
      <arg name="output" type="object" interface="wl_output" allow-null="true"/>
      <arg name="id" type="new_id" interface="zwlr_virtual_pointer_v1"/>
    </request>
  </interface>
</protocol>


================================================
FILE: share/wl-kbptr.desktop
================================================
[Desktop Entry]
Version=1.0
Name=wl-kbptr
Comment=Control the mouse pointer with the keyboard
Exec=wl-kbptr
Terminal=false
Type=Application


================================================
FILE: src/config.c
================================================
#include "config.h"

#include "log.h"
#include "state.h"

#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * `field_color_parse` parses color field values, e.g.:
 *  - 6-digit hex color code (RRGGBB): `#123456`, `123456`
 *  - 8-digit hex color code (RRGGBBAA): `#12345678`, `12345678`
 *  - 3-digit hex color code (RGB): `#123`, `123`
 *  - 4-digit hex color code (RGBA): `#1234`, `1234`
 */
static int parse_color(void *dest, char *value) {
    if (value[0] == '#') {
        value++;
    }

    char digits[8];
    int  len = 0;
    for (int i = 0; value[i] != '\0'; i++) {
        if (++len > 8) {
            return 1;
        }

        char c = value[i];
        if (c >= '0' && c <= '9') {
            digits[i] = c - '0';
            continue;
        }

        c |= 1 << 5; // Makes the character lower case.
        if (c >= 'a' && c <= 'f') {
            digits[i] = c - 'a' + 10;
            continue;
        }

        return 2;
    }

    switch (len) {
    case 8:;
        *((uint32_t *)dest) = digits[7] | digits[6] << 4 |
                              digits[5] << (4 * 2) | digits[4] << (4 * 3) |
                              digits[3] << (4 * 4) | digits[2] << (4 * 5) |
                              digits[1] << (4 * 6) | digits[0] << (4 * 7);
        break;

    case 6:
        *((uint32_t *)dest) = 0xff | digits[5] << (4 * 2) |
                              digits[4] << (4 * 3) | digits[3] << (4 * 4) |
                              digits[2] << (4 * 5) | digits[1] << (4 * 6) |
                              digits[0] << (4 * 7);
        break;

    case 4:
        *((uint32_t *)dest) = digits[3] | digits[3] << 4 |
                              digits[2] << (4 * 2) | digits[2] << (4 * 3) |
                              digits[1] << (4 * 4) | digits[1] << (4 * 5) |
                              digits[0] << (4 * 6) | digits[0] << (4 * 7);
        break;

    case 3:
        *((uint32_t *)dest) = 0xff | digits[2] << (4 * 2) |
                              digits[2] << (4 * 3) | digits[1] << (4 * 4) |
                              digits[1] << (4 * 5) | digits[0] << (4 * 6) |
                              digits[0] << (4 * 7);
        break;

    default:
        return 4;
    }

    return 0;
}

static int parse_double(void *dest, char *value) {
    *((double *)dest) = atof(value);
    // TODO: handle errors better.
    return 0;
}

static int parse_uint8(void *dest, char *value) {
    int decoded = atoi(value);
    if (decoded < 0 || decoded >= 256) {
        LOG_ERR("Value should be between 0 and 255 (included).");
        return 1;
    }

    *((uint8_t *)dest) = (uint8_t)decoded;
    return 0;
}

static int parse_relative_font_size(void *dest, char *value) {
    struct relative_font_size *rfs = dest;

    static const char delims[] = " \t";

    int  s_len = strlen(value);
    char buf[s_len + 1];
    strcpy(buf, value);
    buf[s_len] = '\0';

    char *strtok_p;
    char *token = strtok_r(buf, delims, &strtok_p);

    if (token == NULL) {
        LOG_ERR("No minimum size.");
        return 1;
    }

    errno    = 0;
    rfs->min = strtod(token, NULL);
    if (errno) {
        LOG_ERR("Invalid minimum size.");
        return 1;
    }

    token = strtok_r(NULL, delims, &strtok_p);
    if (token == NULL) {
        LOG_ERR("No relative size.");
        return 1;
    }

    errno           = 0;
    rfs->proportion = strtod(token, NULL);
    if (token[strlen(token) - 1] == '%') {
        rfs->proportion /= 100.;
    }
    if (errno) {
        LOG_ERR("Invalid relative size.");
        return 1;
    }

    token = strtok_r(NULL, delims, &strtok_p);
    if (token == NULL) {
        LOG_ERR("No maximum size.");
        return 1;
    }

    errno    = 0;
    rfs->max = strtod(token, NULL);
    if (errno) {
        LOG_ERR("Invalid maximum size.");
        return 1;
    }

    if (rfs->min < 0) {
        LOG_ERR("Minimum size can't be negative.");
        return 1;
    }

    if (rfs->max < 0) {
        LOG_ERR("Maximum size can't be negative.");
        return 1;
    }

    if (rfs->proportion < 0) {
        LOG_ERR("Proportion can't be negative.");
        return 1;
    }

    if (rfs->min > rfs->max) {
        LOG_ERR("Minimum size can't be greater than maximum size.");
        return 1;
    }

    return 0;
}

static int parse_home_row_keys(void *dest, char *value) {
    char ***home_row_keys_ptr = dest;

    if (value[0] == '\0') {
        *home_row_keys_ptr = NULL;
        return 0;
    }

#define ASSERT_FOLLOW_UP_BYTE(c)           \
    if ((*c & 0b11000000) != 0b10000000) { \
        LOG_ERR("Encoding error.");        \
        goto err;                          \
    }

    char  *b    = malloc(HOME_ROW_LEN_WITH_BTN * 5);
    char **keys = malloc(HOME_ROW_LEN_WITH_BTN * sizeof(char *));

    char *c = value;

    for (int i = 0; i < HOME_ROW_LEN_WITH_BTN; i++) {
        if (*c == 0) {
            LOG_ERR("Could not parse home row keys. Not enough characters.");
            LOG_ERR(
                "Exactly 11 are required. The first 8 are used to select "
                "the sub-areas in the bisect mode."
            );
            LOG_ERR(
                "The next three characters are used for left, right and "
                "middle click respectively."
            );
            goto err;
        }

        if ((*c & 0b10000000) == 0) {
            b[i * 5]     = *c++;
            b[i * 5 + 1] = 0;
        } else if ((*c & 0b11100000) == 0b11000000) {
            b[i * 5] = *c++;
            ASSERT_FOLLOW_UP_BYTE(c);
            b[i * 5 + 1] = *c++;
            b[i * 5 + 2] = 0;
        } else if ((*c & 0b11110000) == 0b11100000) {
            b[i * 5] = *c++;
            ASSERT_FOLLOW_UP_BYTE(c);
            b[i * 5 + 1] = *c++;
            ASSERT_FOLLOW_UP_BYTE(c);
            b[i * 5 + 2] = *c++;
            b[i * 5 + 3] = 0;
        } else if ((*c & 0b11111000) == 0b11110000) {
            b[i * 5] = *c++;
            ASSERT_FOLLOW_UP_BYTE(c);
            b[i * 5 + 1] = *c++;
            ASSERT_FOLLOW_UP_BYTE(c);
            b[i * 5 + 2] = *c++;
            ASSERT_FOLLOW_UP_BYTE(c);
            b[i * 5 + 3] = *c++;
            b[i * 5 + 4] = 0;
        }

        keys[i] = &b[i * 5];
    }

    if (*c != '\0') {
        LOG_ERR("Too many characters. Exactly 11 are required.");
        goto err;
    }

    *home_row_keys_ptr = keys;

    return 0;

err:
    free(b);
    free(keys);
    return 1;
}

static int parse_str(void *dest, char *value) {
    *((char **)dest) = strdup(value);
    return 0;
}

static int parse_floating_mode_source_value(void *dest, char *value) {
    enum floating_mode_source *out = dest;
    if (strcmp(value, "stdin") == 0) {
        *out = FLOATING_MODE_SOURCE_STDIN;
    } else if (strcmp(value, "detect") == 0) {
#if OPENCV_ENABLED
        *out = FLOATING_MODE_SOURCE_DETECT;
#else
        LOG_ERR("Binary not build with OpenCV. 'detect' source not supported.");
        return 2;
#endif
    } else {
        LOG_ERR("Invalid source '%s'. Should be 'stdin' or 'detect'.", value);
        return 1;
    }

    return 0;
}

static int parse_click(void *dest, char *value) {
    enum click *out = dest;
    if (strcmp(value, "none") == 0) {
        *out = CLICK_NONE;
    } else if (strcmp(value, "left") == 0) {
        *out = CLICK_LEFT_BTN;
    } else if (strcmp(value, "right") == 0) {
        *out = CLICK_RIGHT_BTN;
    } else if (strcmp(value, "middle") == 0) {
        *out = CLICK_MIDDLE_BTN;
    } else {
        LOG_ERR(
            "Invalid click button '%s'. Should be 'left', 'right', 'middle' or "
            "'none'.",
            value
        );
        return 1;
    }

    return 0;
}

static void free_home_row_keys(void *field_value) {
    char ***home_row_keys_ptr = field_value;
    if (*home_row_keys_ptr == NULL) {
        return;
    }

    free(**home_row_keys_ptr);
    free(*home_row_keys_ptr);

    *home_row_keys_ptr = NULL;
}

static void free_str(void *field_value) {
    free(*((char **)field_value));
}

struct field_def {
    char  *name;
    size_t offset;
    char  *default_value;
    int (*parse)(void *dest, char *value);
    void (*free)(void *value);
};

struct section_def {
    char              *name;
    size_t             offset;
    struct field_def **fields;
};

#define SECTION(name, ...)                                             \
    (struct section_def) {                                             \
        #name, offsetof(struct config, name), (struct field_def *[]) { \
            __VA_ARGS__, NULL                                          \
        }                                                              \
    }

#define FIELD(type, name, default_value, parse, free)           \
    (struct field_def[]) {                                      \
        #name, offsetof(type, name), default_value, parse, free \
    }

#define G_FIELD(name, default_value, parse, free) \
    FIELD(struct general_config, name, default_value, parse, free)
#define MT_FIELD(name, default_value, parse, free) \
    FIELD(struct mode_tile_config, name, default_value, parse, free)
#define MF_FIELD(name, default_value, parse, free) \
    FIELD(struct mode_floating_config, name, default_value, parse, free)
#define MB_FIELD(name, default_value, parse, free) \
    FIELD(struct mode_bisect_config, name, default_value, parse, free)
#define MS_FIELD(name, default_value, parse, free) \
    FIELD(struct mode_split_config, name, default_value, parse, free)
#define MC_FIELD(name, default_value, parse, free) \
    FIELD(struct mode_click_config, name, default_value, parse, free)

static void noop() {}

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-braces"
static struct section_def section_defs[] = {
    SECTION(
        general,
        G_FIELD(home_row_keys, "", parse_home_row_keys, free_home_row_keys),
        G_FIELD(modes, "tile,bisect", parse_str, free_str),
        G_FIELD(cancellation_status_code, "0", parse_uint8, noop)
    ),
    SECTION(
        mode_tile, MT_FIELD(label_color, "#fffd", parse_color, noop),
        MT_FIELD(label_select_color, "#fd0d", parse_color, noop),
        MT_FIELD(unselectable_bg_color, "#2226", parse_color, noop),
        MT_FIELD(selectable_bg_color, "#0304", parse_color, noop),
        MT_FIELD(selectable_border_color, "#040c", parse_color, noop),
        MT_FIELD(label_font_family, "sans-serif", parse_str, free_str),
        MT_FIELD(label_font_size, "8 50% 100", parse_relative_font_size, noop),
        MT_FIELD(
            label_symbols, "abcdefghijklmnopqrstuvwxyz", parse_str, free_str
        )
    ),
    SECTION(
        mode_floating,
        MF_FIELD(source, "stdin", parse_floating_mode_source_value, noop),
        MF_FIELD(label_color, "#fffd", parse_color, noop),
        MF_FIELD(label_select_color, "#fd0d", parse_color, noop),
        MF_FIELD(unselectable_bg_color, "#2226", parse_color, noop),
        MF_FIELD(selectable_bg_color, "#1718", parse_color, noop),
        MF_FIELD(selectable_border_color, "#040c", parse_color, noop),
        MF_FIELD(label_font_family, "sans-serif", parse_str, free_str),
        MF_FIELD(label_font_size, "12 50% 100", parse_relative_font_size, noop),
        MF_FIELD(
            label_symbols, "abcdefghijklmnopqrstuvwxyz", parse_str, free_str
        )
    ),
    SECTION(
        mode_bisect, MB_FIELD(label_color, "#fffd", parse_color, noop),
        // TODO: we should set minimums for numbers.
        MB_FIELD(label_font_size, "20", parse_double, noop),
        MB_FIELD(label_font_family, "sans-serif", parse_str, free_str),
        MB_FIELD(label_padding, "12", parse_double, noop),
        MB_FIELD(pointer_size, "20", parse_double, noop),
        MB_FIELD(pointer_color, "#e22d", parse_color, noop),
        MB_FIELD(unselectable_bg_color, "#2226", parse_color, noop),
        MB_FIELD(even_area_bg_color, "#0304", parse_color, noop),
        MB_FIELD(even_area_border_color, "#0408", parse_color, noop),
        MB_FIELD(odd_area_bg_color, "#0034", parse_color, noop),
        MB_FIELD(odd_area_border_color, "#0048", parse_color, noop),
        MB_FIELD(history_border_color, "#3339", parse_color, noop)
    ),
    SECTION(
        mode_split, MS_FIELD(pointer_size, "20", parse_double, noop),
        MS_FIELD(pointer_color, "#e22d", parse_color, noop),
        MS_FIELD(bg_color, "#2226", parse_color, noop),
        MS_FIELD(area_bg_color, "#11111188", parse_color, noop),
        MS_FIELD(vertical_color, "#8888ffcc", parse_color, noop),
        MS_FIELD(horizontal_color, "#008800cc", parse_color, noop),
        MS_FIELD(history_border_color, "#3339", parse_color, noop)
    ),
    SECTION(mode_click, MC_FIELD(button, "left", parse_click, noop)),
};
#pragma GCC diagnostic pop

void print_default_config() {
    puts("# wl-kbptr can be configured with a configuration file.");
    puts("# The file location can be passed with the -c parameter.");
    puts("# Othewise the `$XDG_CONFIG_HOME/wl-kbptr/config` file will");
    puts("# be loaded if it exits. Below is the default configuration.");

    for (int i = 0; i < sizeof(section_defs) / sizeof(section_defs[0]); i++) {
        struct section_def *section_def = &section_defs[i];

        printf("\n[%s]\n", section_def->name);

        for (struct field_def **field_def_ptr = section_def->fields;
             *field_def_ptr != NULL; field_def_ptr++) {
            struct field_def *field_def = *field_def_ptr;

            printf("%s=%s\n", field_def->name, field_def->default_value);
        }
    }
}

void config_loader_init(struct config_loader *loader, struct config *config) {
    loader->config           = config;
    loader->curr_section_def = &section_defs[0];
}

int config_loader_enter_section(struct config_loader *loader, char *section) {
    for (int i = 0; i < sizeof(section_defs) / sizeof(section_defs[0]); i++) {
        struct section_def *section_def = &section_defs[i];

        if (strcmp(section, section_def->name) == 0) {
            loader->curr_section_def = section_def;
            return 0;
        }
    }

    LOG_ERR("Configuration section `%s` does not exist.", section);
    return 1;
}

int config_loader_load_field(
    struct config_loader *loader, char *name, char *value
) {
    struct section_def *section_def = loader->curr_section_def;

    for (struct field_def **field_defs = section_def->fields;
         *field_defs != NULL; field_defs++) {
        struct field_def *field_def = *field_defs;

        if (strcmp(name, field_def->name) == 0) {
            void *dest = ((void *)loader->config) + section_def->offset +
                         field_def->offset;
            field_def->free(dest);
            int err = field_def->parse(dest, value);
            if (err != 0) {
                LOG_ERR("Invalid value for %s.%s.", section_def->name, name);
                return 2;
            }

            return 0;
        }
    }

    LOG_ERR(
        "Configuration option `%s.%s` does not exist.", section_def->name, name
    );
    return 1;
}

int config_loader_load_cli_param(struct config_loader *loader, char *value) {
    // `buf` will hold a copy of the section and field name as
    // `section\0field\0`.
    char buf[strlen(value)];

    // `bc` holds the current position in `buf`. Each time we write to `buf`
    // this pointer is incremented.
    char *bc = buf;

    // `c` holds the current position in `value`.
    char *c = value;

    char *section = buf;
    while (*c != '\0' && *c != '.' && *c != '=') {
        *(bc++) = *(c++);
    }

    char *field_name;

    if (*c == '.') {
        *(bc++) = '\0';
        c++;

        field_name = bc;
        while (*c != '\0' && *c != '=') {
            *(bc++) = *(c++);
        }
    } else {
        field_name = section;
        section    = "general";
    }

    if (*c != '=') {
        LOG_ERR("Invalid configuration parameter `%s`.", value);
        return 1;
    }

    *(bc++) = '\0';
    c++;

    int err = config_loader_enter_section(loader, section);
    if (err != 0) {
        return 2;
    }

    char *field_value = c;
    err = config_loader_load_field(loader, field_name, field_value);
    if (err != 0) {
        return 3;
    }

    return 0;
}

void config_set_default(struct config *config) {
    for (int i = 0; i < sizeof(section_defs) / sizeof(section_defs[0]); i++) {
        struct section_def *section_def = &section_defs[i];
        for (struct field_def **field_def_ptr = section_def->fields;
             *field_def_ptr != NULL; field_def_ptr++) {
            struct field_def *field_def = *field_def_ptr;

            int err = field_def->parse(
                ((void *)config) + section_def->offset + field_def->offset,
                field_def->default_value
            );
            if (err != 0) {
                LOG_ERR(
                    "Could not set default value '%s' for %s.%s.",
                    field_def->default_value, section_def->name, field_def->name
                );
            }
        }
    }
}

void config_free_values(struct config *config) {
    for (int i = 0; i < sizeof(section_defs) / sizeof(section_defs[0]); i++) {
        struct section_def *section_def = &section_defs[i];
        for (struct field_def **field_def_ptr = section_def->fields;
             *field_def_ptr != NULL; field_def_ptr++) {
            struct field_def *field_def = *field_def_ptr;

            field_def->free(
                ((void *)config) + section_def->offset + field_def->offset
            );
        }
    }
}

static const char *XDG_PATH_FMT = "%s/wl-kbptr/config";

static FILE *open_config_file(char *file_name) {
    FILE *f = NULL;

    if (file_name != NULL) {
        f = fopen(file_name, "r");
        if (f == NULL) {
            LOG_ERR("Could not open config file '%s'", file_name);
            return NULL;
        }

        LOG_INFO("Loading config file '%s'", file_name);
        return f;
    }

    char       *xdg_config_home     = getenv("XDG_CONFIG_HOME");
    const char *home                = getenv("HOME");
    size_t      config_home_buf_len = 0;

    if (xdg_config_home == NULL && home != NULL) {
        config_home_buf_len = strlen(home) + sizeof("/.config");
    }

    char config_home_buf[config_home_buf_len];

    if (xdg_config_home == NULL && home != NULL) {
        snprintf(config_home_buf, config_home_buf_len, "%s/.config", home);
        xdg_config_home = config_home_buf;
    }

    if (xdg_config_home != NULL) {
        int  path_len = snprintf(NULL, 0, XDG_PATH_FMT, xdg_config_home) + 1;
        char file_path[path_len];
        snprintf(file_path, path_len, XDG_PATH_FMT, xdg_config_home);

        f = fopen(file_path, "r");
        if (f == NULL) {
            LOG_WARN("Could not open config file '%s'", file_path);
            return NULL;
        }

        LOG_INFO("Loading config file '%s'", file_path);
    }

    return f;
}

static const char *WHITE_SPACES = "\r\t ";

int config_loader_load_file(struct config_loader *loader, char *file_name) {
    FILE *f = open_config_file(file_name);
    if (f == NULL) {
        return file_name == NULL ? 0 : 1;
    }

    char buf[256];
    int  c = 0, i, err;

    for (int line; c != EOF; line++) {
        do {
            c = getc(f);
        } while (strchr(WHITE_SPACES, c) != NULL);

        switch (c) {
        // Comment
        case '#':
            do {
                c = getc(f);
            } while (c != '\n' && c != EOF);
            break;

        // Section
        case '[':
            for (i = 0; i < (sizeof(buf) - 1) && (c = getc(f)) != ']'; i++) {
                if (c == EOF) {
                    LOG_ERR(
                        "Unexpected end of file. Section was not terminated."
                    );
                    goto err;
                } else if (c == '\n') {
                    LOG_ERR(
                        "Unexpected end of line. Section was not terminated."
                    );
                    goto err;
                }
                buf[i] = c;
            }

            if (c != ']') {
                LOG_ERR("Line is too long.");
                goto err;
            }

            buf[i] = '\0';

            do {
                c = getc(f);
                if (strchr(WHITE_SPACES, c) != NULL) {
                    LOG_ERR(
                        "Only whitespaces are allowed after a section's ending "
                        "delimiter."
                    );
                    goto err;
                }
            } while (c != '\n' && c != EOF);

            err = config_loader_enter_section(loader, buf) != 0;
            if (err) {
                goto err;
            }
            break;

        // Empty line
        case '\n':
            break;

        case EOF:
            goto success;

        // key=value
        default:
            buf[0] = c;
            for (i = 1; i < (sizeof(buf) - 1) && (c = getc(f)) != '='; i++) {
                if (c == EOF) {
                    LOG_ERR("Unexpected end of file. Expected equal operator.");
                    goto err;
                } else if (c == '\n') {
                    LOG_ERR("Unexpected end of line. Expected equal operator.");
                    goto err;
                }
                buf[i] = c;
            }

            if (c != '=') {
                LOG_ERR("Line is too long");
                goto err;
            }

            buf[i++] = '\0';

            char *value = &buf[i];
            for (; i < (sizeof(buf)); i++) {
                c = getc(f);
                if (c == EOF || c == '\n') {
                    break;
                } else if (c == '\r') {
                    continue;
                }

                buf[i] = c;
            }

            if (i == sizeof(buf)) {
                LOG_ERR("Line is too long");
            }

            buf[i] = '\0';

            err = config_loader_load_field(loader, buf, value);
            if (err) {
                goto err;
            }
        }
    }

success:
    fclose(f);
    return 0;

err:
    fclose(f);
    return 1;
}

double
compute_relative_font_size(struct relative_font_size *rfs, double height) {
    double value = height * rfs->proportion;
    if (value < rfs->min) {
        return rfs->min;
    }

    if (value > rfs->max) {
        return rfs->max;
    }

    return value;
}


================================================
FILE: src/config.h
================================================
#ifndef __CONFIG_H_INCLUDED__
#define __CONFIG_H_INCLUDED__

#include "utils.h"

#include <stdint.h>

struct general_config {
    char  **home_row_keys;
    char   *modes;
    uint8_t cancellation_status_code;
};

struct relative_font_size {
    double proportion;
    double min;
    double max;
};

struct mode_tile_config {
    uint32_t                  label_color;
    uint32_t                  label_select_color;
    uint32_t                  unselectable_bg_color;
    uint32_t                  selectable_bg_color;
    uint32_t                  selectable_border_color;
    char                     *label_font_family;
    struct relative_font_size label_font_size;
    char                     *label_symbols;
};

enum floating_mode_source {
    FLOATING_MODE_SOURCE_STDIN,
    FLOATING_MODE_SOURCE_DETECT,
};

struct mode_floating_config {
    enum floating_mode_source source;
    uint32_t                  label_color;
    uint32_t                  label_select_color;
    uint32_t                  unselectable_bg_color;
    uint32_t                  selectable_bg_color;
    uint32_t                  selectable_border_color;
    char                     *label_font_family;
    struct relative_font_size label_font_size;
    char                     *label_symbols;
};

struct mode_bisect_config {
    uint32_t label_color;
    double   label_font_size;
    char    *label_font_family;
    double   label_padding;

    double  pointer_size;
    int32_t pointer_color;

    uint32_t unselectable_bg_color;
    uint32_t even_area_bg_color;
    uint32_t even_area_border_color;
    uint32_t odd_area_bg_color;
    uint32_t odd_area_border_color;

    uint32_t history_border_color;
};

struct mode_split_config {
    double  pointer_size;
    int32_t pointer_color;

    uint32_t bg_color;
    uint32_t area_bg_color;
    uint32_t vertical_color;
    uint32_t horizontal_color;

    uint32_t history_border_color;
};

struct mode_click_config {
    enum click button;
};

struct config {
    struct general_config       general;
    struct mode_tile_config     mode_tile;
    struct mode_floating_config mode_floating;
    struct mode_bisect_config   mode_bisect;
    struct mode_split_config    mode_split;
    struct mode_click_config    mode_click;
};

/**
 * The `config_loader` structure stores needed states to set parse values.
 */
struct config_loader {
    struct config *config;
    void          *curr_section_def;
};

void print_default_config();

/**
 * `config_set_default` sets default values set in the configuration's
 * definitions.
 */
void config_set_default(struct config *config);

/**
 * `config_free_values` frees configuration fields' values. This doesn't free
 * the `config` structure itself.
 */
void config_free_values(struct config *config);

/**
 * `config_loader_init` initialise the `config_loader` structure.
 */
void config_loader_init(
    struct config_loader *config_loader, struct config *config
);

/**
 * `config_loader_enter_section` sets the current section's state. Following
 * calls to `config_loader_load_field` will load fields for the given section.
 */
int config_loader_enter_section(struct config_loader *loader, char *section);

/**
 * `config_loader_load_field` loads the give field value from the current
 * section.
 */
int config_loader_load_field(
    struct config_loader *loader, char *name, char *value
);

/**
 * `config_loader_load_cli_param` loads a configuration value from a CLI
 * parameter value, e.g. `mode_bisect.label_color=#66666666`.
 */
int config_loader_load_cli_param(struct config_loader *loader, char *value);

/**
 * `config_loader_load_file` loads configuration values from the given file or
 * from one of the default locations (if `file_name` is NULL).
 */
int config_loader_load_file(struct config_loader *loader, char *file_name);

double
compute_relative_font_size(struct relative_font_size *rfs, double height);

#endif


================================================
FILE: src/label.c
================================================
#include "label.h"

#include "log.h"
#include "utils.h"

#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

label_symbols_t *label_symbols_from_str(char *s) {
    char *c = s;

    uint32_t r;
    int      c_len;

    int len         = sizeof(label_symbols_t);
    int num_symbols = 0;

    while ((c_len = str_to_rune(c, &r)) > 0) {
        // One byte for the indices and one of the end of string (`\0`).
        c           += c_len;
        len         += c_len + 2;
        num_symbols += 1;
    }

    if (c_len < 0) {
        LOG_ERR("Invalid UTF-8 input.");
        return NULL;
    }

    if (num_symbols < 2) {
        LOG_ERR(
            "Not enough characters (%d). Must have at least 2.", num_symbols
        );
        return NULL;
    }

    if (num_symbols >= 255) {
        LOG_ERR("Too many characters (%d).", num_symbols);
        return NULL;
    }

    label_symbols_t *label_symbols = malloc(len);

    label_symbols->num_symbols = num_symbols;
    unsigned char *indices     = (unsigned char *)label_symbols->data;
    char          *str         = &label_symbols->data[num_symbols];

    c              = s;
    int str_offset = 0;
    for (int i = 0; i < num_symbols; i++) {
        c_len      = str_to_rune(c, &r);
        indices[i] = str_offset;
        memcpy(str + str_offset, c, c_len);
        str[str_offset + c_len] = '\0';

        str_offset += c_len + 1;
        c          += c_len;
    }

    return label_symbols;
}

void label_symbols_free(label_symbols_t *ls) {
    free(ls);
}

char *label_symbols_idx_to_ptr(label_symbols_t *label_symbols, int idx) {
    if (idx < 0 || idx >= label_symbols->num_symbols) {
        LOG_ERR("Label symbols index (%d) out of bound.", idx);
        return NULL;
    }

    return ((char *)label_symbols->data) + label_symbols->num_symbols +
           ((unsigned char *)label_symbols->data)[idx];
}

int label_symbols_find_idx(label_symbols_t *label_symbols, char *s) {
    for (int i = 0; i < label_symbols->num_symbols; i++) {
        if (strcmp(label_symbols_idx_to_ptr(label_symbols, i), s) == 0) {
            return i;
        }
    }

    return -1;
}

label_selection_t *
label_selection_new(label_symbols_t *label_symbols, int num_labels) {
    label_selection_t *l = malloc(sizeof(*l) + label_symbols->num_symbols);

    l->num_labels = num_labels;

    l->len = 0;
    while (num_labels > 0) {
        l->len++;
        num_labels /= label_symbols->num_symbols;
    }

    l->next          = 0;
    l->label_symbols = label_symbols;
    return l;
}

void label_selection_clear(label_selection_t *label_selection) {
    label_selection->next = 0;
}

static int label_selection_to_partial_idx(label_selection_t *label_selection) {
    int idx         = 0;
    int factor      = 1;
    int num_symbols = label_selection->label_symbols->num_symbols;

    for (int i = 0; i < label_selection->next; i++) {
        idx    += label_selection->input[i] * factor;
        factor *= num_symbols;
    }

    return idx;
}

enum label_selection_append_ret
label_selection_append(label_selection_t *label_selection, int idx) {
    if (label_selection->next >= label_selection->label_symbols->num_symbols) {
        return LABEL_SELECTION_APPEND_FULL;
    }

    label_selection->input[label_selection->next++] = idx;

    if (label_selection_to_partial_idx(label_selection) >=
        label_selection->num_labels) {
        label_selection->next--;
        return LABEL_SELECTION_APPEND_IDX_OVERFLOW;
    }

    return LABEL_SELECTION_APPEND_SUCCESS;
}

bool label_selection_back(label_selection_t *label_selection) {
    if (label_selection->next == 0) {
        return false;
    }

    label_selection->next--;
    return true;
}

bool label_selection_is_included(
    label_selection_t *reference, label_selection_t *start
) {
    if (reference->label_symbols != start->label_symbols ||
        reference->len != start->len || reference->next < start->next) {
        return false;
    }

    for (int i = 0; i < start->next; i++) {
        if (reference->input[i] != start->input[i]) {
            return false;
        }
    }

    return true;
}

int label_selection_to_idx(label_selection_t *label_selection) {
    if (label_selection->next != label_selection->len) {
        return -1;
    }

    return label_selection_to_partial_idx(label_selection);
}

int label_selection_set_from_idx(label_selection_t *label_selection, int idx) {
    int num_symbols = label_selection->label_symbols->num_symbols;

    for (label_selection->next = 0;
         label_selection->next < label_selection->len;
         label_selection->next++) {
        label_selection->input[label_selection->next]  = idx % num_symbols;
        idx                                           /= num_symbols;
    }

    return idx == 0;
}

int label_selection_incr(label_selection_t *label_selection) {
    int num_symbols = label_selection->label_symbols->num_symbols;

    for (int i = 0; i < label_selection->len; i++) {
        label_selection->input[i] += 1;

        if (label_selection->input[i] < num_symbols) {
            return 1;
        }

        label_selection->input[i] %= num_symbols;
    }

    return 0;
}

static int label_symbols_max_str_len(label_symbols_t *label_symbols) {
    unsigned char *indices = (unsigned char *)label_symbols->data;
    int            i;

    int max_len  = 0;
    int curr_len = 0;

    for (i = 1; i < label_symbols->num_symbols; i++) {
        curr_len = indices[i] - indices[i - 1] - 1;
        if (curr_len > max_len) {
            max_len = curr_len;
        }
    }

    curr_len = strlen(
        label_symbols_idx_to_ptr(label_symbols, label_symbols->num_symbols - 1)
    );
    if (curr_len > max_len) {
        max_len = curr_len;
    }

    return max_len;
}

int label_selection_str_max_len(label_selection_t *label_selection) {
    return label_symbols_max_str_len(label_selection->label_symbols) *
           label_selection->len;
}

void label_selection_str(label_selection_t *label_selection, char *out) {
    label_symbols_t *label_symbols = label_selection->label_symbols;
    for (int i = 0; i < label_selection->next; i++) {
        out = stpcpy(
            out,
            label_symbols_idx_to_ptr(label_symbols, label_selection->input[i])
        );
    }

    *out = '\0';
}

void label_selection_str_split(
    label_selection_t *label_selection, char *prefix, char *suffix, int cut
) {
    if (cut < 0) {
        cut = 0;
    } else if (cut >= label_selection->next) {
        cut = label_selection->next;
    }

    label_symbols_t *label_symbols = label_selection->label_symbols;
    for (int i = 0; i < cut; i++) {
        prefix = stpcpy(
            prefix,
            label_symbols_idx_to_ptr(label_symbols, label_selection->input[i])
        );
    }
    *prefix = '\0';

    for (int i = cut; i < label_selection->next; i++) {
        suffix = stpcpy(
            suffix,
            label_symbols_idx_to_ptr(label_symbols, label_selection->input[i])
        );
    }
    *suffix = '\0';
}

void label_selection_free(label_selection_t *label_selection) {
    free(label_selection);
}


================================================
FILE: src/label.h
================================================
#ifndef __LABEL_H_INCLUDED__
#define __LABEL_H_INCLUDED__

#include <stdbool.h>

typedef struct {
    /*         data             data[num_symbols]
     *         |                |
     *  | 4 || 0 | 2 | 4 | 6 ||`a`| 0 |`b`| 0 |`c`| 0 |`d`| 0 |
     *    ^    ^-----------^    ^---------------------------^
     *    |       offsets               strings
     *    |
     *  number of symbols
     */
    unsigned char num_symbols;
    char          data[];
} label_symbols_t;

typedef struct {
    label_symbols_t *label_symbols;
    int              num_labels;
    unsigned char    len;
    unsigned char    next;
    unsigned char    input[];
} label_selection_t;

// Create a `label_symbols_t` from a string of characters.
// Returns `NULL` upon error.
label_symbols_t *label_symbols_from_str(char *s);

// Free memory of a `label_symbols_t`.
void label_symbols_free(label_symbols_t *ls);

// Get pointer to string of the symbol at given index.
// Returns value <0 upon error.
char *label_symbols_idx_to_ptr(label_symbols_t *label_symbols, int idx);

// Find symbol index from given string.
// Returns value <0 upon error.
int label_symbols_find_idx(label_symbols_t *label_symbols, char *s);

// Create a `label_selection_t`.
label_selection_t *
label_selection_new(label_symbols_t *label_symbols, int num_labels);

// Clear selection.
void label_selection_clear(label_selection_t *label_selection);

enum label_selection_append_ret {
    LABEL_SELECTION_APPEND_SUCCESS      = 0,
    LABEL_SELECTION_APPEND_IDX_OVERFLOW = 1,
    LABEL_SELECTION_APPEND_FULL         = 2
};
// Append to selection.
enum label_selection_append_ret
label_selection_append(label_selection_t *label_selection, int idx);

// Erase last symbol.
// Returns true if it did else false.
bool label_selection_back(label_selection_t *label_selection);

// Returns true if `start` is the same as `reference` beginning else false.
bool label_selection_is_included(
    label_selection_t *reference, label_selection_t *start
);

// Returns associated label index.
int label_selection_to_idx(label_selection_t *label_selection);

// Set selection from associated index.
int label_selection_set_from_idx(label_selection_t *label_selection, int idx);

// Set to selection with incremented associated index.
int label_selection_incr(label_selection_t *label_selection);

// Get size of buffer needed to store label's string.
int label_selection_str_max_len(label_selection_t *label_selection);

// Get label's string.
void label_selection_str(label_selection_t *label_selection, char *out);

// Get label string split at `cut`.
void label_selection_str_split(
    label_selection_t *label_selection, char *prefix, char *suffix, int cut
);

// Free memory of `label_selection_t`.
void label_selection_free(label_selection_t *label_selection);

#endif


================================================
FILE: src/log.h
================================================
#ifndef __LOG_H_INCLUDED__
#define __LOG_H_INCLUDED__

#include <stdio.h>

#define LOG_ERR(msg, ...) \
    fprintf(stderr, "\x1b[31merr:\x1b[0m " msg "\n", ##__VA_ARGS__)

#define LOG_WARN(msg, ...) \
    fprintf(stderr, "\x1b[33mwarn:\x1b[0m " msg "\n", ##__VA_ARGS__)

#define LOG_INFO(msg, ...) \
    fprintf(stderr, "\x1b[34minfo:\x1b[0m " msg "\n", ##__VA_ARGS__)

#ifdef DEBUG
#define LOG_DEBUG(msg, ...) \
    fprintf(stderr, "\x1b[35mdebug:\x1b[0m " msg "\n", ##__VA_ARGS__)
#else
#define LOG_DEBUG(msg, ...) ((void)0)
#endif

#endif


================================================
FILE: src/main.c
================================================
#include "config.h"
#include "fractional-scale-v1-client-protocol.h"
#include "log.h"
#include "mode.h"
#include "state.h"
#include "surface_buffer.h"
#include "utils_wayland.h"
#include "viewporter-client-protocol.h"
#include "wlr-layer-shell-unstable-v1-client-protocol.h"
#include "wlr-screencopy-unstable-v1-client-protocol.h"
#include "wlr-virtual-pointer-unstable-v1-client-protocol.h"
#include "xdg-output-unstable-v1-client-protocol.h"

#include <cairo/cairo.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <wayland-client-protocol.h>
#include <wayland-client.h>
#include <wayland-util.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <xkbcommon/xkbcommon.h>

static void send_frame(struct state *state) {
    int32_t scale_120 = state->fractional_scale;
    if (scale_120 == 0) {
        // Falling back to the output scale if fractional scale is not received.
        scale_120 =
            (state->current_output == NULL ? 1 : state->current_output->scale) *
            120;
    }

    struct surface_buffer *surface_buffer = get_next_buffer(
        state->wl_shm, &state->surface_buffer_pool,
        state->surface_width * scale_120 / 120,
        state->surface_height * scale_120 / 120
    );
    if (surface_buffer == NULL) {
        return;
    }
    surface_buffer->state = SURFACE_BUFFER_BUSY;

    cairo_t *cairo = surface_buffer->cairo;
    cairo_identity_matrix(cairo);
    cairo_scale(cairo, scale_120 / 120.0, scale_120 / 120.0);
    mode_render(state, cairo);

    wl_surface_set_buffer_scale(state->wl_surface, 1);

    wl_surface_attach(state->wl_surface, surface_buffer->wl_buffer, 0, 0);
    wp_viewport_set_destination(
        state->wp_viewport, state->surface_width, state->surface_height
    );
    wl_surface_damage(
        state->wl_surface, 0, 0, state->surface_width, state->surface_height
    );
    wl_surface_commit(state->wl_surface);
}

/**
 * Send a 1x1px transparent surface.
 *
 * This is used so that the surface is shown on the screen which triggers the
 * `surface.enter()` event callback.
 */
static void send_transparent_frame(struct state *state) {
    struct surface_buffer *surface_buffer =
        get_next_buffer(state->wl_shm, &state->surface_buffer_pool, 1, 1);
    if (surface_buffer == NULL) {
        return;
    }
    surface_buffer->state = SURFACE_BUFFER_BUSY;
    cairo_t *cairo        = surface_buffer->cairo;
    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
    cairo_set_source_rgba(cairo, 0, 0, 0, 0);
    cairo_fill(cairo);
    wl_surface_attach(state->wl_surface, surface_buffer->wl_buffer, 0, 0);
    wp_viewport_set_destination(
        state->wp_viewport, state->surface_width, state->surface_height
    );
    wl_surface_damage(state->wl_surface, 0, 0, 1, 1);
    wl_surface_commit(state->wl_surface);
}

static void surface_callback_done(
    void *data, struct wl_callback *callback, uint32_t callback_data
) {
    struct state *state = data;
    send_frame(state);

    wl_callback_destroy(state->wl_surface_callback);
    state->wl_surface_callback = NULL;
}

const struct wl_callback_listener surface_callback_listener = {
    .done = surface_callback_done,
};

static void request_frame(struct state *state) {
    if (state->wl_surface_callback != NULL) {
        return;
    }

    state->wl_surface_callback = wl_surface_frame(state->wl_surface);
    wl_callback_add_listener(
        state->wl_surface_callback, &surface_callback_listener, state
    );
    wl_surface_commit(state->wl_surface);
}

bool compute_initial_area(struct state *state, struct rect *initial_area) {
    if (initial_area->w == -1) {
        initial_area->x = 0;
        initial_area->y = 0;
        initial_area->w = state->surface_width;
        initial_area->h = state->surface_height;
    } else {
        if (initial_area->x < 0) {
            initial_area->w += initial_area->x;
            initial_area->x  = 0;
        }

        if (initial_area->y < 0) {
            initial_area->h += initial_area->y;
            initial_area->y  = 0;
        }

        if (initial_area->w + initial_area->x > state->current_output->width) {
            initial_area->w = state->current_output->width - initial_area->x;
        }

        if (initial_area->h + initial_area->y > state->current_output->height) {
            initial_area->h = state->current_output->height - initial_area->y;
        }
    }

    if (initial_area->w <= 0 || initial_area->h <= 0) {
        LOG_ERR(
            "Initial area (%dx%d) is too small.", initial_area->w,
            initial_area->h
        );
        return false;
    }

    return true;
}

static void noop() {}

static void load_home_row(
    struct xkb_keymap *keymap, char **home_row, char *home_row_buffer
) {
    static const xkb_keycode_t key_codes[] = {
        0x26, // a
        0x27, // s
        0x28, // d
        0x29, // f
        0x2c, // j
        0x2d, // k
        0x2e, // l
        0x2f, // m
        0x2a, // g
        0x2b, // h
        0x38, // b
    };

    struct xkb_state *xkb_state   = xkb_state_new(keymap);
    char             *buffer      = home_row_buffer;
    size_t            buffer_size = HOME_ROW_BUFFER_LEN;

    for (int i = 0; i < sizeof(key_codes) / sizeof(key_codes[0]); i++) {
        xkb_keysym_t keysym =
            xkb_state_key_get_one_sym(xkb_state, key_codes[i]);
        int char_len = xkb_keysym_to_utf8(keysym, buffer, buffer_size);
        if (char_len < 0) {
            LOG_ERR("Could not load home row keys. Buffer is too small.");
            exit(1);
        }

        if (char_len == 0) {
            LOG_ERR(
                "0x%x symkey does not have a UTF-8 representation in given "
                "keymap.",
                key_codes[i]
            );
            exit(1);
        }

        home_row[i]  = buffer;
        buffer      += char_len;
        buffer_size -= char_len;
    }

    xkb_state_unref(xkb_state);
}

static void handle_keyboard_keymap(
    void *data, struct wl_keyboard *keyboard, uint32_t format, int fd,
    uint32_t size
) {
    struct seat *seat = data;
    if (seat->xkb_state != NULL) {
        xkb_state_unref(seat->xkb_state);
        seat->xkb_state = NULL;
    }
    if (seat->xkb_keymap != NULL) {
        xkb_keymap_unref(seat->xkb_keymap);
        seat->xkb_keymap = NULL;
    }

    switch (format) {
    case WL_KEYBOARD_KEYMAP_FORMAT_NO_KEYMAP:
        seat->xkb_keymap = xkb_keymap_new_from_names(
            seat->xkb_context, NULL, XKB_KEYMAP_COMPILE_NO_FLAGS
        );
        break;

    case WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1:;
        void *buffer = mmap(NULL, size - 1, PROT_READ, MAP_PRIVATE, fd, 0);
        if (buffer == MAP_FAILED) {
            LOG_ERR("Could not mmap keymap data.");
            return;
        }

        seat->xkb_keymap = xkb_keymap_new_from_buffer(
            seat->xkb_context, buffer, size - 1, XKB_KEYMAP_FORMAT_TEXT_V1,
            XKB_KEYMAP_COMPILE_NO_FLAGS
        );

        munmap(buffer, size - 1);
        close(fd);
        break;
    }

    if (seat->state->config.general.home_row_keys == NULL) {
        load_home_row(
            seat->xkb_keymap, seat->state->home_row,
            seat->state->home_row_buffer
        );
    }
    seat->xkb_state = xkb_state_new(seat->xkb_keymap);
}

static void handle_keyboard_key(
    void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time,
    uint32_t key, uint32_t key_state
) {
    struct seat        *seat = data;
    char                text[64];
    const xkb_keycode_t key_code = key + 8;
    const xkb_keysym_t  key_sym =
        xkb_state_key_get_one_sym(seat->xkb_state, key_code);
    xkb_keysym_to_utf8(key_sym, text, sizeof(text));

    if (key_state == WL_KEYBOARD_KEY_STATE_PRESSED) {
        bool redraw = mode_handle_key(seat->state, key_sym, text);
        if (has_last_mode_returned(seat->state)) {
            seat->state->running = false;
        } else if (redraw) {
            request_frame(seat->state);
        }
    }
}

static void handle_keyboard_modifiers(
    void *data, struct wl_keyboard *keyboard, uint32_t serial,
    uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked,
    uint32_t group
) {
    struct seat *seat = data;
    xkb_state_update_mask(
        seat->xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group
    );
}

static const struct wl_keyboard_listener wl_keyboard_listener = {
    .keymap      = handle_keyboard_keymap,
    .enter       = noop,
    .leave       = noop,
    .key         = handle_keyboard_key,
    .modifiers   = handle_keyboard_modifiers,
    .repeat_info = noop,
};

static void handle_seat_capabilities(
    void *data, struct wl_seat *wl_seat, uint32_t capabilities
) {
    struct seat *seat = data;
    if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {
        seat->wl_keyboard = wl_seat_get_keyboard(seat->wl_seat);
        wl_keyboard_add_listener(
            seat->wl_keyboard, &wl_keyboard_listener, data
        );
    }
}

const struct wl_seat_listener wl_seat_listener = {
    .name         = noop,
    .capabilities = handle_seat_capabilities,
};

static void free_seats(struct wl_list *seats) {
    struct seat *seat;
    struct seat *tmp;
    wl_list_for_each_safe (seat, tmp, seats, link) {
        if (seat->wl_keyboard != NULL) {
            wl_keyboard_destroy(seat->wl_keyboard);
        }

        if (seat->xkb_state != NULL) {
            xkb_state_unref(seat->xkb_state);
        }
        if (seat->xkb_keymap != NULL) {
            xkb_keymap_unref(seat->xkb_keymap);
        }
        xkb_context_unref(seat->xkb_context);

        wl_seat_destroy(seat->wl_seat);
        wl_list_remove(&seat->link);
        free(seat);
    }
}

static void free_outputs(struct wl_list *outputs) {
    struct output *output;
    struct output *tmp;
    wl_list_for_each_safe (output, tmp, outputs, link) {
        wl_output_destroy(output->wl_output);
        zxdg_output_v1_destroy(output->xdg_output);
        wl_list_remove(&output->link);
        free(output->name);
        free(output);
    }
}

static struct output *find_output_from_wl_output(
    struct wl_list *outputs, struct wl_output *wl_output
) {
    struct output *output;
    wl_list_for_each (output, outputs, link) {
        if (wl_output == output->wl_output) {
            return output;
        }
    }

    return NULL;
}

static void
handle_output_scale(void *data, struct wl_output *wl_output, int32_t scale) {
    struct output *output = data;
    output->scale         = scale;
}

static void handle_output_geometry(
    void *data, struct wl_output *wl_output, int32_t x, int32_t y,
    int32_t physical_width, int32_t physical_height, int32_t subpixel,
    const char *make, const char *model, int32_t transform
) {
    struct output *output = data;
    output->transform     = transform;
}

const static struct wl_output_listener output_listener = {
    .name        = noop,
    .geometry    = handle_output_geometry,
    .mode        = noop,
    .scale       = handle_output_scale,
    .description = noop,
    .done        = noop,
};

static void handle_xdg_output_logical_position(
    void *data, struct zxdg_output_v1 *xdg_output, int32_t x, int32_t y
) {
    struct output *output = data;
    output->x             = x;
    output->y             = y;
}

static void handle_xdg_output_logical_size(
    void *data, struct zxdg_output_v1 *xdg_output, int32_t w, int32_t h
) {
    struct output *output = data;
    output->width         = w;
    output->height        = h;
}

static void handle_xdg_output_name(
    void *data, struct zxdg_output_v1 *xdg_output, const char *name
) {
    struct output *output = data;
    output->name          = strdup(name);
}

const static struct zxdg_output_v1_listener xdg_output_listener = {
    .logical_position = handle_xdg_output_logical_position,
    .logical_size     = handle_xdg_output_logical_size,
    .done             = noop,
    .name             = handle_xdg_output_name,
    .description      = noop,
};

static void load_xdg_outputs(struct state *state) {
    struct output *output;
    wl_list_for_each (output, &state->outputs, link) {
        output->xdg_output = zxdg_output_manager_v1_get_xdg_output(
            state->xdg_output_manager, output->wl_output
        );
        zxdg_output_v1_add_listener(
            output->xdg_output, &xdg_output_listener, output
        );
    }

    wl_display_roundtrip(state->wl_display);
}

static void enter_first_mode(struct state *state) {
    if (state->current_mode == NO_MODE_ENTERED) {
        if (!compute_initial_area(state, &state->initial_area)) {
            state->running = false;
            return;
        }

        LOG_DEBUG(
            "Initial area: %dx%d+%d+%d", state->initial_area.w,
            state->initial_area.h, state->initial_area.x, state->initial_area.y
        );

        LOG_DEBUG(
            "Output: %s (position: %dx%d+%d+%d, transform: %d)",
            state->current_output->name, state->current_output->width,
            state->current_output->height, state->current_output->x,
            state->current_output->y, state->current_output->transform
        );

        enter_next_mode(state, state->initial_area);

        if (state->running) {
            send_frame(state);
        }
    }
}

static void handle_surface_enter(
    void *data, struct wl_surface *surface, struct wl_output *wl_output
) {
    struct state  *state = data;
    struct output *output =
        find_output_from_wl_output(&state->outputs, wl_output);
    state->current_output = output;

    if (state->surface_configured) {
        enter_first_mode(state);
    }
}

static const struct wl_surface_listener surface_listener = {
    .enter                      = handle_surface_enter,
    .leave                      = noop,
    .preferred_buffer_transform = noop,
    .preferred_buffer_scale     = noop,
};

static void handle_registry_global(
    void *data, struct wl_registry *registry, uint32_t name,
    const char *interface, uint32_t version
) {
    struct state *state = data;

    if (strcmp(interface, wl_compositor_interface.name) == 0) {
        state->wl_compositor =
            wl_registry_bind(registry, name, &wl_compositor_interface, 4);

    } else if (strcmp(interface, wl_shm_interface.name) == 0) {
        state->wl_shm = wl_registry_bind(registry, name, &wl_shm_interface, 1);

    } else if (strcmp(interface, zwlr_layer_shell_v1_interface.name) == 0) {
        state->wl_layer_shell =
            wl_registry_bind(registry, name, &zwlr_layer_shell_v1_interface, 2);

    } else if (strcmp(interface, wl_seat_interface.name) == 0) {
        struct seat *seat = calloc(1, sizeof(struct seat));
        seat->wl_seat = wl_registry_bind(registry, name, &wl_seat_interface, 7);
        seat->wl_keyboard = NULL;
        seat->xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
        seat->xkb_state   = NULL;
        seat->xkb_keymap  = NULL;
        seat->state       = state;

        wl_seat_add_listener(seat->wl_seat, &wl_seat_listener, seat);
        wl_list_insert(&state->seats, &seat->link);

    } else if (strcmp(interface, wl_output_interface.name) == 0) {
        struct wl_output *wl_output =
            wl_registry_bind(registry, name, &wl_output_interface, 3);
        struct output *output = calloc(1, sizeof(struct output));
        output->wl_output     = wl_output;
        output->scale         = 1;

        wl_output_add_listener(output->wl_output, &output_listener, output);
        wl_list_insert(&state->outputs, &output->link);

    } else if (strcmp(interface, zxdg_output_manager_v1_interface.name) == 0) {
        state->xdg_output_manager = wl_registry_bind(
            registry, name, &zxdg_output_manager_v1_interface, 2
        );

    } else if (strcmp(
                   interface, zwlr_virtual_pointer_manager_v1_interface.name
               ) == 0) {
        state->wl_virtual_pointer_mgr = wl_registry_bind(
            registry, name, &zwlr_virtual_pointer_manager_v1_interface, 2
        );
    } else if (strcmp(interface, wp_viewporter_interface.name) == 0) {
        state->wp_viewporter =
            wl_registry_bind(registry, name, &wp_viewporter_interface, 1);
    } else if (strcmp(
                   interface, wp_fractional_scale_manager_v1_interface.name
               ) == 0) {
        state->fractional_scale_mgr = wl_registry_bind(
            registry, name, &wp_fractional_scale_manager_v1_interface, 1
        );
#if OPENCV_ENABLED
    } else if (strcmp(interface, zwlr_screencopy_manager_v1_interface.name) ==
               0) {
        state->wl_screencopy_manager = wl_registry_bind(
            registry, name, &zwlr_screencopy_manager_v1_interface, 1
        );
#endif
    }
}

const struct wl_registry_listener wl_registry_listener = {
    .global        = handle_registry_global,
    .global_remove = noop,
};

static void handle_layer_surface_configure(
    void *data, struct zwlr_layer_surface_v1 *layer_surface, uint32_t serial,
    uint32_t width, uint32_t height
) {
    struct state *state   = data;
    state->surface_width  = width;
    state->surface_height = height;
    zwlr_layer_surface_v1_ack_configure(layer_surface, serial);

    if (state->current_output != NULL) {
        enter_first_mode(state);
    } else if (!state->surface_configured) {
        send_transparent_frame(state);
    }

    state->surface_configured = true;
}

static void handle_layer_surface_closed(
    void *data, struct zwlr_layer_surface_v1 *layer_surface
) {
    struct state *state = data;
    state->running      = false;
}

const struct zwlr_layer_surface_v1_listener wl_layer_surface_listener = {
    .configure = handle_layer_surface_configure,
    .closed    = handle_layer_surface_closed,
};

static void fractional_scale_preferred(
    void *data, struct wp_fractional_scale_v1 *fractional_scale, uint32_t scale
) {
    struct state *state     = data;
    int32_t       old_scale = state->fractional_scale;
    state->fractional_scale = scale;

    if (old_scale != 0 && old_scale != scale) {
        request_frame(state);
    }
}

const struct wp_fractional_scale_v1_listener fractional_scale_listener = {
    .preferred_scale = fractional_scale_preferred,
};

static struct output *
find_output_from_rect(struct state *state, struct rect *rect) {
    struct output *output;
    wl_list_for_each (output, &state->outputs, link) {
        if (output->x <= rect->x && output->y <= rect->y &&
            output->x + output->width > rect->x &&
            output->y + output->height > rect->y) {
            return output;
        }
    }

    return NULL;
}

static struct output *find_output_by_name(struct state *state, char *name) {
    struct output *output;
    wl_list_for_each (output, &state->outputs, link) {
        if (strcmp(output->name, name) == 0) {
            return output;
        }
    }

    return NULL;
}

static void print_result(struct state *state) {
    char click;
    switch (state->click) {
    case CLICK_LEFT_BTN:
        click = 'l';
        break;
    case CLICK_MIDDLE_BTN:
        click = 'm';
        break;
    case CLICK_RIGHT_BTN:
        click = 'r';
        break;
    case CLICK_NONE:
        click = 'n';
    }

    printf(
        "%dx%d+%d+%d +%d+%d %c\n", state->result.w, state->result.h,
        state->result.x, state->result.y, state->current_output->x,
        state->current_output->y, click
    );
}

static void print_usage() {
    puts("wl-kbptr [OPTION...]\n");

    puts(" -h, --help          show this help");
    puts(" --help-config       show help on configuration");
    puts(" -v, --version       show version");
    puts(" -c, --config=FILE   use given configuration file");
    puts(" -r, --restrict=AREA restrict to given area (wxh+x+y)");
    puts(" -o, --option        set configuration option");
    puts(" -O, --output        specify display output to use");
    puts(" -p, --only-print    only print, don't move the cursor or click");
}

static void print_version() {
    printf("wl-kbptr %s", VERSION);
#if OPENCV_ENABLED
    printf(" (opencv)");
#endif
    puts("");
}

int main(int argc, char **argv) {
    struct state state = {
        .wl_display          = NULL,
        .wl_registry         = NULL,
        .wl_compositor       = NULL,
        .wl_shm              = NULL,
        .wl_layer_shell      = NULL,
        .wl_surface          = NULL,
        .wl_surface_callback = NULL,
        .wl_layer_surface    = NULL,
        .surface_configured  = false,
#if OPENCV_ENABLED
        .wl_screencopy_manager = NULL,
#endif
        .wp_viewporter        = NULL,
        .fractional_scale_mgr = NULL,
        .running              = true,
        .fractional_scale     = 0,
        .result               = (struct rect){-1, -1, -1, -1},
        .initial_area         = (struct rect){-1, -1, -1, -1},
        .home_row = (char *[]){"", "", "", "", "", "", "", "", "", "", ""},
        .click    = CLICK_NONE,
    };

    config_set_default(&state.config);
    struct config_loader config_loader;
    config_loader_init(&config_loader, &state.config);

    static struct option long_options[] = {
        {"help", no_argument, 0, 'h'},
        {"help-config", no_argument, 0, 'H'},
        {"version", no_argument, 0, 'v'},
        {"restrict", required_argument, 0, 'r'},
        {"config", required_argument, 0, 'c'},
        {"output", required_argument, 0, 'O'},
        {"only-print", no_argument, 0, 'p'},
        {NULL, 0, NULL, 0}
    };

    int    num_cli_configs      = 0;
    char **cli_configs          = malloc(10 * sizeof(char*));
    int    cli_configs_len      = 10;
    int    option_char          = 0;
    int    option_index         = 0;
    char  *config_filename      = NULL;
    char  *selected_output_name = NULL;
    bool   only_print           = false;
    while ((option_char = getopt_long(
                argc, argv, "hvr:o:c:O:Rp", long_options, &option_index
            )) != -1) {
        switch (option_char) {
        case 'h':
            print_usage();
            config_free_values(&state.config);
            return 0;

        case 'v':
            print_version();
            config_free_values(&state.config);
            return 0;

        case 'r':
            if (sscanf(
                    optarg, "%dx%d+%d+%d", &state.initial_area.w,
                    &state.initial_area.h, &state.initial_area.x,
                    &state.initial_area.y
                ) != 4) {
                LOG_ERR("Could not parse --restrict argument.");
                return 1;
            }
            break;

        case 'o':
            if (num_cli_configs >= cli_configs_len) {
                cli_configs_len += 10;
                cli_configs =
                    realloc(cli_configs, cli_configs_len * sizeof(char*));
            }
            cli_configs[num_cli_configs++] = optarg;
            break;

        case 'c':
            config_filename = strdup(optarg);
            break;

        case 'H':
            print_default_config();
            config_free_values(&state.config);
            return 0;

        case 'O':
            selected_output_name = strdup(optarg);
            break;

        case 'p':
            only_print = true;
            break;

        default:
            LOG_ERR("Unknown argument.");
            config_free_values(&state.config);
            return 1;
        }
    }

    int err = config_loader_load_file(&config_loader, config_filename);
    if (err) {
        LOG_ERR("Failed to read configuration file.");
        return 1;
    }
    if (config_filename != NULL) {
        free(config_filename);
        config_filename = NULL;
    }

    for (int i = 0; i < num_cli_configs; i++) {
        if (config_loader_load_cli_param(&config_loader, cli_configs[i])) {
            return 1;
        }
    }
    free(cli_configs);
    cli_configs = NULL;

    if (state.config.general.home_row_keys != NULL) {
        state.home_row = state.config.general.home_row_keys;
    }

    if (load_modes(&state, state.config.general.modes) != 0) {
        LOG_ERR("Could not load modes.");
        return 1;
    }

    wl_list_init(&state.outputs);
    wl_list_init(&state.seats);

    state.wl_display = wl_display_connect(NULL);
    if (state.wl_display == NULL) {
        LOG_ERR("Failed to connect to Wayland compositor.");
        return 1;
    }

    state.wl_registry = wl_display_get_registry(state.wl_display);
    if (state.wl_registry == NULL) {
        LOG_ERR("Failed to get Wayland registry.");
        return 1;
    }

    wl_registry_add_listener(state.wl_registry, &wl_registry_listener, &state);
    wl_display_roundtrip(state.wl_display);

    if (state.wl_compositor == NULL) {
        LOG_ERR("Failed to get wl_compositor object.");
        return 1;
    }

    if (state.wl_shm == NULL) {
        LOG_ERR("Failed to get wl_shm object.");
        return 1;
    }

    if (state.wl_layer_shell == NULL) {
        LOG_ERR("Failed to get zwlr_layer_shell_v1 object.");
        return 1;
    }

    if (state.wl_virtual_pointer_mgr == NULL && !only_print) {
        LOG_ERR("Failed to get wlr_virtual_pointer_manager_v1 object.");
        return 1;
    }

    if (state.xdg_output_manager == NULL) {
        LOG_ERR("Failed to get xdg_output_manager object.");
        return 1;
    }

    if (state.wp_viewporter == NULL) {
        LOG_ERR("Failed to get wp_viewporter object.");
        return 1;
    }

    load_xdg_outputs(&state);

    // This round trip should load the keymap which is needed to determine the
    // home row keys.
    wl_display_roundtrip(state.wl_display);

    if (selected_output_name) {
        state.current_output =
            find_output_by_name(&state, selected_output_name);

        if (!state.current_output) {
            LOG_ERR("Could not find output '%s'.", selected_output_name);
            return 1;
        }

        free(selected_output_name);
        selected_output_name = NULL;
    } else if (state.initial_area.w != -1) {
        state.current_output =
            find_output_from_rect(&state, &state.initial_area);

        if (!state.current_output) {
            LOG_ERR("Could not find output containing given area.");
            return 1;
        }

        state.initial_area.x -= state.current_output->x;
        state.initial_area.y -= state.current_output->y;
    }

    surface_buffer_pool_init(&state.surface_buffer_pool);

    state.wl_surface = wl_compositor_create_surface(state.wl_compositor);
    wl_surface_add_listener(state.wl_surface, &surface_listener, &state);
    state.wl_layer_surface = zwlr_layer_shell_v1_get_layer_surface(
        state.wl_layer_shell, state.wl_surface,
        state.current_output == NULL ? NULL : state.current_output->wl_output,
        ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY, "selection"
    );
    zwlr_layer_surface_v1_add_listener(
        state.wl_layer_surface, &wl_layer_surface_listener, &state
    );
    zwlr_layer_surface_v1_set_exclusive_zone(state.wl_layer_surface, -1);
    zwlr_layer_surface_v1_set_anchor(
        state.wl_layer_surface, ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT |
                                    ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT |
                                    ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP |
                                    ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM
    );
    zwlr_layer_surface_v1_set_keyboard_interactivity(
        state.wl_layer_surface, true
    );

    struct wp_fractional_scale_v1 *fractional_scale = NULL;
    if (state.fractional_scale_mgr) {
        fractional_scale = wp_fractional_scale_manager_v1_get_fractional_scale(
            state.fractional_scale_mgr, state.wl_surface
        );
        wp_fractional_scale_v1_add_listener(
            fractional_scale, &fractional_scale_listener, &state
        );
    }

    state.wp_viewport =
        wp_viewporter_get_viewport(state.wp_viewporter, state.wl_surface);

    struct wl_region *wl_region =
        wl_compositor_create_region(state.wl_compositor);
    wl_region_add(wl_region, 0, 0, 0, 0);
    wl_surface_set_input_region(state.wl_surface, wl_region);

    wl_surface_commit(state.wl_surface);
    while (state.running && wl_display_dispatch(state.wl_display)) {}

    wp_viewport_destroy(state.wp_viewport);

    zwlr_layer_surface_v1_destroy(state.wl_layer_surface);
    wl_surface_destroy(state.wl_surface);
    wl_region_destroy(wl_region);

    surface_buffer_pool_destroy(&state.surface_buffer_pool);
    wl_display_roundtrip(state.wl_display);

    int status_code = 0;
    if (state.result.x != -1) {
        print_result(&state);
        if (!only_print) {
            move_pointer(
                &state, state.result.x + state.result.w / 2,
                state.result.y + state.result.h / 2, state.click
            );
        }
    } else {
        status_code = state.config.general.cancellation_status_code;
    }

    if (state.wl_virtual_pointer_mgr != NULL) {
        zwlr_virtual_pointer_manager_v1_destroy(state.wl_virtual_pointer_mgr);
    }

    free_seats(&state.seats);
    free_outputs(&state.outputs);

    zxdg_output_manager_v1_destroy(state.xdg_output_manager);

    if (state.fractional_scale_mgr) {
        wp_fractional_scale_v1_destroy(fractional_scale);
        wp_fractional_scale_manager_v1_destroy(state.fractional_scale_mgr);
    }

    wp_viewporter_destroy(state.wp_viewporter);
    wl_shm_destroy(state.wl_shm);
    wl_compositor_destroy(state.wl_compositor);
    wl_registry_destroy(state.wl_registry);
    zwlr_layer_shell_v1_destroy(state.wl_layer_shell);

#if OPENCV_ENABLED
    if (state.wl_screencopy_manager) {
        zwlr_screencopy_manager_v1_destroy(state.wl_screencopy_manager);
    }
#endif

    wl_display_disconnect(state.wl_display);

    config_free_values(&state.config);
    free_mode_states(&state);

#if DEBUG
    cairo_debug_reset_static_data();
#endif

    return status_code;
}


================================================
FILE: src/mode.c
================================================
#include "mode.h"

#include "log.h"

#include <stdlib.h>
#include <string.h>

extern struct mode_interface tile_mode_interface;
extern struct mode_interface floating_mode_interface;
extern struct mode_interface bisect_mode_interface;
extern struct mode_interface split_mode_interface;
extern struct mode_interface click_mode_interface;

struct mode_interface *mode_interfaces[] = {
    &tile_mode_interface,  &floating_mode_interface, &bisect_mode_interface,
    &split_mode_interface, &click_mode_interface,    NULL,
};

static struct mode_interface *find_mode_interface_by_name(char *name) {
    struct mode_interface **curr_mode_interface = mode_interfaces;
    while (*curr_mode_interface != NULL) {
        if (strcmp(name, (*curr_mode_interface)->name) == 0) {
            return *curr_mode_interface;
        }

        curr_mode_interface++;
    }

    return NULL;
}

int load_modes(struct state *state, char *modes) {
    char buf[strlen(modes) + 1];
    strcpy(buf, modes);

    int mode_i = 0;

    static const char *delim = ",";
    char              *tok   = strtok(buf, delim);
    while (tok != NULL) {
        if (mode_i >= MAX_NUM_MODES) {
            LOG_ERR("Only %d modes can be specified.", MAX_NUM_MODES);
            return 1;
        }

        struct mode_interface *mode_interface =
            find_mode_interface_by_name(tok);
        if (mode_interface == NULL) {
            LOG_ERR("Unknown mode '%s'.", tok);
            return 2;
        }

        state->mode_interfaces[mode_i++] = mode_interface;
        tok                              = strtok(NULL, delim);
    }

    if (mode_i < MAX_NUM_MODES) {
        state->mode_interfaces[mode_i] = NULL;
    }

    state->current_mode = NO_MODE_ENTERED;
    return 0;
}

void enter_next_mode(struct state *state, struct rect area) {
    if (has_last_mode_returned(state)) {
        return;
    }

    state->current_mode += 1;

    if (has_last_mode_returned(state)) {
        memcpy(&state->result, &area, sizeof(struct rect));
        return;
    }

    state->mode_states[state->current_mode] =
        state->mode_interfaces[state->current_mode]->enter(state, area);
}

bool has_last_mode_returned(struct state *state) {
    return state->current_mode >= MAX_NUM_MODES ||
           state->mode_interfaces[state->current_mode] == NULL;
}

bool reenter_prev_mode(struct state *state) {
    if (state->current_mode <= 0) {
        return false;
    }

    void *current_mode_state = state->mode_states[state->current_mode];
    if (current_mode_state != NULL) {
        state->mode_interfaces[state->current_mode]->free(current_mode_state);
    }

    state->current_mode--;
    state->mode_interfaces[state->current_mode]->reenter(
        state, state->mode_states[state->current_mode]
    );

    return true;
}

void free_mode_states(struct state *state) {
    if (state->current_mode == NO_MODE_ENTERED) {
        return;
    }

    for (int i = 0; i <= state->current_mode; i++) {
        if (state->mode_interfaces[i] == NULL ||
            state->mode_states[i] == NULL) {
            return;
        }

        state->mode_interfaces[i]->free(state->mode_states[i]);
    }
}

bool mode_handle_key(struct state *state, xkb_keysym_t sym, char *text) {
    if (has_last_mode_returned(state)) {
        return false;
    }

    return state->mode_interfaces[state->current_mode]->key(
        state, state->mode_states[state->current_mode], sym, text
    );
}
void mode_render(struct state *state, cairo_t *cairo) {
    if (has_last_mode_returned(state)) {
        return;
    }

    return state->mode_interfaces[state->current_mode]->render(
        state, state->mode_states[state->current_mode], cairo
    );
}


================================================
FILE: src/mode.h
================================================
#ifndef __MODE_H_INCLUDED__
#define __MODE_H_INCLUDED__

#include "state.h"

#include <cairo.h>
#include <stdbool.h>
#include <xkbcommon/xkbcommon.h>

struct mode_interface {
    char *name;
    void *(*enter)(struct state *, struct rect area);
    void (*reenter)(struct state *, void *mode_state);
    bool (*key)(struct state *, void *mode_state, xkb_keysym_t, char *text);
    void (*render)(struct state *, void *mode_state, cairo_t *);
    void (*free)(void *mode_state);
};

extern struct mode_interface *mode_interfaces[];

/**
 * Load modes from given coma seperated list of mode names.
 * Returns 0 on success.
 */
int load_modes(struct state *, char *);

void enter_next_mode(struct state *, struct rect area);
bool has_last_mode_returned(struct state *);
bool reenter_prev_mode(struct state *);
void free_mode_states(struct state *);
bool mode_handle_key(struct state *, xkb_keysym_t, char *text);
void mode_render(struct state *, cairo_t *);

#endif


================================================
FILE: src/mode_bisect.c
================================================
#include "config.h"
#include "mode.h"
#include "state.h"
#include "utils.h"
#include "utils_cairo.h"
#include "utils_wayland.h"

#include <math.h>
#include <stdlib.h>
#include <string.h>

#define DIVIDE_8_RATIO 1.8

enum bisect_division {
    /*
     * The tiling mode should give us areas that are twice as wide as they are
     * tall. In this case, we want to divide the area in 8 instead of 4 as to
     * then get equal square areas.
     *
     *  +--+--+--+--+
     *  | 0| 1| 2| 3|
     *  +--+--+--+--+
     *  | 4| 5| 6| 7|
     *  +--+--+--+--+
     */
    DIVISION_8 = 0,
    /*
     * After the first pass, we should only get mostly square areas.
     *
     *  +--+--+
     *  | 0| 1|
     *  +--+--+
     *  | 2| 3|
     *  +--+--+
     */
    DIVISION_4,
    /*
     * Once we have divide the areas enough times, we will end up with a line,
     * i.e. a area with a width or height of a single pixel. In this case we
     * divide the area in two.
     *
     *    0  1
     *  +--+--+
     */
    DIVISION_HORIZONTAL,
    /*
     *    +
     *    | 0
     *    +
     *    | 1
     *    +
     */
    DIVISION_VERTICAL,
    /*
     * Given enough divisions, we should end up with a single pixel.
     *
     *    +
     */
    UNDIVIDABLE,
};

static void
bisect_mode_move_pointer(struct state *state, struct bisect_mode_state *ms) {
    struct rect *r = &ms->areas[ms->current];
    move_pointer(state, r->x + r->w / 2, r->y + r->h / 2, CLICK_NONE);
}

void *bisect_mode_enter(struct state *state, struct rect area) {
    struct bisect_mode_state *ms = malloc(sizeof(*ms));
    ms->areas[0]                 = area;
    ms->current                  = 0;

    ms->label_font_face = cairo_toy_font_face_create(
        state->config.mode_bisect.label_font_family, CAIRO_FONT_SLANT_NORMAL,
        CAIRO_FONT_WEIGHT_NORMAL
    );

    bisect_mode_move_pointer(state, ms);

    return ms;
}

static enum bisect_division determine_division(struct rect *area) {
    if (area->w <= 1 && area->h <= 1) {
        return UNDIVIDABLE;
    }

    if (area->w <= 1) {
        return DIVISION_VERTICAL;
    }

    if (area->h <= 1) {
        return DIVISION_HORIZONTAL;
    }

    return area->w > area->h * DIVIDE_8_RATIO ? DIVISION_8 : DIVISION_4;
}

struct division_interface {
    void (*render)(
        enum bisect_division, struct state *, struct bisect_mode_state *ms,
        cairo_t *
    );

    // `idx_to_sub_area` returns the sub-area indicated by the given index in
    // `rect` while also returning true. If the index does map to a sub-area,
    // `rect` is left unchanged and it returns false.
    bool (*idx_to_sub_area)(
        enum bisect_division, int idx, struct rect *current_area,
        struct rect *new_area
    );
};

static void division_4_or_8_render(
    enum bisect_division division, struct state *state,
    struct bisect_mode_state *ms, cairo_t *cairo
) {
    struct mode_bisect_config *config = &state->config.mode_bisect;
    struct rect               *area   = &ms->areas[ms->current];

    bool divide_8 = division == DIVISION_8;

    const int sub_area_columns = divide_8 ? 4 : 2;
    const int sub_area_rows    = 2;

    const int sub_area_width      = area->w / sub_area_columns;
    const int sub_area_width_off  = area->w % sub_area_columns;
    const int sub_area_height     = area->h / sub_area_rows;
    const int sub_area_height_off = area->h % sub_area_rows;

    const bool inner_labels = config->label_font_size < sub_area_height;
    const int  font_size =
        max(min(512, sub_area_height * .9), config->label_font_size);

    cairo_set_font_face(cairo, ms->label_font_face);
    cairo_set_font_size(cairo, font_size);

    for (int i = 0; i < sub_area_columns; i++) {
        for (int j = 0; j < sub_area_rows; j++) {
            const int x =
                area->x + i * sub_area_width + min(i, sub_area_width_off);
            const int y =
                area->y + j * sub_area_height + min(j, sub_area_height_off);
            const int w = sub_area_width + (i < sub_area_width_off ? 1 : 0);
            const int h = sub_area_height + (j < sub_area_height_off ? 1 : 0);

            cairo_set_source_u32(
                cairo, (i + j) % 2 == 0 ? config->even_area_bg_color
                                        : config->odd_area_bg_color
            );
            cairo_rectangle(cairo, x, y, w, h);
            cairo_fill(cairo);

            cairo_set_line_width(cairo, 1);
            cairo_rectangle(cairo, x + .5, y + .5, w - 1, h - 1);
            cairo_set_source_u32(
                cairo, (i + j) % 2 == 0 ? config->even_area_border_color
                                        : config->odd_area_border_color
            );
            cairo_stroke(cairo);

            if (inner_labels) {
                cairo_set_source_u32(cairo, config->label_color);
                char *label = state->home_row[i + j * sub_area_columns];
                cairo_text_extents_t te;
                cairo_text_extents(cairo, label, &te);
                cairo_move_to(
                    cairo, x + (int)(w / 2) - (int)(te.width / 2),
                    y + (h + te.height) / 2
                );
                cairo_show_text(cairo, label);
            }
        }
    }

    if (!inner_labels) {
        cairo_set_font_size(cairo, config->label_font_size);
        cairo_set_source_u32(cairo, config->label_color);
        char label[64];

        // Top label
        if (divide_8) {
            snprintf(
                label, sizeof(label), "%s %s %s %s", state->home_row[0],
                state->home_row[1], state->home_row[2], state->home_row[3]
            );
        } else {
            snprintf(
                label, sizeof(label), "%s %s", state->home_row[0],
                state->home_row[1]
            );
        }

        cairo_text_extents_t te;
        cairo_text_extents(cairo, label, &te);
        cairo_move_to(
            cairo, area->x + (int)(area->w / 2) - (int)(te.width / 2),
            area->y - config->label_padding
        );
        cairo_show_text(cairo, label);

        // Bottom label
        if (divide_8) {
            snprintf(
                label, sizeof(label), "%s %s %s %s", state->home_row[4],
                state->home_row[5], state->home_row[6], state->home_row[7]
            );
        } else {
            snprintf(
                label, sizeof(label), "%s %s", state->home_row[2],
                state->home_row[3]
            );
        }

        cairo_text_extents(cairo, label, &te);
        cairo_move_to(
            cairo, area->x + (int)(area->w / 2) - (int)(te.width / 2),
            area->y + area->h + te.height + config->label_padding
        );
        cairo_show_text(cairo, label);
    }
}

static bool division_4_or_8_idx_to_rect(
    enum bisect_division division, int idx, struct rect *area, struct rect *rect
) {
    bool divide_8 = division == DIVISION_8;
    if (!divide_8 && idx >= 4) {
        return false;
    }

    const int sub_area_columns = divide_8 ? 4 : 2;
    const int sub_area_rows    = 2;

    const int sub_area_width      = area->w / sub_area_columns;
    const int sub_area_width_off  = area->w % sub_area_columns;
    const int sub_area_height     = area->h / sub_area_rows;
    const int sub_area_height_off = area->h % sub_area_rows;

    const int i = idx % sub_area_columns;
    const int j = idx / sub_area_columns;

    rect->x = area->x + i * sub_area_width + min(i, sub_area_width_off);
    rect->y = area->y + j * sub_area_height + min(j, sub_area_height_off);
    rect->w = sub_area_width + (i < sub_area_width_off ? 1 : 0);
    rect->h = sub_area_height + (j < sub_area_height_off ? 1 : 0);

    return true;
}

static void division_horizontal_render(
    enum bisect_division division, struct state *state,
    struct bisect_mode_state *ms, cairo_t *cairo
) {
    struct mode_bisect_config *config = &state->config.mode_bisect;
    struct rect               *area   = &ms->areas[ms->current];

    cairo_set_source_u32(cairo, config->even_area_border_color);
    cairo_set_line_width(cairo, 1);
    cairo_move_to(cairo, area->x + .5, area->y + .5);
    cairo_line_to(cairo, area->x + (int)(area->w / 2) - .5, area->y + .5);
    cairo_stroke(cairo);

    cairo_set_source_u32(cairo, config->odd_area_border_color);
    cairo_move_to(cairo, area->x + (int)(area->w / 2) + .5, area->y + .5);
    cairo_line_to(cairo, area->x + area->w + .5, area->y + .5);
    cairo_stroke(cairo);

    cairo_set_source_u32(cairo, config->label_color);

    cairo_text_extents_t te;
    cairo_text_extents(cairo, state->home_row[0], &te);
    cairo_move_to(
        cairo, area->x - config->label_padding - te.width,
        area->y + te.height / 2
    );
    cairo_show_text(cairo, state->home_row[0]);

    cairo_text_extents(cairo, state->home_row[1], &te);
    cairo_move_to(
        cairo, area->x + area->w + config->label_padding,
        area->y + te.height / 2
    );
    cairo_show_text(cairo, state->home_row[1]);
}

static bool division_horizontal_idx_to_rect(
    enum bisect_division division, int idx, struct rect *area, struct rect *rect
) {
    if (idx > 1) {
        return false;
    }

    rect->x = area->x + idx * area->w / 2;
    rect->y = area->y;
    rect->w = area->w / 2;
    rect->h = area->h;

    return true;
}

static void division_vertical_render(
    enum bisect_division division, struct state *state,
    struct bisect_mode_state *ms, cairo_t *cairo
) {

    struct mode_bisect_config *config = &state->config.mode_bisect;
    struct rect               *area   = &ms->areas[ms->current];

    cairo_set_source_u32(cairo, config->even_area_border_color);
    cairo_set_line_width(cairo, 1);
    cairo_move_to(cairo, area->x + .5, area->y + .5);
    cairo_line_to(cairo, area->x + .5, area->y - .5 + (int)(area->h / 2));
    cairo_stroke(cairo);

    cairo_set_source_u32(cairo, config->odd_area_border_color);
    cairo_move_to(cairo, area->x + .5, area->y + .5 + (int)(area->h / 2));
    cairo_line_to(cairo, area->x + .5, area->y + .5 + area->h);
    cairo_stroke(cairo);

    cairo_set_source_u32(cairo, config->label_color);

    cairo_text_extents_t te;
    cairo_text_extents(cairo, state->home_row[0], &te);
    cairo_move_to(
        cairo, area->x - te.width / 2, area->y - config->label_padding
    );
    cairo_show_text(cairo, state->home_row[0]);

    cairo_text_extents(cairo, state->home_row[1], &te);
    cairo_move_to(
        cairo, area->x - te.width / 2,
        area->y + area->h + config->label_padding + te.height
    );
    cairo_show_text(cairo, state->home_row[1]);
}

static bool division_vertical_idx_to_rect(
    enum bisect_division division, int idx, struct rect *area, struct rect *rect
) {
    if (idx > 1) {
        return false;
    }

    rect->x = area->x;
    rect->y = area->y + idx * area->h / 2;
    rect->w = area->w;
    rect->h = area->h / 2;

    return true;
}

static void undividable_render(
    enum bisect_division division, struct state *state,
    struct bisect_mode_state *ms, cairo_t *cairo
) {
    struct mode_bisect_config *config = &state->config.mode_bisect;
    struct rect               *area   = &ms->areas[ms->current];

    cairo_set_source_u32(cairo, config->pointer_color);
    cairo_arc(
        cairo, area->x + .5, area->y + .5, config->pointer_size / 4., 0,
        2 * M_PI
    );
    cairo_set_line_width(cairo, 1);
    cairo_stroke(cairo);
}

static bool undividable_select_idx() {
    return false;
}

static const struct division_interface division_interfaces[] = {
    [DIVISION_8] =
        {.render          = division_4_or_8_render,
         .idx_to_sub_area = division_4_or_8_idx_to_rect},
    [DIVISION_4] =
        {.render          = division_4_or_8_render,
         .idx_to_sub_area = division_4_or_8_idx_to_rect},
    [DIVISION_VERTICAL] =
        {.render          = division_vertical_render,
         .idx_to_sub_area = division_vertical_idx_to_rect},
    [DIVISION_HORIZONTAL] =
        {.render          = division_horizontal_render,
         .idx_to_sub_area = division_horizontal_idx_to_rect},
    [UNDIVIDABLE] = {
        .render = undividable_render, .idx_to_sub_area = undividable_select_idx
    },
};

static void
bisect_mode_render(struct state *state, void *mode_state, cairo_t *cairo) {
    struct mode_bisect_config *config = &state->config.mode_bisect;
    struct bisect_mode_state  *ms     = mode_state;
    struct rect               *area   = &ms->areas[ms->current];

    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
    cairo_set_source_u32(cairo, config->unselectable_bg_color);
    cairo_paint(cairo);

    cairo_set_source_u32(cairo, config->history_border_color);
    cairo_set_line_width(cairo, 1);

    for (int i = 0; i < ms->current; i++) {
        struct rect *area = &ms->areas[i];
        cairo_rectangle(
            cairo, area->x + .5, area->y + .5, area->w - 1, area->h - 1
        );
        cairo_stroke(cairo);
    }

    if (ms->current < BISECT_MAX_HISTORY) {
        enum bisect_division division = determine_division(area);
        division_interfaces[division].render(division, state, ms, cairo);
    }

    cairo_set_line_width(cairo, 1);
    cairo_set_source_u32(cairo, config->pointer_color);
    const int pointer_x = area->x + area->w / 2;
    const int pointer_y = area->y + area->h / 2;
    cairo_move_to(
        cairo, pointer_x + .5, pointer_y - (int)(config->pointer_size / 2) + .5
    );
    cairo_line_to(
        cairo, pointer_x + .5, pointer_y + (int)(config->pointer_size / 2) + .5
    );
    cairo_stroke(cairo);
    cairo_move_to(
        cairo, pointer_x - (int)(config->pointer_size / 2) + .5, pointer_y + .5
    );
    cairo_line_to(
        cairo, pointer_x + (int)(config->pointer_size / 2) + .5, pointer_y + .5
    );
    cairo_stroke(cairo);
}

static bool bisect_mode_key(
    struct state *state, void *mode_state, xkb_keysym_t keysym, char *text
) {
    struct bisect_mode_state *ms = mode_state;

    switch (keysym) {
    case XKB_KEY_Escape:
        state->running = false;
        break;

    case XKB_KEY_Return:
    case XKB_KEY_space:
        enter_next_mode(state, ms->areas[ms->current]);
        return true;

    case XKB_KEY_BackSpace:
        if (ms->current > 0) {
            ms->current--;
        } else {
            reenter_prev_mode(state);
        }
        return true;

    default:
        if (ms->current + 1 >= BISECT_MAX_HISTORY) {
            return false;
        }

        struct rect         *area     = &ms->areas[ms->current];
        enum bisect_division division = determine_division(area);

        int matched_i = find_str(state->home_row, HOME_ROW_LEN_WITH_BTN, text);
        if (matched_i < 0) {
            return false;
        }

        if (matched_i >= HOME_ROW_LEN) {
            switch (matched_i) {
            case HOME_ROW_LEFT_CLICK:
                state->click = CLICK_LEFT_BTN;
                break;
            case HOME_ROW_RIGHT_CLICK:
                state->click = CLICK_RIGHT_BTN;
                break;
            case HOME_ROW_MIDDLE_CLICK:
                state->click = CLICK_MIDDLE_BTN;
                break;
            }

            enter_next_mode(state, ms->areas[ms->current]);
            return false;
        }

        if (division == UNDIVIDABLE) {
            return false;
        }

        struct rect *new_area = &ms->areas[ms->current + 1];
        if (division_interfaces[division].idx_to_sub_area(
                division, matched_i, area, new_area
            )) {
            ms->current++;
            bisect_mode_move_pointer(state, ms);
            return true;
        }
    }

    return false;
}

void bisect_mode_reenter(struct state *state, void *mode_state) {
    bisect_mode_move_pointer(state, mode_state);
}
void bisect_mode_free(void *mode_state) {
    struct bisect_mode_state *ms = mode_state;
    cairo_font_face_destroy(ms->label_font_face);
    free(ms);
}

struct mode_interface bisect_mode_interface = {
    .name    = "bisect",
    .enter   = bisect_mode_enter,
    .reenter = bisect_mode_reenter,
    .key     = bisect_mode_key,
    .render  = bisect_mode_render,
    .free    = bisect_mode_free,
};


================================================
FILE: src/mode_click.c
================================================
#include "mode.h"

static void *click_mode_enter(struct state *state, struct rect area) {
    state->click = state->config.mode_click.button;
    enter_next_mode(state, area);
    return NULL;
}

static void click_mode_reenter(struct state *state, void *mode_state) {
    reenter_prev_mode(state);
}

static bool click_mode_key(
    struct state *state, void *mode_state, xkb_keysym_t keysym, char *text
) {
    return false;
}

static void
click_mode_render(struct state *state, void *mode_state, cairo_t *cairo) {}

static void click_mode_free(void *mode_state) {}

struct mode_interface click_mode_interface = {
    .name    = "click",
    .enter   = click_mode_enter,
    .reenter = click_mode_reenter,
    .key     = click_mode_key,
    .render  = click_mode_render,
    .free    = click_mode_free,
};


================================================
FILE: src/mode_floating.c
================================================
#include "config.h"
#include "log.h"
#include "mode.h"
#include "screencopy.h"
#include "state.h"
#include "target_detection.h"
#include "utils.h"
#include "utils_cairo.h"

#include <cairo.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon.h>

#define MIN_SUB_AREA_SIZE (25 * 50)

static void get_areas_from_stdin(struct floating_mode_state *ms) {
    size_t       areas_cap   = 256;
    struct rect *areas       = malloc(sizeof(struct rect) * areas_cap);
    int          areas_count = 0;
    char        *buf         = NULL;
    size_t       buf_n       = 0;

    while (getline(&buf, &buf_n, stdin) >= 0) {
        if (areas_count >= areas_cap) {
            areas_cap *= 2;
            areas      = realloc(areas, sizeof(struct rect) * areas_cap);
        }

        struct rect *curr_area     = &areas[areas_count];
        int          matched_count = sscanf(
            buf, "%dx%d+%d+%d", &curr_area->w, &curr_area->h, &curr_area->x,
            &curr_area->y
        );
        if (matched_count < 4) {
            LOG_ERR("Error parsing '%s'. Skipping.", buf);
            continue;
        }

        areas_count++;
    }

    free(buf);

    LOG_INFO("Got %d areas.", areas_count);

    ms->areas     = areas;
    ms->num_areas = areas_count;
}

#if OPENCV_ENABLED

static void get_area_from_screenshot(
    struct state *state, struct floating_mode_state *ms, struct rect area
) {
    // This is so that we don't capture window borders.
    area.x += 1;
    area.y += 1;
    area.h -= 2;
    area.w -= 2;

    struct scrcpy_buffer    *scrcpy_buffer = query_screenshot(state, area);
    enum wl_output_transform output_transform =
        state->current_output->transform;
    ms->num_areas = compute_target_from_img_buffer(
        scrcpy_buffer->data, scrcpy_buffer->height, scrcpy_buffer->width,
        scrcpy_buffer->stride, scrcpy_buffer->format, output_transform, area,
        &ms->areas
    );
    destroy_scrcpy_buffer(scrcpy_buffer);
}

#endif

void *floating_mode_enter(struct state *state, struct rect area) {
    struct floating_mode_state *ms = malloc(sizeof(*ms));

    ms->label_symbols =
        label_symbols_from_str(state->config.mode_floating.label_symbols);

    if (ms->label_symbols == NULL) {
        ms->areas           = NULL;
        ms->label_selection = NULL;
        state->running      = false;
        return ms;
    }

    switch (state->config.mode_floating.source) {
    case FLOATING_MODE_SOURCE_STDIN:
        get_areas_from_stdin(ms);
        break;
    case FLOATING_MODE_SOURCE_DETECT:
#if OPENCV_ENABLED
        get_area_from_screenshot(state, ms, area);
#else
        // This should not happen as the value is checked when loading the
        // configuration.
        LOG_ERR("Binary not built with OpenCV support.");
        exit(1);
#endif
        break;
    }

    ms->label_selection = label_selection_new(ms->label_symbols, ms->num_areas);

    ms->label_font_face = cairo_toy_font_face_create(
        state->config.mode_floating.label_font_family, CAIRO_FONT_SLANT_NORMAL,
        CAIRO_FONT_WEIGHT_NORMAL
    );

    return ms;
}

void floating_mode_reenter(struct state *state, void *mode_state) {
    struct floating_mode_state *ms = mode_state;
    label_selection_back(ms->label_selection);
}

static bool floating_mode_key(
    struct state *state, void *mode_state, xkb_keysym_t keysym, char *text
) {
    struct floating_mode_state *ms = mode_state;

    switch (keysym) {
    case XKB_KEY_BackSpace:
        return label_selection_back(ms->label_selection) != 0;

    case XKB_KEY_Escape:
        state->running = false;
        break;
    default:;
        int symbol_idx = label_symbols_find_idx(ms->label_symbols, text);
        if (symbol_idx < 0) {
            return false;
        }

        label_selection_append(ms->label_selection, symbol_idx);

        int idx = label_selection_to_idx(ms->label_selection);
        if (idx >= 0) {
            enter_next_mode(state, ms->areas[idx]);
        }
        return true;
    }

    return false;
}

void floating_mode_render(
    struct state *state, void *mode_state, cairo_t *cairo
) {
    struct floating_mode_state  *ms     = mode_state;
    struct mode_floating_config *config = &state->config.mode_floating;

    label_selection_t *curr_label =
        label_selection_new(ms->label_symbols, ms->num_areas);
    label_selection_set_from_idx(curr_label, 0);

    int  label_str_max_len = label_selection_str_max_len(curr_label) + 1;
    char label_selected_str[label_str_max_len];
    char label_unselected_str[label_str_max_len];

    cairo_set_font_face(cairo, ms->label_font_face);

    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
    cairo_set_source_u32(cairo, config->unselectable_bg_color);
    cairo_paint(cairo);

    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
    for (int i = 0; i < ms->num_areas; i++) {
        const bool selectable =
            label_selection_is_included(curr_label, ms->label_selection);

        if (selectable) {
            struct rect a = ms->areas[i];
            cairo_set_source_rgba(cairo, 0, 0, 0, 0);
            cairo_rectangle(cairo, a.x, a.y, a.w, a.h);
            cairo_fill(cairo);
        }

        label_selection_incr(curr_label);
    }

    label_selection_set_from_idx(curr_label, 0);
    for (int i = 0; i < ms->num_areas; i++) {
        struct rect a = ms->areas[i];

        const bool selectable =
            label_selection_is_included(curr_label, ms->label_selection);

        if (selectable) {
            cairo_set_operator(cairo, CAIRO_OPERATOR_OVER);
            cairo_set_source_u32(cairo, config->selectable_bg_color);
            cairo_rectangle(cairo, a.x, a.y, a.w, a.h);
            cairo_fill(cairo);

            cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
            cairo_set_source_u32(cairo, config->selectable_border_color);
            cairo_rectangle(cairo, a.x + .5, a.y + .5, a.w - 1, a.h - 1);
            cairo_set_line_width(cairo, 1);
            cairo_stroke(cairo);

            cairo_set_font_size(
                cairo, compute_relative_font_size(&config->label_font_size, a.h)
            );
            cairo_text_extents_t te_all;
            label_selection_str(curr_label, label_selected_str);
            cairo_text_extents(cairo, label_selected_str, &te_all);

            label_selection_str_split(
                curr_label, label_selected_str, label_unselected_str,
                ms->label_selection->next
            );

            cairo_text_extents_t te_selected, te_unselected;
            cairo_text_extents(cairo, label_selected_str, &te_selected);
            cairo_text_extents(cairo, label_unselected_str, &te_unselected);

            cairo_move_to(
                cairo,
                a.x +
                    (a.w - te_selected.x_advance - te_unselected.x_advance) / 2,
                a.y + (int)((a.h + te_all.height) / 2)
            );
            cairo_set_operator(cairo, CAIRO_OPERATOR_OVER);
            cairo_set_source_u32(cairo, config->label_select_color);
            cairo_show_text(cairo, label_selected_str);
            cairo_set_source_u32(cairo, config->label_color);
            cairo_show_text(cairo, label_unselected_str);
        }

        label_selection_incr(curr_label);
    }

    label_selection_free(curr_label);
}

void floating_mode_free(void *mode_state) {
    struct floating_mode_state *ms = mode_state;
    free(ms->areas);
    cairo_font_face_destroy(ms->label_font_face);
    label_selection_free(ms->label_selection);
    label_symbols_free(ms->label_symbols);
    free(ms);
}

struct mode_interface floating_mode_interface = {
    .name    = "floating",
    .enter   = floating_mode_enter,
    .reenter = floating_mode_reenter,
    .key     = floating_mode_key,
    .render  = floating_mode_render,
    .free    = floating_mode_free,
};


================================================
FILE: src/mode_split.c
================================================
#include "config.h"
#include "mode.h"
#include "state.h"
#include "utils.h"
#include "utils_cairo.h"
#include "utils_wayland.h"

#include <stdlib.h>

#define ARROW_SIZE 5

// Split direction -- defines the "shrink" direction of the rectangle
enum split_dir {
    SPLIT_DIR_DOWN  = 0,
    SPLIT_DIR_UP    = 1,
    SPLIT_DIR_LEFT  = 2,
    SPLIT_DIR_RIGHT = 3,
};

static void
split_mode_move_pointer(struct state *state, struct split_mode_state *ms) {
    struct rect *r = &ms->areas[ms->current];
    move_pointer(state, r->x + r->w / 2, r->y + r->h / 2, CLICK_NONE);
}

void *split_mode_enter(struct state *state, struct rect area) {
    struct split_mode_state *ms = malloc(sizeof(*ms));
    ms->areas[0]                = area;
    ms->current                 = 0;

    split_mode_move_pointer(state, ms);

    return ms;
}

static void split_mode_render_cursor(
    struct state *state, void *mode_state, cairo_t *cairo
) {
    struct mode_split_config *config = &state->config.mode_split;
    struct split_mode_state  *ms     = mode_state;
    struct rect              *area   = &ms->areas[ms->current];

    cairo_set_line_width(cairo, 1);
    cairo_set_source_u32(cairo, config->pointer_color);
    const int pointer_x = area->x + area->w / 2;
    const int pointer_y = area->y + area->h / 2;
    cairo_move_to(
        cairo, pointer_x + .5, pointer_y - (int)(config->pointer_size / 2) + .5
    );
    cairo_line_to(
        cairo, pointer_x + .5, pointer_y + (int)(config->pointer_size / 2) + .5
    );
    cairo_stroke(cairo);
    cairo_move_to(
        cairo, pointer_x - (int)(config->pointer_size / 2) + .5, pointer_y + .5
    );
    cairo_line_to(
        cairo, pointer_x + (int)(config->pointer_size / 2) + .5, pointer_y + .5
    );
    cairo_stroke(cairo);

    // Draw "undividable" marker, draw a red circle around the cursor
    if (area->w <= 1 && area->h <= 1) {
        cairo_set_source_u32(cairo, config->pointer_color);
        cairo_arc(
            cairo, area->x + .5, area->y + .5, config->pointer_size / 4., 0,
            2 * M_PI
        );
        cairo_set_line_width(cairo, 1);
        cairo_stroke(cairo);
    }
}

static void render_split_render_arrow(
    cairo_t *cairo, int x, int y, enum split_dir dir, uint32_t color
) {
    static const struct {
        char dx1 : 2;
        char dy1 : 2;
        char dx2 : 2;
        char dy2 : 2;
    } arrow_points[] = {
        [SPLIT_DIR_LEFT] =
            {
                .dx1 = 1,
                .dy1 = 1,
                .dx2 = 1,
                .dy2 = -1,
            },
        [SPLIT_DIR_RIGHT] =
            {
                .dx1 = -1,
                .dy1 = 1,
                .dx2 = -1,
                .dy2 = -1,
            },
        [SPLIT_DIR_UP] =
            {
                .dx1 = -1,
                .dy1 = 1,
                .dx2 = 1,
                .dy2 = 1,
            },

        [SPLIT_DIR_DOWN] = {
            .dx1 = -1,
            .dy1 = -1,
            .dx2 = 1,
            .dy2 = -1,
        },
    };

    if (dir < 0 || dir >= 4) {
        return;
    }

    cairo_set_source_u32(cairo, color);
    cairo_set_line_join(cairo, CAIRO_LINE_JOIN_ROUND);
    cairo_set_line_width(cairo, 2);
    cairo_move_to(
        cairo, x + ARROW_SIZE * arrow_points[dir].dx1 + .5,
        y + ARROW_SIZE * arrow_points[dir].dy1 + .5
    );
    cairo_line_to(cairo, x + .5, y + .5);
    cairo_line_to(
        cairo, x + ARROW_SIZE * arrow_points[dir].dx2 + .5,
        y + ARROW_SIZE * arrow_points[dir].dy2 + .5
    );
    cairo_stroke(cairo);
}

static void split_mode_render_markers(
    cairo_t *cairo, struct rect *area, uint32_t vcolor, uint32_t hcolor
) {
    ui
Download .txt
gitextract_pvjsi8rp/

├── .clang-format
├── .github/
│   └── ISSUE_TEMPLATE/
│       └── bug_report.md
├── .gitignore
├── LICENSE
├── README.md
├── config.example
├── helpers/
│   └── wl-kbptr-sway-active-win
├── meson.build
├── meson.options
├── protocol/
│   ├── fractional-scale-v1.xml
│   ├── meson.build
│   ├── wlr-layer-shell-unstable-v1.xml
│   ├── wlr-screencopy-unstable-v1.xml
│   └── wlr-virtual-pointer-unstable-v1.xml
├── share/
│   └── wl-kbptr.desktop
└── src/
    ├── config.c
    ├── config.h
    ├── label.c
    ├── label.h
    ├── log.h
    ├── main.c
    ├── mode.c
    ├── mode.h
    ├── mode_bisect.c
    ├── mode_click.c
    ├── mode_floating.c
    ├── mode_split.c
    ├── mode_tile.c
    ├── screencopy.c
    ├── screencopy.h
    ├── state.h
    ├── surface_buffer.c
    ├── surface_buffer.h
    ├── target_detection.cpp
    ├── target_detection.h
    ├── test_label.c
    ├── utils.c
    ├── utils.h
    ├── utils_cairo.c
    ├── utils_cairo.h
    ├── utils_wayland.c
    └── utils_wayland.h
Download .txt
SYMBOL INDEX (279 symbols across 25 files)

FILE: src/config.c
  function parse_color (line 19) | static int parse_color(void *dest, char *value) {
  function parse_double (line 82) | static int parse_double(void *dest, char *value) {
  function parse_uint8 (line 88) | static int parse_uint8(void *dest, char *value) {
  function parse_relative_font_size (line 99) | static int parse_relative_font_size(void *dest, char *value) {
  function parse_home_row_keys (line 176) | static int parse_home_row_keys(void *dest, char *value) {
  function parse_str (line 253) | static int parse_str(void *dest, char *value) {
  function parse_floating_mode_source_value (line 258) | static int parse_floating_mode_source_value(void *dest, char *value) {
  function parse_click (line 277) | static int parse_click(void *dest, char *value) {
  function free_home_row_keys (line 299) | static void free_home_row_keys(void *field_value) {
  function free_str (line 311) | static void free_str(void *field_value) {
  type field_def (line 315) | struct field_def {
  type section_def (line 323) | struct section_def {
  function noop (line 354) | static void noop() {}
  type section_def (line 358) | struct section_def
  function print_default_config (line 419) | void print_default_config() {
  function config_loader_init (line 439) | void config_loader_init(struct config_loader *loader, struct config *con...
  function config_loader_enter_section (line 444) | int config_loader_enter_section(struct config_loader *loader, char *sect...
  function config_loader_load_field (line 458) | int config_loader_load_field(
  function config_loader_load_cli_param (line 487) | int config_loader_load_cli_param(struct config_loader *loader, char *val...
  function config_set_default (line 541) | void config_set_default(struct config *config) {
  function config_free_values (line 562) | void config_free_values(struct config *config) {
  function FILE (line 578) | static FILE *open_config_file(char *file_name) {
  function config_loader_load_file (line 626) | int config_loader_load_file(struct config_loader *loader, char *file_nam...
  function compute_relative_font_size (line 751) | double

FILE: src/config.h
  type general_config (line 8) | struct general_config {
  type relative_font_size (line 14) | struct relative_font_size {
  type mode_tile_config (line 20) | struct mode_tile_config {
  type floating_mode_source (line 31) | enum floating_mode_source {
  type mode_floating_config (line 36) | struct mode_floating_config {
  type mode_bisect_config (line 48) | struct mode_bisect_config {
  type mode_split_config (line 66) | struct mode_split_config {
  type mode_click_config (line 78) | struct mode_click_config {
  type config (line 82) | struct config {
  type config_loader (line 94) | struct config_loader {
  type config (line 105) | struct config
  type config (line 111) | struct config
  type config_loader (line 117) | struct config_loader
  type config (line 117) | struct config
  type config_loader (line 124) | struct config_loader
  type config_loader (line 131) | struct config_loader
  type config_loader (line 138) | struct config_loader
  type config_loader (line 144) | struct config_loader
  type relative_font_size (line 147) | struct relative_font_size

FILE: src/label.c
  function label_symbols_t (line 10) | label_symbols_t *label_symbols_from_str(char *s) {
  function label_symbols_free (line 64) | void label_symbols_free(label_symbols_t *ls) {
  function label_symbols_find_idx (line 78) | int label_symbols_find_idx(label_symbols_t *label_symbols, char *s) {
  function label_selection_t (line 88) | label_selection_t *
  function label_selection_clear (line 105) | void label_selection_clear(label_selection_t *label_selection) {
  function label_selection_to_partial_idx (line 109) | static int label_selection_to_partial_idx(label_selection_t *label_selec...
  function label_selection_append (line 122) | enum label_selection_append_ret
  function label_selection_back (line 139) | bool label_selection_back(label_selection_t *label_selection) {
  function label_selection_is_included (line 148) | bool label_selection_is_included(
  function label_selection_to_idx (line 165) | int label_selection_to_idx(label_selection_t *label_selection) {
  function label_selection_set_from_idx (line 173) | int label_selection_set_from_idx(label_selection_t *label_selection, int...
  function label_selection_incr (line 186) | int label_selection_incr(label_selection_t *label_selection) {
  function label_symbols_max_str_len (line 202) | static int label_symbols_max_str_len(label_symbols_t *label_symbols) {
  function label_selection_str_max_len (line 226) | int label_selection_str_max_len(label_selection_t *label_selection) {
  function label_selection_str (line 231) | void label_selection_str(label_selection_t *label_selection, char *out) {
  function label_selection_str_split (line 243) | void label_selection_str_split(
  function label_selection_free (line 270) | void label_selection_free(label_selection_t *label_selection) {

FILE: src/label.h
  type label_symbols_t (line 6) | typedef struct {
  type label_selection_t (line 19) | typedef struct {
  type label_selection_append_ret (line 49) | enum label_selection_append_ret {
  type label_selection_append_ret (line 55) | enum label_selection_append_ret

FILE: src/main.c
  function send_frame (line 26) | static void send_frame(struct state *state) {
  function send_transparent_frame (line 68) | static void send_transparent_frame(struct state *state) {
  function surface_callback_done (line 87) | static void surface_callback_done(
  type wl_callback_listener (line 97) | struct wl_callback_listener
  function request_frame (line 101) | static void request_frame(struct state *state) {
  function compute_initial_area (line 113) | bool compute_initial_area(struct state *state, struct rect *initial_area) {
  function noop (line 150) | static void noop() {}
  function load_home_row (line 152) | static void load_home_row(
  function handle_keyboard_keymap (line 199) | static void handle_keyboard_keymap(
  function handle_keyboard_key (line 246) | static void handle_keyboard_key(
  function handle_keyboard_modifiers (line 267) | static void handle_keyboard_modifiers(
  type wl_keyboard_listener (line 278) | struct wl_keyboard_listener
  function handle_seat_capabilities (line 287) | static void handle_seat_capabilities(
  type wl_seat_listener (line 299) | struct wl_seat_listener
  function free_seats (line 304) | static void free_seats(struct wl_list *seats) {
  function free_outputs (line 326) | static void free_outputs(struct wl_list *outputs) {
  type output (line 338) | struct output
  type wl_list (line 339) | struct wl_list
  type wl_output (line 339) | struct wl_output
  type output (line 341) | struct output
  function handle_output_scale (line 351) | static void
  function handle_output_geometry (line 357) | static void handle_output_geometry(
  type wl_output_listener (line 366) | struct wl_output_listener
  function handle_xdg_output_logical_position (line 375) | static void handle_xdg_output_logical_position(
  function handle_xdg_output_logical_size (line 383) | static void handle_xdg_output_logical_size(
  function handle_xdg_output_name (line 391) | static void handle_xdg_output_name(
  type zxdg_output_v1_listener (line 398) | struct zxdg_output_v1_listener
  function load_xdg_outputs (line 406) | static void load_xdg_outputs(struct state *state) {
  function enter_first_mode (line 420) | static void enter_first_mode(struct state *state) {
  function handle_surface_enter (line 447) | static void handle_surface_enter(
  type wl_surface_listener (line 460) | struct wl_surface_listener
  function handle_registry_global (line 467) | static void handle_registry_global(
  type wl_registry_listener (line 536) | struct wl_registry_listener
  function handle_layer_surface_configure (line 541) | static void handle_layer_surface_configure(
  function handle_layer_surface_closed (line 559) | static void handle_layer_surface_closed(
  type zwlr_layer_surface_v1_listener (line 566) | struct zwlr_layer_surface_v1_listener
  function fractional_scale_preferred (line 571) | static void fractional_scale_preferred(
  type wp_fractional_scale_v1_listener (line 583) | struct wp_fractional_scale_v1_listener
  type output (line 587) | struct output
  type state (line 588) | struct state
  type rect (line 588) | struct rect
  type output (line 589) | struct output
  type output (line 601) | struct output
  type state (line 601) | struct state
  type output (line 602) | struct output
  function print_result (line 612) | static void print_result(struct state *state) {
  function print_usage (line 635) | static void print_usage() {
  function print_version (line 648) | static void print_version() {
  function main (line 656) | int main(int argc, char **argv) {

FILE: src/mode.c
  type mode_interface (line 8) | struct mode_interface
  type mode_interface (line 9) | struct mode_interface
  type mode_interface (line 10) | struct mode_interface
  type mode_interface (line 11) | struct mode_interface
  type mode_interface (line 12) | struct mode_interface
  type mode_interface (line 14) | struct mode_interface
  type mode_interface (line 19) | struct mode_interface
  type mode_interface (line 20) | struct mode_interface
  function load_modes (line 32) | int load_modes(struct state *state, char *modes) {
  function enter_next_mode (line 65) | void enter_next_mode(struct state *state, struct rect area) {
  function has_last_mode_returned (line 81) | bool has_last_mode_returned(struct state *state) {
  function reenter_prev_mode (line 86) | bool reenter_prev_mode(struct state *state) {
  function free_mode_states (line 104) | void free_mode_states(struct state *state) {
  function mode_handle_key (line 119) | bool mode_handle_key(struct state *state, xkb_keysym_t sym, char *text) {
  function mode_render (line 128) | void mode_render(struct state *state, cairo_t *cairo) {

FILE: src/mode.h
  type mode_interface (line 10) | struct mode_interface {
  type mode_interface (line 19) | struct mode_interface
  type state (line 25) | struct state
  type state (line 27) | struct state
  type rect (line 27) | struct rect
  type state (line 28) | struct state
  type state (line 29) | struct state
  type state (line 30) | struct state
  type state (line 31) | struct state
  type state (line 32) | struct state

FILE: src/mode_bisect.c
  type bisect_division (line 14) | enum bisect_division {
  function bisect_mode_move_pointer (line 62) | static void
  type state (line 68) | struct state
  type rect (line 68) | struct rect
  type bisect_mode_state (line 69) | struct bisect_mode_state
  function determine_division (line 83) | static enum bisect_division determine_division(struct rect *area) {
  type division_interface (line 99) | struct division_interface {
  function division_4_or_8_render (line 114) | static void division_4_or_8_render(
  function division_4_or_8_idx_to_rect (line 224) | static bool division_4_or_8_idx_to_rect(
  function division_horizontal_render (line 251) | static void division_horizontal_render(
  function division_horizontal_idx_to_rect (line 287) | static bool division_horizontal_idx_to_rect(
  function division_vertical_render (line 302) | static void division_vertical_render(
  function division_vertical_idx_to_rect (line 338) | static bool division_vertical_idx_to_rect(
  function undividable_render (line 353) | static void undividable_render(
  function undividable_select_idx (line 369) | static bool undividable_select_idx() {
  type division_interface (line 373) | struct division_interface
  function bisect_mode_render (line 391) | static void
  function bisect_mode_key (line 437) | static bool bisect_mode_key(
  function bisect_mode_reenter (line 507) | void bisect_mode_reenter(struct state *state, void *mode_state) {
  function bisect_mode_free (line 510) | void bisect_mode_free(void *mode_state) {
  type mode_interface (line 516) | struct mode_interface

FILE: src/mode_click.c
  type state (line 3) | struct state
  type rect (line 3) | struct rect
  function click_mode_reenter (line 9) | static void click_mode_reenter(struct state *state, void *mode_state) {
  function click_mode_key (line 13) | static bool click_mode_key(
  function click_mode_render (line 19) | static void
  function click_mode_free (line 22) | static void click_mode_free(void *mode_state) {}
  type mode_interface (line 24) | struct mode_interface

FILE: src/mode_floating.c
  function get_areas_from_stdin (line 19) | static void get_areas_from_stdin(struct floating_mode_state *ms) {
  function get_area_from_screenshot (line 55) | static void get_area_from_screenshot(
  type state (line 77) | struct state
  type rect (line 77) | struct rect
  type floating_mode_state (line 78) | struct floating_mode_state
  function floating_mode_reenter (line 116) | void floating_mode_reenter(struct state *state, void *mode_state) {
  function floating_mode_key (line 121) | static bool floating_mode_key(
  function floating_mode_render (line 151) | void floating_mode_render(
  function floating_mode_free (line 240) | void floating_mode_free(void *mode_state) {
  type mode_interface (line 249) | struct mode_interface

FILE: src/mode_split.c
  type split_dir (line 13) | enum split_dir {
  function split_mode_move_pointer (line 20) | static void
  type state (line 26) | struct state
  type rect (line 26) | struct rect
  type split_mode_state (line 27) | struct split_mode_state
  function split_mode_render_cursor (line 36) | static void split_mode_render_cursor(
  function render_split_render_arrow (line 74) | static void render_split_render_arrow(
  function split_mode_render_markers (line 132) | static void split_mode_render_markers(
  function split_mode_render (line 188) | static void
  function split_mode_split (line 220) | static bool
  function split_mode_key (line 271) | static bool split_mode_key(
  function split_mode_reenter (line 351) | void split_mode_reenter(struct state *state, void *mode_state) {
  function split_mode_free (line 354) | void split_mode_free(void *mode_state) {
  type mode_interface (line 358) | struct mode_interface

FILE: src/mode_tile.c
  type state (line 16) | struct state
  type rect (line 16) | struct rect
  type tile_mode_state (line 17) | struct tile_mode_state
  function tile_mode_back (line 63) | static bool tile_mode_back(struct tile_mode_state *mode_state) {
  function tile_mode_reenter (line 69) | void tile_mode_reenter(struct state *state, void *mode_state) {
  function idx_to_rect (line 74) | static struct rect
  function tile_mode_key (line 91) | static bool tile_mode_key(
  function tile_mode_render (line 124) | void tile_mode_render(struct state *state, void *mode_state, cairo_t *ca...
  function tile_mode_state_free (line 214) | void tile_mode_state_free(void *mode_state) {
  type mode_interface (line 222) | struct mode_interface

FILE: src/screencopy.c
  type screen_capture_state (line 16) | enum screen_capture_state {
  type scrcpy_state (line 23) | struct scrcpy_state {
  type scrcpy_buffer (line 30) | struct scrcpy_buffer
  type wl_shm (line 31) | struct wl_shm
  type wl_shm_format (line 31) | enum wl_shm_format
  type wl_shm_pool (line 50) | struct wl_shm_pool
  type wl_buffer (line 51) | struct wl_buffer
  type scrcpy_buffer (line 58) | struct scrcpy_buffer
  function destroy_scrcpy_buffer (line 70) | void destroy_scrcpy_buffer(struct scrcpy_buffer *buf) {
  function screencopy_frame_handle_buffer (line 78) | static void screencopy_frame_handle_buffer(
  function screencopy_frame_handle_ready (line 95) | static void screencopy_frame_handle_ready(
  function screencopy_frame_handle_failed (line 103) | static void screencopy_frame_handle_failed(
  function noop (line 111) | static void noop() {}
  type zwlr_screencopy_frame_v1_listener (line 113) | struct zwlr_screencopy_frame_v1_listener
  type scrcpy_buffer (line 123) | struct scrcpy_buffer
  type state (line 124) | struct state
  type rect (line 124) | struct rect
  type scrcpy_state (line 125) | struct scrcpy_state

FILE: src/screencopy.h
  type scrcpy_buffer (line 8) | struct scrcpy_buffer {
  type state (line 17) | struct state
  type rect (line 18) | struct rect
  type scrcpy_buffer (line 19) | struct scrcpy_buffer
  type state (line 19) | struct state
  type rect (line 19) | struct rect
  type scrcpy_buffer (line 21) | struct scrcpy_buffer

FILE: src/state.h
  type mode_interface (line 40) | struct mode_interface
  type tile_mode_state (line 42) | struct tile_mode_state {
  type floating_mode_state (line 59) | struct floating_mode_state {
  type bisect_mode_state (line 69) | struct bisect_mode_state {
  type split_mode_state (line 76) | struct split_mode_state {
  type output (line 81) | struct output {
  type seat (line 94) | struct seat {
  type state (line 104) | struct state {

FILE: src/surface_buffer.c
  function create_shm_file (line 15) | static int create_shm_file(void) {
  function allocate_shm_file (line 26) | int allocate_shm_file(size_t size) {
  function handle_buffer_release (line 42) | static void handle_buffer_release(void *data, struct wl_buffer *wl_buffe...
  type wl_buffer_listener (line 46) | struct wl_buffer_listener
  type surface_buffer (line 50) | struct surface_buffer
  type wl_shm (line 51) | struct wl_shm
  type surface_buffer (line 51) | struct surface_buffer
  type wl_shm_pool (line 73) | struct wl_shm_pool
  function surface_buffer_destroy (line 96) | static void surface_buffer_destroy(struct surface_buffer *buffer) {
  function surface_buffer_pool_init (line 120) | void surface_buffer_pool_init(struct surface_buffer_pool *pool) {
  function surface_buffer_pool_destroy (line 124) | void surface_buffer_pool_destroy(struct surface_buffer_pool *pool) {
  type surface_buffer (line 129) | struct surface_buffer
  type wl_shm (line 130) | struct wl_shm
  type surface_buffer_pool (line 130) | struct surface_buffer_pool
  type surface_buffer (line 133) | struct surface_buffer

FILE: src/surface_buffer.h
  type surface_buffer_state (line 7) | enum surface_buffer_state {
  type surface_buffer (line 16) | struct surface_buffer {
  type surface_buffer_pool (line 27) | struct surface_buffer_pool {
  type surface_buffer_pool (line 31) | struct surface_buffer_pool
  type surface_buffer_pool (line 32) | struct surface_buffer_pool
  type surface_buffer (line 34) | struct surface_buffer
  type wl_shm (line 35) | struct wl_shm
  type surface_buffer_pool (line 35) | struct surface_buffer_pool

FILE: src/target_detection.cpp
  function pixman_format_code_t (line 12) | static pixman_format_code_t get_pixman_format(enum wl_shm_format format) {
  function pixman_image_t (line 71) | static pixman_image_t *make_pixman_image_a8r8g8b8(
  function get_gray_scale_from_buffer (line 118) | static cv::Mat get_gray_scale_from_buffer(
  function apply_transform (line 178) | static void apply_transform(
  function compute_rects (line 236) | static void compute_rects(
  function filter_rects (line 255) | static size_t filter_rects(
  function compute_target_from_img_buffer (line 341) | int compute_target_from_img_buffer(

FILE: src/target_detection.h
  type wl_shm_format (line 19) | enum wl_shm_format
  type wl_output_transform (line 19) | enum wl_output_transform
  type rect (line 20) | struct rect
  type rect (line 20) | struct rect

FILE: src/test_label.c
  function main (line 6) | int main() {

FILE: src/utils.c
  function min (line 4) | int min(int a, int b) {
  function max (line 8) | int max(int a, int b) {
  function str_to_rune (line 12) | int str_to_rune(char *str, uint32_t *rune) {
  function find_str (line 54) | int find_str(char **strs, size_t len, char *to_find) {

FILE: src/utils.h
  type rect (line 7) | struct rect {
  type click (line 14) | enum click {

FILE: src/utils_cairo.c
  function cairo_set_source_u32 (line 5) | void cairo_set_source_u32(void *cairo, uint32_t color) {

FILE: src/utils_wayland.c
  function _apply_transform (line 8) | static void _apply_transform(
  function move_pointer (line 64) | void move_pointer(

FILE: src/utils_wayland.h
  type state (line 7) | struct state
  type click (line 7) | enum click
Condensed preview — 42 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (257K chars).
[
  {
    "path": ".clang-format",
    "chars": 5930,
    "preview": "---\nLanguage:        Cpp\nAlignAfterOpenBracket: BlockIndent\nAlignArrayOfStructures: None\nAlignConsecutiveAssignments:\n  "
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 1240,
    "preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\nFirst describe t"
  },
  {
    "path": ".gitignore",
    "chars": 13,
    "preview": ".cache\n*.gch\n"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 9592,
    "preview": "# wl-kbptr\n\n`wl-kbptr` &mdash; short for Wayland Keyboard Pointer &mdash; is a utility to help move the mouse pointer wi"
  },
  {
    "path": "config.example",
    "chars": 1284,
    "preview": "# wl-kbptr can be configured with a configuration file.\n# The file location can be passed with the -c parameter.\n# Othew"
  },
  {
    "path": "helpers/wl-kbptr-sway-active-win",
    "chars": 217,
    "preview": "#!/bin/sh\n\nactive_area=$(swaymsg -t get_tree | jq --raw-output \\\n\t'.. | (.nodes? + .floating_nodes? // empty)[] | select"
  },
  {
    "path": "meson.build",
    "chars": 1762,
    "preview": "project(\n  'wl-kbptr',\n  'c',\n  meson_version: '>=1.1',\n  default_options: ['c_std=c11'],\n  license: 'GPL-3.0',\n  versio"
  },
  {
    "path": "meson.options",
    "chars": 53,
    "preview": "option('opencv', type: 'feature', value: 'disabled')\n"
  },
  {
    "path": "protocol/fractional-scale-v1.xml",
    "chars": 4635,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<protocol name=\"fractional_scale_v1\">\n  <copyright>\n    Copyright © 2022 Kenny Le"
  },
  {
    "path": "protocol/meson.build",
    "chars": 1032,
    "preview": "wayland_scanner_dep = dependency('wayland-scanner', native: true)\nwayland_scanner = find_program(\n  wayland_scanner_dep."
  },
  {
    "path": "protocol/wlr-layer-shell-unstable-v1.xml",
    "chars": 18461,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<protocol name=\"wlr_layer_shell_unstable_v1\">\n  <copyright>\n    Copyright © 2017 "
  },
  {
    "path": "protocol/wlr-screencopy-unstable-v1.xml",
    "chars": 10164,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<protocol name=\"wlr_screencopy_unstable_v1\">\n  <copyright>\n    Copyright © 2018 S"
  },
  {
    "path": "protocol/wlr-virtual-pointer-unstable-v1.xml",
    "chars": 6894,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<protocol name=\"wlr_virtual_pointer_unstable_v1\">\n  <copyright>\n    Copyright © 2"
  },
  {
    "path": "share/wl-kbptr.desktop",
    "chars": 140,
    "preview": "[Desktop Entry]\nVersion=1.0\nName=wl-kbptr\nComment=Control the mouse pointer with the keyboard\nExec=wl-kbptr\nTerminal=fal"
  },
  {
    "path": "src/config.c",
    "chars": 22421,
    "preview": "#include \"config.h\"\n\n#include \"log.h\"\n#include \"state.h\"\n\n#include <errno.h>\n#include <stddef.h>\n#include <stdio.h>\n#inc"
  },
  {
    "path": "src/config.h",
    "chars": 3919,
    "preview": "#ifndef __CONFIG_H_INCLUDED__\n#define __CONFIG_H_INCLUDED__\n\n#include \"utils.h\"\n\n#include <stdint.h>\n\nstruct general_con"
  },
  {
    "path": "src/label.c",
    "chars": 7130,
    "preview": "#include \"label.h\"\n\n#include \"log.h\"\n#include \"utils.h\"\n\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n\nl"
  },
  {
    "path": "src/label.h",
    "chars": 2818,
    "preview": "#ifndef __LABEL_H_INCLUDED__\n#define __LABEL_H_INCLUDED__\n\n#include <stdbool.h>\n\ntypedef struct {\n    /*         data   "
  },
  {
    "path": "src/log.h",
    "chars": 542,
    "preview": "#ifndef __LOG_H_INCLUDED__\n#define __LOG_H_INCLUDED__\n\n#include <stdio.h>\n\n#define LOG_ERR(msg, ...) \\\n    fprintf(stder"
  },
  {
    "path": "src/main.c",
    "chars": 29962,
    "preview": "#include \"config.h\"\n#include \"fractional-scale-v1-client-protocol.h\"\n#include \"log.h\"\n#include \"mode.h\"\n#include \"state."
  },
  {
    "path": "src/mode.c",
    "chars": 3705,
    "preview": "#include \"mode.h\"\n\n#include \"log.h\"\n\n#include <stdlib.h>\n#include <string.h>\n\nextern struct mode_interface tile_mode_int"
  },
  {
    "path": "src/mode.h",
    "chars": 963,
    "preview": "#ifndef __MODE_H_INCLUDED__\n#define __MODE_H_INCLUDED__\n\n#include \"state.h\"\n\n#include <cairo.h>\n#include <stdbool.h>\n#in"
  },
  {
    "path": "src/mode_bisect.c",
    "chars": 16190,
    "preview": "#include \"config.h\"\n#include \"mode.h\"\n#include \"state.h\"\n#include \"utils.h\"\n#include \"utils_cairo.h\"\n#include \"utils_way"
  },
  {
    "path": "src/mode_click.c",
    "chars": 807,
    "preview": "#include \"mode.h\"\n\nstatic void *click_mode_enter(struct state *state, struct rect area) {\n    state->click = state->conf"
  },
  {
    "path": "src/mode_floating.c",
    "chars": 7918,
    "preview": "#include \"config.h\"\n#include \"log.h\"\n#include \"mode.h\"\n#include \"screencopy.h\"\n#include \"state.h\"\n#include \"target_detec"
  },
  {
    "path": "src/mode_split.c",
    "chars": 9822,
    "preview": "#include \"config.h\"\n#include \"mode.h\"\n#include \"state.h\"\n#include \"utils.h\"\n#include \"utils_cairo.h\"\n#include \"utils_way"
  },
  {
    "path": "src/mode_tile.c",
    "chars": 7824,
    "preview": "#include \"config.h\"\n#include \"label.h\"\n#include \"mode.h\"\n#include \"state.h\"\n#include \"utils.h\"\n#include \"utils_cairo.h\"\n"
  },
  {
    "path": "src/screencopy.c",
    "chars": 4409,
    "preview": "#if OPENCV_ENABLED\n\n#include \"screencopy.h\"\n\n#include \"log.h\"\n#include \"state.h\"\n#include \"surface_buffer.h\"\n#include \"w"
  },
  {
    "path": "src/screencopy.h",
    "chars": 511,
    "preview": "#ifndef __SCREENCOPY_H_INCLUDED__\n#define __SCREENCOPY_H_INCLUDED__\n\n#if OPENCV_ENABLED\n\n#include <wayland-client.h>\n\nst"
  },
  {
    "path": "src/state.h",
    "chars": 4424,
    "preview": "#ifndef __STATE_H_INCLUDED__\n#define __STATE_H_INCLUDED__\n\n#include \"config.h\"\n#include \"fractional-scale-v1-client-prot"
  },
  {
    "path": "src/surface_buffer.c",
    "chars": 4055,
    "preview": "#include \"surface_buffer.h\"\n\n#include \"log.h\"\n\n#include <cairo/cairo.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <"
  },
  {
    "path": "src/surface_buffer.h",
    "chars": 1090,
    "preview": "#ifndef __SURFACE_BUFFER_H_INCLUDED__\n#define __SURFACE_BUFFER_H_INCLUDED__\n\n#include <cairo/cairo.h>\n#include <wayland-"
  },
  {
    "path": "src/target_detection.cpp",
    "chars": 10964,
    "preview": "#include \"target_detection.h\"\n\n#include \"log.h\"\n\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n#includ"
  },
  {
    "path": "src/target_detection.h",
    "chars": 504,
    "preview": "#ifndef __TARGET_DETECTION_INCLUDED__\n#define __TARGET_DETECTION_INCLUDED__\n\n#ifdef __cplusplus\n#define EXTERNC extern \""
  },
  {
    "path": "src/test_label.c",
    "chars": 4202,
    "preview": "#include \"log.h\"\n#include \"src/label.h\"\n\n#include <string.h>\n\nint main() {\n    label_symbols_t *label_symbols = label_sy"
  },
  {
    "path": "src/utils.c",
    "chars": 1287,
    "preview": "#include <stdint.h>\n#include <string.h>\n\nint min(int a, int b) {\n    return a < b ? a : b;\n}\n\nint max(int a, int b) {\n  "
  },
  {
    "path": "src/utils.h",
    "chars": 539,
    "preview": "#ifndef __UTILS_H_INCLUDED__\n#define __UTILS_H_INCLUDED__\n\n#include <stddef.h>\n#include <stdint.h>\n\nstruct rect {\n    in"
  },
  {
    "path": "src/utils_cairo.c",
    "chars": 293,
    "preview": "#include \"utils_cairo.h\"\n\n#include <cairo.h>\n\nvoid cairo_set_source_u32(void *cairo, uint32_t color) {\n    cairo_set_sou"
  },
  {
    "path": "src/utils_cairo.h",
    "chars": 156,
    "preview": "#ifndef __CAIRO_UTILS_H_INCLUDED__\n#define __CAIRO_UTILS_H_INCLUDED__\n\n#include <stdint.h>\n\nvoid cairo_set_source_u32(vo"
  },
  {
    "path": "src/utils_wayland.c",
    "chars": 2959,
    "preview": "#include \"utils_wayland.h\"\n\n#include \"state.h\"\n#include \"wlr-virtual-pointer-unstable-v1-client-protocol.h\"\n\n#include <w"
  },
  {
    "path": "src/utils_wayland.h",
    "chars": 191,
    "preview": "#ifndef __UTILS_WAYLAND_H_INCLUDED__\n#define __UTILS_WAYLAND_H_INCLUDED__\n\n#include \"state.h\"\n\nvoid move_pointer(\n    st"
  }
]

About this extraction

This page contains the full source code of the moverest/wl-kbptr GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 42 files (240.4 KB), approximately 61.4k tokens, and a symbol index with 279 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!