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.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
# wl-kbptr
`wl-kbptr` — short for Wayland Keyboard Pointer — 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) — which uses arbitrary areas either given by the user or detected,
- [`tile`](#tile-mode) — which uses a grid to select areas,
- [`bisect`](#bisect-mode) — which enables to bisect an area,
- [`split`](#split-mode) — which enables to successively split an area,
- and [`click`](#click-mode) — 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 — e.g. select the wrong area — 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 — 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` — 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
================================================
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.
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.
A global interface for requesting surfaces to use fractional scales.
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.
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.
An additional interface to a wl_surface object which allows the compositor
to inform the client of the preferred scale.
Destroy the fractional scale object. When this object is destroyed,
preferred_scale events will no longer be sent.
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.
================================================
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
================================================
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
This request destroys the layer surface.
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.
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.
Change the layer that the surface is rendered on.
Layer is double-buffered, see wl_surface.commit.
================================================
FILE: protocol/wlr-screencopy-unstable-v1.xml
================================================
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.
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.
This object is a manager which offers requests to start capturing from a
source.
Capture the next frame of an entire output.
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.
All objects created by the manager will still remain valid, until their
appropriate destroy request has been called.
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.
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.
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.
Provides flags about the frame. This event is sent once before the
"ready" event.
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.
This event indicates that the attempted frame copy has failed.
After receiving this event, the client should destroy the object.
Destroys the frame. This request can be sent at any time by the client.
Same as copy, except it waits until there is damage to copy.
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.
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.
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.
================================================
FILE: protocol/wlr-virtual-pointer-unstable-v1.xml
================================================
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.
This protocol allows clients to emulate a physical pointer device. The
requests are mostly mirror opposites of those specified in wl_pointer.
The pointer has moved by a relative amount to the previous request.
Values are in the global compositor space.
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.
A button was pressed or released.
Scroll and other axis requests.
Indicates the set of events that logically belong together.
Source information for scroll and other axis.
Stop notification for scroll and other axes.
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.
This object allows clients to create individual virtual pointer objects.
Creates a new virtual pointer. The optional seat is a suggestion to the
compositor.
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.
================================================
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
#include
#include
#include
#include
/**
* `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 = §ion_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 = §ion_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 = §ion_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 = §ion_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 = §ion_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
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
#include
#include
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
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
#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
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
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
#include
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
#include
#include
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
#include
#include
#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
#include
#include
#include
#include
#include
#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
#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
) {
uint32_t middle_x = area->x + area->w / 2;
uint32_t middle_y = area->y + area->h / 2;
cairo_set_source_u32(cairo, hcolor);
cairo_set_line_width(cairo, 1);
cairo_move_to(cairo, middle_x + .5, area->y + .5);
cairo_line_to(cairo, middle_x + .5, area->y + area->h + .5);
cairo_stroke(cairo);
cairo_set_source_u32(cairo, vcolor);
cairo_set_line_width(cairo, 1);
cairo_move_to(cairo, area->x + .5, middle_y + .5);
cairo_line_to(cairo, area->x + area->w + .5, middle_y + .5);
cairo_stroke(cairo);
/*
x x+w/4 x+w
+--+-----+--+ y
| . . |
+.....0.....+ y+h/4 (2)
| . . |
|..2..*..3..|
| . . |
+.....1.....+ y+3h/4 (3)
| . . |
+--+-----+--+ y+h
(0) x+3w/4
*/
if (area->w > 1) {
render_split_render_arrow(
cairo, area->x + area->w / 4, area->y + area->h / 2, SPLIT_DIR_LEFT,
hcolor
);
render_split_render_arrow(
cairo, area->x + area->w * 3 / 4, area->y + area->h / 2,
SPLIT_DIR_RIGHT, hcolor
);
}
if (area->h > 1) {
render_split_render_arrow(
cairo, area->x + area->w / 2, area->y + area->h / 4, SPLIT_DIR_UP,
vcolor
);
render_split_render_arrow(
cairo, area->x + area->w / 2, area->y + area->h * 3 / 4,
SPLIT_DIR_DOWN, vcolor
);
}
}
static void
split_mode_render(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;
cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
cairo_set_source_u32(cairo, config->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);
}
struct rect *area = &ms->areas[ms->current];
cairo_set_source_u32(cairo, config->area_bg_color);
cairo_rectangle(
cairo, area->x + .5, area->y + .5, area->w - 1, area->h - 1
);
cairo_fill(cairo);
split_mode_render_markers(
cairo, area, config->vertical_color, config->horizontal_color
);
split_mode_render_cursor(state, mode_state, cairo);
}
static bool
split_mode_split(struct state *state, void *mode_state, enum split_dir dir) {
struct split_mode_state *ms = mode_state;
if (ms->current + 1 >= SPLIT_MAX_HISTORY) {
return false;
}
struct rect *area = &ms->areas[ms->current];
struct rect *new_area = &ms->areas[ms->current + 1];
*new_area = *area;
switch (dir) {
case SPLIT_DIR_RIGHT:
if (area->w <= 1) {
return false; /* Cannot split further */
}
new_area->w = area->w / 2;
new_area->x += new_area->w;
break;
case SPLIT_DIR_LEFT:
if (area->w <= 1) {
return false; /* Cannot split further */
}
new_area->w = area->w / 2;
break;
case SPLIT_DIR_UP:
if (area->h <= 1) {
return false; /* Cannot split further */
}
new_area->h = area->h / 2;
break;
case SPLIT_DIR_DOWN:
if (area->h <= 1) {
return false; /* Cannot split further */
}
new_area->h = area->h / 2;
new_area->y += new_area->h;
break;
}
ms->current++;
split_mode_move_pointer(state, ms);
return true;
}
static bool split_mode_key(
struct state *state, void *mode_state, xkb_keysym_t keysym, char *text
) {
struct split_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--;
split_mode_move_pointer(state, ms);
} else {
reenter_prev_mode(state);
}
return true;
case XKB_KEY_Left:
return split_mode_split(state, mode_state, SPLIT_DIR_LEFT);
case XKB_KEY_Right:
return split_mode_split(state, mode_state, SPLIT_DIR_RIGHT);
case XKB_KEY_Up:
return split_mode_split(state, mode_state, SPLIT_DIR_UP);
case XKB_KEY_Down:
return split_mode_split(state, mode_state, SPLIT_DIR_DOWN);
}
int matched_i = find_str(state->home_row, HOME_ROW_LEN_WITH_BTN, text);
switch (matched_i) {
case HOME_ROW_LEFT_CLICK:
state->click = CLICK_LEFT_BTN;
enter_next_mode(state, ms->areas[ms->current]);
return false;
case HOME_ROW_RIGHT_CLICK:
state->click = CLICK_RIGHT_BTN;
enter_next_mode(state, ms->areas[ms->current]);
return false;
case HOME_ROW_MIDDLE_CLICK:
state->click = CLICK_MIDDLE_BTN;
enter_next_mode(state, ms->areas[ms->current]);
return false;
default:
break;
}
// Handle `wasd` and `hjkl` but only after home_row_keys
switch (text[0]) {
case 'a':
case 'h':
return split_mode_split(state, mode_state, SPLIT_DIR_LEFT);
case 'd':
case 'l':
return split_mode_split(state, mode_state, SPLIT_DIR_RIGHT);
case 'w':
case 'k':
return split_mode_split(state, mode_state, SPLIT_DIR_UP);
case 's':
case 'j':
return split_mode_split(state, mode_state, SPLIT_DIR_DOWN);
}
return false;
}
void split_mode_reenter(struct state *state, void *mode_state) {
split_mode_move_pointer(state, mode_state);
}
void split_mode_free(void *mode_state) {
free(mode_state);
}
struct mode_interface split_mode_interface = {
.name = "split",
.enter = split_mode_enter,
.reenter = split_mode_reenter,
.key = split_mode_key,
.render = split_mode_render,
.free = split_mode_free,
};
================================================
FILE: src/mode_tile.c
================================================
#include "config.h"
#include "label.h"
#include "mode.h"
#include "state.h"
#include "utils.h"
#include "utils_cairo.h"
#include
#include
#include
#include
#include
#define MIN_SUB_AREA_SIZE (25 * 50)
void *tile_mode_enter(struct state *state, struct rect area) {
struct tile_mode_state *ms = malloc(sizeof(*ms));
ms->area = area;
const int max_num_sub_areas = 26 * 26;
const int area_size = ms->area.w * ms->area.h;
const int sub_area_size =
max(area_size / max_num_sub_areas, MIN_SUB_AREA_SIZE);
ms->sub_area_height = sqrt(sub_area_size / 2.);
ms->sub_area_rows = ms->area.h / ms->sub_area_height;
if (ms->sub_area_rows == 0) {
ms->sub_area_rows = 1;
}
ms->sub_area_height_off = ms->area.h % ms->sub_area_rows;
ms->sub_area_height = ms->area.h / ms->sub_area_rows;
ms->sub_area_width = sqrt(sub_area_size * 2);
ms->sub_area_columns = ms->area.w / ms->sub_area_width;
if (ms->sub_area_columns == 0) {
ms->sub_area_columns = 1;
}
ms->sub_area_width_off = ms->area.w % ms->sub_area_columns;
ms->sub_area_width = ms->area.w / ms->sub_area_columns;
ms->label_symbols =
label_symbols_from_str(state->config.mode_tile.label_symbols);
if (ms->label_symbols == NULL) {
ms->label_selection = NULL;
state->running = false;
return ms;
}
ms->label_selection = label_selection_new(
ms->label_symbols, ms->sub_area_rows * ms->sub_area_columns
);
ms->label_font_face = cairo_toy_font_face_create(
state->config.mode_tile.label_font_family, CAIRO_FONT_SLANT_NORMAL,
CAIRO_FONT_WEIGHT_NORMAL
);
return ms;
}
// `tile_mode_back` goes back in history. Returns true if there was something to
// go back to.
static bool tile_mode_back(struct tile_mode_state *mode_state) {
return label_selection_back(mode_state->label_selection) != 0;
}
// `tile_mode_reenter` reenters the tile mode. We assume that the saved state is
// valid and goes back in history once.
void tile_mode_reenter(struct state *state, void *mode_state) {
struct tile_mode_state *ms = mode_state;
tile_mode_back(ms);
}
static struct rect
idx_to_rect(struct tile_mode_state *mode_state, int idx, int x_off, int y_off) {
int column = idx / mode_state->sub_area_rows;
int row = idx % mode_state->sub_area_rows;
return (struct rect){
.x = column * mode_state->sub_area_width +
min(column, mode_state->sub_area_width_off) + x_off,
.w = mode_state->sub_area_width +
(column < mode_state->sub_area_width_off ? 1 : 0),
.y = row * mode_state->sub_area_height +
min(row, mode_state->sub_area_height_off) + y_off,
.h = mode_state->sub_area_height +
(row < mode_state->sub_area_height_off ? 1 : 0),
};
}
static bool tile_mode_key(
struct state *state, void *mode_state, xkb_keysym_t keysym, char *text
) {
struct tile_mode_state *ms = mode_state;
switch (keysym) {
case XKB_KEY_BackSpace:
return tile_mode_back(ms);
break;
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, idx_to_rect(ms, idx, ms->area.x, ms->area.y)
);
}
return true;
}
return false;
}
void tile_mode_render(struct state *state, void *mode_state, cairo_t *cairo) {
struct mode_tile_config *config = &state->config.mode_tile;
struct tile_mode_state *ms = mode_state;
cairo_set_font_face(cairo, ms->label_font_face);
cairo_set_font_size(
cairo, compute_relative_font_size(
&config->label_font_size, ms->sub_area_height
)
);
cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
cairo_set_source_u32(cairo, config->unselectable_bg_color);
cairo_paint(cairo);
cairo_translate(cairo, ms->area.x, ms->area.y);
cairo_set_source_u32(cairo, config->unselectable_bg_color);
cairo_rectangle(cairo, .5, .5, ms->area.w - 1, ms->area.h - 1);
cairo_set_line_width(cairo, 1);
cairo_stroke(cairo);
label_selection_t *curr_label = label_selection_new(
ms->label_symbols, ms->sub_area_columns * ms->sub_area_rows
);
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];
for (int i = 0; i < ms->sub_area_columns; i++) {
for (int j = 0; j < ms->sub_area_rows; j++) {
const int x =
i * ms->sub_area_width + min(i, ms->sub_area_width_off);
const int w =
ms->sub_area_width + (i < ms->sub_area_width_off ? 1 : 0);
const int y =
j * ms->sub_area_height + min(j, ms->sub_area_height_off);
const int h =
ms->sub_area_height + (j < ms->sub_area_height_off ? 1 : 0);
const bool selectable =
label_selection_is_included(curr_label, ms->label_selection);
cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
if (selectable) {
cairo_set_source_u32(cairo, config->selectable_bg_color);
cairo_rectangle(cairo, x, y, w, h);
cairo_fill(cairo);
cairo_set_source_u32(cairo, config->selectable_border_color);
cairo_rectangle(cairo, x + .5, y + .5, w - 1, h - 1);
cairo_set_line_width(cairo, 1);
cairo_stroke(cairo);
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);
// Centers the label.
cairo_move_to(
cairo,
x + (w - te_selected.x_advance - te_unselected.x_advance) /
2,
y + (int)((h + te_all.height) / 2)
);
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);
cairo_translate(cairo, -ms->area.x, -ms->area.y);
}
void tile_mode_state_free(void *mode_state) {
struct tile_mode_state *ms = mode_state;
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 tile_mode_interface = {
.name = "tile",
.enter = tile_mode_enter,
.reenter = tile_mode_reenter,
.key = tile_mode_key,
.render = tile_mode_render,
.free = tile_mode_state_free,
};
================================================
FILE: src/screencopy.c
================================================
#if OPENCV_ENABLED
#include "screencopy.h"
#include "log.h"
#include "state.h"
#include "surface_buffer.h"
#include "wlr-screencopy-unstable-v1-client-protocol.h"
#include
#include
#include
#include
#include
enum screen_capture_state {
CAPTURE_NOT_REQUESTED,
CAPTURE_REQUESTED,
CAPTURE_FAILED,
CAPTURE_SUCCESS,
};
struct scrcpy_state {
struct wl_shm *wl_shm;
struct zwlr_screencopy_frame_v1 *wl_screencopy_frame;
struct scrcpy_buffer *scrcpy_buffer;
enum screen_capture_state screen_capture_state;
};
static struct scrcpy_buffer *create_scrcpy_buffer(
struct wl_shm *shm, enum wl_shm_format format, uint32_t width,
uint32_t height, uint32_t stride
) {
size_t size = stride * height;
int fd = allocate_shm_file(size);
if (fd == -1) {
LOG_ERR("Could not allocate SHM file.");
return NULL;
}
void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) {
LOG_ERR("Could not mmap shared buffer for surface buffer.");
close(fd);
return NULL;
}
struct wl_shm_pool *wl_shm_pool = wl_shm_create_pool(shm, fd, size);
struct wl_buffer *wl_buffer = wl_shm_pool_create_buffer(
wl_shm_pool, 0, width, height, stride, format
);
wl_shm_pool_destroy(wl_shm_pool);
close(fd);
struct scrcpy_buffer *buffer = malloc(sizeof(*buffer));
buffer->wl_buffer = wl_buffer;
buffer->format = format;
buffer->data = data;
buffer->width = width;
buffer->height = height;
buffer->stride = stride;
return buffer;
}
void destroy_scrcpy_buffer(struct scrcpy_buffer *buf) {
if (buf != NULL) {
munmap(buf->data, buf->stride * buf->height);
wl_buffer_destroy(buf->wl_buffer);
free(buf);
}
}
static void screencopy_frame_handle_buffer(
void *data, struct zwlr_screencopy_frame_v1 *frame, uint32_t format,
uint32_t width, uint32_t height, uint32_t stride
) {
struct scrcpy_state *state = data;
LOG_DEBUG(
"Copying capture buffer (format: 0x%08x, %dx%d, stride: %d)", format,
width, height, stride
);
state->scrcpy_buffer =
create_scrcpy_buffer(state->wl_shm, format, width, height, stride);
zwlr_screencopy_frame_v1_copy(frame, state->scrcpy_buffer->wl_buffer);
}
static void screencopy_frame_handle_ready(
void *data, struct zwlr_screencopy_frame_v1 *frame, uint32_t tv_sec_hi,
uint32_t tv_sec_lo, uint32_t tv_nsec
) {
struct scrcpy_state *state = data;
state->screen_capture_state = CAPTURE_SUCCESS;
}
static void screencopy_frame_handle_failed(
void *data, struct zwlr_screencopy_frame_v1 *frame
) {
struct scrcpy_state *state = data;
state->screen_capture_state = CAPTURE_FAILED;
LOG_ERR("Could not capture screen.");
}
static void noop() {}
const struct zwlr_screencopy_frame_v1_listener screencopy_frame_listener = {
.buffer = screencopy_frame_handle_buffer,
.flags = noop,
.ready = screencopy_frame_handle_ready,
.failed = screencopy_frame_handle_failed,
.buffer_done = noop,
.damage = noop,
.linux_dmabuf = noop,
};
struct scrcpy_buffer *
query_screenshot(struct state *state, struct rect region) {
struct scrcpy_state scrcpy_state;
scrcpy_state.wl_shm = state->wl_shm;
if (state->wl_screencopy_manager == NULL) {
LOG_ERR("Could not load `zwlr_screencopy_manager_v1`.");
exit(1);
}
LOG_DEBUG(
"Capture region: %dx%d+%d+%d", region.w, region.h, region.x, region.y
);
scrcpy_state.wl_screencopy_frame =
zwlr_screencopy_manager_v1_capture_output_region(
state->wl_screencopy_manager, false,
state->current_output->wl_output, region.x, region.y, region.w,
region.h
);
zwlr_screencopy_frame_v1_add_listener(
scrcpy_state.wl_screencopy_frame, &screencopy_frame_listener,
&scrcpy_state
);
scrcpy_state.screen_capture_state = CAPTURE_REQUESTED;
while (scrcpy_state.screen_capture_state == CAPTURE_REQUESTED) {
wl_display_roundtrip(state->wl_display);
}
zwlr_screencopy_frame_v1_destroy(scrcpy_state.wl_screencopy_frame);
return scrcpy_state.scrcpy_buffer;
}
#endif
================================================
FILE: src/screencopy.h
================================================
#ifndef __SCREENCOPY_H_INCLUDED__
#define __SCREENCOPY_H_INCLUDED__
#if OPENCV_ENABLED
#include
struct scrcpy_buffer {
struct wl_buffer *wl_buffer;
void *data;
enum wl_shm_format format;
int32_t width;
int32_t height;
int32_t stride;
};
struct state;
struct rect;
struct scrcpy_buffer *query_screenshot(struct state *state, struct rect region);
void destroy_scrcpy_buffer(struct scrcpy_buffer *buf);
#endif
#endif
================================================
FILE: src/state.h
================================================
#ifndef __STATE_H_INCLUDED__
#define __STATE_H_INCLUDED__
#include "config.h"
#include "fractional-scale-v1-client-protocol.h"
#include "label.h"
#include "screencopy.h"
#include "surface_buffer.h"
#include "utils.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
#include
#include
#include
#include
#define NO_AREA_SELECTION -1
#define HOME_ROW_LEN 8
#define HOME_ROW_LEN_WITH_BTN 11
#define HOME_ROW_BUFFER_LEN 128
#define HOME_ROW_LEFT_CLICK 8
#define HOME_ROW_RIGHT_CLICK 9
#define HOME_ROW_MIDDLE_CLICK 10
// This should cover a initial maximum area with a width and height of 65536
// pixels.
#define BISECT_MAX_HISTORY 16
// Split history of up to a resolution of 65536x65536 assuming equal number of
// divisions each way.
#define SPLIT_MAX_HISTORY 32
#define MAX_NUM_MODES 3
#define NO_MODE_ENTERED -1
struct mode_interface;
struct tile_mode_state {
struct rect area;
int sub_area_rows;
int sub_area_width;
int sub_area_width_off;
int sub_area_columns;
int sub_area_height;
int sub_area_height_off;
label_selection_t *label_selection;
label_symbols_t *label_symbols;
cairo_font_face_t *label_font_face;
};
struct floating_mode_state {
struct rect *areas;
int num_areas;
label_selection_t *label_selection;
label_symbols_t *label_symbols;
cairo_font_face_t *label_font_face;
};
struct bisect_mode_state {
struct rect areas[BISECT_MAX_HISTORY];
int current;
cairo_font_face_t *label_font_face;
};
struct split_mode_state {
struct rect areas[SPLIT_MAX_HISTORY];
int current;
};
struct output {
struct wl_list link; // type: struct output
struct wl_output *wl_output;
struct zxdg_output_v1 *xdg_output;
char *name;
int32_t scale;
int32_t width;
int32_t height;
int32_t x;
int32_t y;
enum wl_output_transform transform;
};
struct seat {
struct wl_list link; // type: struct seat
struct wl_seat *wl_seat;
struct wl_keyboard *wl_keyboard;
struct xkb_context *xkb_context;
struct xkb_keymap *xkb_keymap;
struct xkb_state *xkb_state;
struct state *state;
};
struct state {
struct config config;
struct wl_display *wl_display;
struct wl_registry *wl_registry;
struct wl_compositor *wl_compositor;
struct wl_shm *wl_shm;
struct zwlr_layer_shell_v1 *wl_layer_shell;
struct zwlr_virtual_pointer_manager_v1 *wl_virtual_pointer_mgr;
struct wp_viewporter *wp_viewporter;
struct wp_viewport *wp_viewport;
struct wp_fractional_scale_manager_v1 *fractional_scale_mgr;
struct surface_buffer_pool surface_buffer_pool;
struct wl_surface *wl_surface;
struct wl_callback *wl_surface_callback;
struct zwlr_layer_surface_v1 *wl_layer_surface;
bool surface_configured;
#if OPENCV_ENABLED
struct zwlr_screencopy_manager_v1 *wl_screencopy_manager;
#endif
struct zxdg_output_manager_v1 *xdg_output_manager;
struct wl_list outputs;
struct wl_list seats;
struct output *current_output;
uint32_t surface_height;
uint32_t surface_width;
uint32_t fractional_scale; // scale / 120
bool running;
struct rect initial_area;
char home_row_buffer[HOME_ROW_BUFFER_LEN];
char **home_row;
struct rect result;
struct mode_interface *mode_interfaces[MAX_NUM_MODES];
void *mode_states[MAX_NUM_MODES];
int current_mode;
enum click click;
};
#endif
================================================
FILE: src/surface_buffer.c
================================================
#include "surface_buffer.h"
#include "log.h"
#include
#include
#include
#include
#include
#include
#include
#define CAIRO_SURFACE_FORMAT CAIRO_FORMAT_ARGB32
static int create_shm_file(void) {
char name[] = "/tmp/wl-shm-XXXXXX";
int fd = mkostemp(name, O_CLOEXEC);
if (fd < 0) {
return -1;
}
unlink(name);
return fd;
}
int allocate_shm_file(size_t size) {
int fd = create_shm_file();
if (fd < 0) {
return -1;
}
int err;
while ((err = ftruncate(fd, size)) && errno == EINTR) {}
if (err) {
close(fd);
return -1;
}
return fd;
}
static void handle_buffer_release(void *data, struct wl_buffer *wl_buffer) {
((struct surface_buffer *)data)->state = SURFACE_BUFFER_READY;
}
static const struct wl_buffer_listener wl_buffer_listener = {
.release = handle_buffer_release,
};
static struct surface_buffer *surface_buffer_init(
struct wl_shm *wl_shm, struct surface_buffer *buffer, int32_t width,
int32_t height
) {
const uint32_t stride =
cairo_format_stride_for_width(CAIRO_SURFACE_FORMAT, width);
const uint32_t data_size = height * stride;
void *data;
int fd = allocate_shm_file(data_size);
if (fd < 0) {
LOG_ERR("Could not allocate shared buffer for surface buffer.");
return NULL;
}
data = mmap(NULL, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) {
LOG_ERR("Could not mmap shared buffer for surface buffer.");
close(fd);
return NULL;
}
struct wl_shm_pool *wl_shm_pool = wl_shm_create_pool(wl_shm, fd, data_size);
buffer->wl_buffer = wl_shm_pool_create_buffer(
wl_shm_pool, 0, width, height, stride, WL_SHM_FORMAT_ARGB8888
);
wl_buffer_add_listener(buffer->wl_buffer, &wl_buffer_listener, buffer);
wl_shm_pool_destroy(wl_shm_pool);
close(fd);
buffer->data = data;
buffer->data_size = data_size;
buffer->width = width;
buffer->height = height;
buffer->state = SURFACE_BUFFER_READY;
buffer->cairo_surface = cairo_image_surface_create_for_data(
buffer->data, CAIRO_SURFACE_FORMAT, width, height, stride
);
buffer->cairo = cairo_create(buffer->cairo_surface);
return buffer;
}
static void surface_buffer_destroy(struct surface_buffer *buffer) {
if (buffer->state == SURFACE_BUFFER_UNINITIALIZED) {
return;
}
if (buffer->cairo) {
cairo_destroy(buffer->cairo);
}
if (buffer->cairo_surface) {
cairo_surface_destroy(buffer->cairo_surface);
}
if (buffer->wl_buffer) {
wl_buffer_destroy(buffer->wl_buffer);
}
if (buffer->data) {
munmap(buffer->data, buffer->data_size);
}
memset(buffer, 0, sizeof(struct surface_buffer));
}
void surface_buffer_pool_init(struct surface_buffer_pool *pool) {
memset(pool, 0, sizeof(struct surface_buffer_pool));
}
void surface_buffer_pool_destroy(struct surface_buffer_pool *pool) {
surface_buffer_destroy(&pool->buffers[0]);
surface_buffer_destroy(&pool->buffers[1]);
}
struct surface_buffer *get_next_buffer(
struct wl_shm *wl_shm, struct surface_buffer_pool *pool, uint32_t width,
uint32_t height
) {
struct surface_buffer *buffer = NULL;
for (size_t i = 0; i < 2; i++) {
if (pool->buffers[i].state != SURFACE_BUFFER_BUSY) {
buffer = &pool->buffers[i];
break;
}
}
if (buffer == NULL) {
LOG_WARN("All surface buffers are busy.");
return NULL;
}
if (buffer->width != width || buffer->height != height) {
surface_buffer_destroy(buffer);
}
if (buffer->state == SURFACE_BUFFER_UNINITIALIZED) {
if (surface_buffer_init(wl_shm, buffer, width, height) == NULL) {
LOG_ERR("Could not initialize next buffer.");
return NULL;
}
}
return buffer;
}
================================================
FILE: src/surface_buffer.h
================================================
#ifndef __SURFACE_BUFFER_H_INCLUDED__
#define __SURFACE_BUFFER_H_INCLUDED__
#include
#include
enum surface_buffer_state {
// This must be set to 0 as we set the whole structure to 0 when it's not
// initialized.
SURFACE_BUFFER_UNINITIALIZED = 0,
SURFACE_BUFFER_READY = 1,
SURFACE_BUFFER_BUSY = 2,
};
struct surface_buffer {
enum surface_buffer_state state;
struct wl_buffer *wl_buffer;
cairo_surface_t *cairo_surface;
cairo_t *cairo;
void *data;
size_t data_size;
uint32_t width;
uint32_t height;
};
struct surface_buffer_pool {
struct surface_buffer buffers[2];
};
void surface_buffer_pool_init(struct surface_buffer_pool *pool);
void surface_buffer_pool_destroy(struct surface_buffer_pool *pool);
struct surface_buffer *get_next_buffer(
struct wl_shm *wl_shm, struct surface_buffer_pool *pool, uint32_t width,
uint32_t height
);
int allocate_shm_file(size_t size);
#endif
================================================
FILE: src/target_detection.cpp
================================================
#include "target_detection.h"
#include "log.h"
#include
#include
#include
#include
#include
#include
static pixman_format_code_t get_pixman_format(enum wl_shm_format format) {
switch (format) {
case WL_SHM_FORMAT_RGB332:
return PIXMAN_r3g3b2;
case WL_SHM_FORMAT_BGR233:
return PIXMAN_b2g3r3;
case WL_SHM_FORMAT_ARGB4444:
return PIXMAN_a4r4g4b4;
case WL_SHM_FORMAT_XRGB4444:
return PIXMAN_x4r4g4b4;
case WL_SHM_FORMAT_ABGR4444:
return PIXMAN_a4b4g4r4;
case WL_SHM_FORMAT_XBGR4444:
return PIXMAN_x4b4g4r4;
case WL_SHM_FORMAT_ARGB1555:
return PIXMAN_a1r5g5b5;
case WL_SHM_FORMAT_XRGB1555:
return PIXMAN_x1r5g5b5;
case WL_SHM_FORMAT_ABGR1555:
return PIXMAN_a1b5g5r5;
case WL_SHM_FORMAT_XBGR1555:
return PIXMAN_x1b5g5r5;
case WL_SHM_FORMAT_RGB565:
return PIXMAN_r5g6b5;
case WL_SHM_FORMAT_BGR565:
return PIXMAN_b5g6r5;
case WL_SHM_FORMAT_RGB888:
return PIXMAN_r8g8b8;
case WL_SHM_FORMAT_BGR888:
return PIXMAN_b8g8r8;
case WL_SHM_FORMAT_ARGB8888:
return PIXMAN_a8r8g8b8;
case WL_SHM_FORMAT_XRGB8888:
return PIXMAN_x8r8g8b8;
case WL_SHM_FORMAT_ABGR8888:
return PIXMAN_a8b8g8r8;
case WL_SHM_FORMAT_XBGR8888:
return PIXMAN_x8b8g8r8;
case WL_SHM_FORMAT_BGRA8888:
return PIXMAN_b8g8r8a8;
case WL_SHM_FORMAT_BGRX8888:
return PIXMAN_b8g8r8x8;
case WL_SHM_FORMAT_RGBA8888:
return PIXMAN_r8g8b8a8;
case WL_SHM_FORMAT_RGBX8888:
return PIXMAN_r8g8b8x8;
case WL_SHM_FORMAT_ARGB2101010:
return PIXMAN_a2r10g10b10;
case WL_SHM_FORMAT_ABGR2101010:
return PIXMAN_a2b10g10r10;
case WL_SHM_FORMAT_XRGB2101010:
return PIXMAN_x2r10g10b10;
case WL_SHM_FORMAT_XBGR2101010:
return PIXMAN_x2b10g10r10;
default:
return (pixman_format_code_t)0;
}
}
static pixman_image_t *make_pixman_image_a8r8g8b8(
void *data, uint32_t width, uint32_t height, uint32_t stride,
enum wl_shm_format format
) {
pixman_format_code_t pixman_format = get_pixman_format(format);
if (pixman_format == 0) {
LOG_ERR("Unsupported format 0x%08x.", format);
return NULL;
}
LOG_DEBUG(
"Creating `pixman_image_t` for input image (w: %d, h: %d, stride: %d).",
width, height, stride
);
pixman_image_t *in_image = pixman_image_create_bits(
pixman_format, width, height, (uint32_t *)data, stride
);
if (in_image == NULL) {
LOG_ERR("Failed to create pixman image.");
return NULL;
}
int out_stride = width * sizeof(uint32_t);
LOG_DEBUG(
"Creating `pixman_image_t` for ouput image (w: %d, h: %d, stride: %d).",
width, height, out_stride
);
pixman_image_t *out_image = pixman_image_create_bits(
PIXMAN_a8r8g8b8, width, height, NULL, out_stride
);
if (out_image == NULL) {
LOG_ERR("Failed to create (out) pixman image.");
return NULL;
}
pixman_image_composite32(
PIXMAN_OP_SRC, in_image, NULL, out_image, 0, 0, 0, 0, 0, 0, width,
height
);
pixman_image_unref(in_image);
return out_image;
}
static cv::Mat get_gray_scale_from_buffer(
void *data, uint32_t height, uint32_t width, uint32_t stride,
enum wl_shm_format format
) {
pixman_image_t *image = NULL;
cv::Mat buf;
int in_out[3];
switch (format) {
case WL_SHM_FORMAT_ARGB8888:
case WL_SHM_FORMAT_XRGB8888:
buf = cv::Mat(height, width, CV_8UC4, data);
in_out[0] = 1;
in_out[1] = 1;
in_out[2] = 2;
break;
case WL_SHM_FORMAT_XBGR8888:
case WL_SHM_FORMAT_ABGR8888:
buf = cv::Mat(height, width, CV_8UC4, data);
in_out[0] = 2;
in_out[1] = 1;
in_out[2] = 0;
break;
default:
LOG_DEBUG("Converting buffer with Pixman");
image = make_pixman_image_a8r8g8b8(data, width, height, stride, format);
if (image == NULL) {
exit(1);
}
buf = cv::Mat(height, width, CV_8UC4, pixman_image_get_data(image));
in_out[0] = 1;
in_out[1] = 1;
in_out[2] = 2;
break;
}
cv::Mat in_channels[4];
cv::split(buf, in_channels);
cv::Mat out_channels[3] = {
in_channels[in_out[0]],
in_channels[in_out[1]],
in_channels[in_out[2]],
};
cv::Mat out;
cv::merge(out_channels, 3, out);
cv::Mat grayed;
cv::cvtColor(out, grayed, cv::COLOR_BGR2GRAY);
if (image != NULL) {
pixman_image_unref(image);
}
return grayed;
}
static void apply_transform(
cv::Mat &m, enum wl_output_transform transform, uint32_t &width,
uint32_t &height
) {
cv::Mat tmp;
bool switch_width_height = false;
switch (transform) {
case WL_OUTPUT_TRANSFORM_NORMAL:
break;
case WL_OUTPUT_TRANSFORM_90:
cv::rotate(m, tmp, cv::ROTATE_90_CLOCKWISE);
m = tmp;
switch_width_height = true;
break;
case WL_OUTPUT_TRANSFORM_270:
cv::rotate(m, tmp, cv::ROTATE_90_COUNTERCLOCKWISE);
m = tmp;
switch_width_height = true;
break;
case WL_OUTPUT_TRANSFORM_180:
cv::rotate(m, tmp, cv::ROTATE_180);
m = tmp;
break;
case WL_OUTPUT_TRANSFORM_FLIPPED:
cv::flip(m, tmp, 1);
m = tmp;
break;
case WL_OUTPUT_TRANSFORM_FLIPPED_90:
cv::rotate(m, tmp, cv::ROTATE_90_CLOCKWISE);
cv::flip(tmp, m, 1);
switch_width_height = true;
break;
case WL_OUTPUT_TRANSFORM_FLIPPED_180:
cv::rotate(m, tmp, cv::ROTATE_180);
cv::flip(tmp, m, 1);
break;
case WL_OUTPUT_TRANSFORM_FLIPPED_270:
cv::rotate(m, tmp, cv::ROTATE_90_COUNTERCLOCKWISE);
cv::flip(tmp, m, 1);
switch_width_height = true;
break;
}
if (switch_width_height) {
uint32_t tmp = height;
height = width;
width = tmp;
}
}
static void compute_rects(
const std::vector> &contours,
std::vector &rects, double scale, double x_off, double y_off
) {
rects.clear();
rects.reserve(contours.size());
for (const std::vector &contour : contours) {
cv::Rect rect = cv::boundingRect(contour);
rects.push_back(
cv::Rect2d(
rect.x / scale + x_off, rect.y / scale + y_off,
rect.width / scale, rect.height / scale
)
);
}
}
static size_t filter_rects(
const std::vector &rects,
const std::vector &hierachy, std::vector &filtered
) {
filtered.assign(rects.size(), false);
for (size_t i = 0; i < rects.size(); i++) {
const auto &rect = rects[i];
if (rect.height >= 50 || rect.width >= 500 || rect.height <= 3 ||
rect.width <= 7) {
filtered[i] = true;
continue;
}
}
std::vector to_explore;
for (size_t i = 0; i < rects.size(); i++) {
if (hierachy[i][3] >= 0) {
to_explore.push_back(i);
}
}
while (!to_explore.empty()) {
int i = to_explore.back();
to_explore.pop_back();
if (!filtered[i]) {
int parent_i = hierachy[i][3];
if (filtered[parent_i]) {
goto filtered;
}
const auto &rect = rects[i];
// Inner targets that are flat are most likely lines forming an
// icon, e.g. a hamburger menu.
if (rect.height <= 6) {
filtered[i] = true;
goto filtered;
}
const auto &parent_rect = rects[parent_i];
const double center_x = rect.x + rect.width / 2.;
const double center_y = rect.y + rect.height / 2.;
const double parent_center_x =
parent_rect.x + parent_rect.width / 2.;
const double parent_center_y =
parent_rect.y + parent_rect.height / 2.;
// There's not much reasons to keep inner targets that have the same
// center as this is where the user is going to click most likely.
if (abs(center_x - parent_center_x) < 8 &&
abs(center_y - parent_center_y) < 8) {
filtered[i] = true;
goto filtered;
}
// If the parent target is a square, it's most likely a button with
// a single option or an icon.
if (abs(parent_rect.height - parent_rect.width) < 5 &&
parent_rect.height < 40 && parent_rect.width < 40) {
filtered[i] = true;
goto filtered;
}
}
filtered:
int child = hierachy[i][0];
while (child >= 0) {
to_explore.push_back(child);
child = hierachy[child][2];
}
}
size_t not_filtered_count = 0;
for (const auto &curr : filtered) {
if (!curr) {
not_filtered_count += 1;
}
}
return not_filtered_count;
}
int compute_target_from_img_buffer(
void *data, uint32_t height, uint32_t width, uint32_t stride,
enum wl_shm_format format, enum wl_output_transform transform,
struct rect initial_area, struct rect **areas
) {
cv::Mat m1 =
get_gray_scale_from_buffer(data, height, width, stride, format);
apply_transform(m1, transform, width, height);
double scale = ((double)height) / ((double)initial_area.h);
cv::Mat m2;
cv::Mat kernel =
cv::Mat::ones(round(2.5 * scale), round(3.5 * scale), CV_8U);
cv::Canny(m1, m2, 70, 220);
cv::dilate(m2, m1, kernel);
std::vector> contours;
std::vector hierachy;
cv::findContours(
m1, contours, hierachy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE
);
std::vector rects;
std::vector filtered;
compute_rects(contours, rects, scale, initial_area.x, initial_area.y);
int final_rect_count = filter_rects(rects, hierachy, filtered);
size_t area_i = 0;
*areas = (struct rect *)malloc(sizeof(struct rect) * final_rect_count);
for (size_t i = 0; i < rects.size(); i++) {
if (filtered[i]) {
continue;
}
const auto rect = rects[i];
struct rect *area = &(*areas)[area_i];
area->x = round(rect.x);
area->y = round(rect.y);
area->w = round(rect.width);
area->h = round(rect.height);
area_i++;
}
return final_rect_count;
}
================================================
FILE: src/target_detection.h
================================================
#ifndef __TARGET_DETECTION_INCLUDED__
#define __TARGET_DETECTION_INCLUDED__
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
#if OPENCV_ENABLED
#include "utils.h"
#include
#include
EXTERNC int compute_target_from_img_buffer(
void *data, uint32_t height, uint32_t width, uint32_t stride,
enum wl_shm_format format, enum wl_output_transform transform,
struct rect initial_area, struct rect **areas
);
#endif
#undef EXTERNC
#endif
================================================
FILE: src/test_label.c
================================================
#include "log.h"
#include "src/label.h"
#include
int main() {
label_symbols_t *label_symbols = label_symbols_from_str("abcdé");
if (!label_symbols) {
LOG_ERR("`label_symbolss_from_str` should not have returned null.");
return 1;
}
if (label_symbols->num_symbols != 5) {
LOG_ERR("Expected 5 symbols, got %d.", label_symbols->num_symbols);
return 2;
}
char *s = label_symbols_idx_to_ptr(label_symbols, 0);
if (strcmp(s, "a")) {
LOG_ERR("No match");
LOG_ERR("Given string: '%s'", s);
return 3;
}
char *symbols[] = {
"a", "b", "c", "d", "é",
};
for (int i = 0; i < sizeof(symbols) / sizeof(symbols[0]); i++) {
int symbol_idx = label_symbols_find_idx(label_symbols, symbols[i]);
if (symbol_idx != i) {
LOG_ERR(
"Wrong index %d (expected %d) for symbol '%s'", symbol_idx, i,
symbols[i]
);
return 4;
}
}
label_selection_t *label_selection =
label_selection_new(label_symbols, 100);
int label_selection_str_buf_size =
label_selection_str_max_len(label_selection) + 1;
if (label_selection_str_buf_size != 7) {
LOG_ERR(
"Wrong label_selection_str_buffer_size = %d",
label_selection_str_buf_size
);
return 5;
}
char label_selection_str_buf[label_selection_str_buf_size];
int idx;
for (int i = 0; i < 100; i++) {
label_selection_set_from_idx(label_selection, i);
idx = label_selection_to_idx(label_selection);
if (idx != i) {
LOG_ERR("Wrong index %d, expected %d.", idx, i);
label_selection_str(label_selection, label_selection_str_buf);
LOG_ERR("Selection: '%s'", label_selection_str_buf);
return 6;
}
}
label_selection_clear(label_selection);
label_selection_append(label_selection, 4);
label_selection_append(label_selection, 2);
label_selection_str(label_selection, label_selection_str_buf);
if (strcmp(label_selection_str_buf, "éc")) {
LOG_ERR("Wrong selection string '%s'", label_selection_str_buf);
return 7;
}
label_selection_append(label_selection, 0);
if ((idx = label_selection_to_idx(label_selection)) != 14) {
LOG_ERR("Wrong index %d", idx);
return 8;
}
if (!label_selection_incr(label_selection)) {
LOG_ERR("We should not be overflowing here.");
return 9;
}
if ((idx = label_selection_to_idx(label_selection)) != 15) {
LOG_ERR("Wrong index %d", idx);
return 10;
}
char label_selection_str_buf_1[label_selection_str_buf_size];
label_selection_str_split(
label_selection, label_selection_str_buf, label_selection_str_buf_1, 1
);
if (strcmp(label_selection_str_buf, "a")) {
LOG_ERR("Wrong prefix '%s'", label_selection_str_buf);
return 11;
}
if (strcmp(label_selection_str_buf_1, "da")) {
LOG_ERR("Wrong suffix '%s'", label_selection_str_buf_1);
return 12;
}
// Tests with the unicode character not at end-of-string
label_symbols_t *alt_label_symbols = label_symbols_from_str("abcdéfghi");
label_selection_t *alt_selection =
label_selection_new(alt_label_symbols, 100);
int alt_selection_str_buf_size =
label_selection_str_max_len(alt_selection) + 1;
if (alt_selection_str_buf_size != 7) {
LOG_ERR(
"Wrong label_selection_str_buffer_size = %d",
alt_selection_str_buf_size
);
return 13;
}
char *alt_symbols[] = {
"a", "b", "c", "d", "é", "f", "g", "h", "i",
};
for (int i = 0; i < 9; i++) {
int symbol_idx =
label_symbols_find_idx(alt_label_symbols, alt_symbols[i]);
if (symbol_idx != i) {
LOG_ERR(
"Wrong index %d (expected %d) for symbol '%s'", symbol_idx, i,
symbols[i]
);
return 14;
}
}
label_selection_free(label_selection);
label_symbols_free(label_symbols);
return 0;
}
================================================
FILE: src/utils.c
================================================
#include
#include
int min(int a, int b) {
return a < b ? a : b;
}
int max(int a, int b) {
return a > b ? a : b;
}
int str_to_rune(char *str, uint32_t *rune) {
unsigned char *c = ((unsigned char *)str);
// `\0`, End of string byte.
if (*c == 0) {
*rune = 0;
return 0;
}
uint32_t value;
int size;
if ((*c & 0b10000000) == 0) {
value = *c & 0b01111111;
size = 1;
} else if ((*c & 0b11100000) == 0b11000000) {
value = *c & 0b00011111;
size = 2;
} else if ((*c & 0b11110000) == 0b11100000) {
value = *c & 0b00001111;
size = 3;
} else if ((*c & 0b11111000) == 0b11110000) {
value = *c & 0b00000111;
size = 4;
} else {
return -1;
}
for (int i = 1; i < size; i++) {
c++;
if ((*c & 0b11000000) != 0b10000000) {
return -1;
}
value <<= 6;
value += *c & 0b00111111;
}
*rune = value;
return size;
}
int find_str(char **strs, size_t len, char *to_find) {
int matched_i = -1;
for (int i = 0; i < len; i++) {
if (strcmp(to_find, strs[i]) == 0) {
matched_i = i;
break;
}
}
return matched_i;
}
================================================
FILE: src/utils.h
================================================
#ifndef __UTILS_H_INCLUDED__
#define __UTILS_H_INCLUDED__
#include
#include
struct rect {
int32_t x;
int32_t y;
int32_t w;
int32_t h;
};
enum click {
CLICK_NONE = 0,
CLICK_LEFT_BTN,
CLICK_RIGHT_BTN,
CLICK_MIDDLE_BTN,
};
int max(int a, int b);
int min(int a, int b);
int find_str(char **strs, size_t len, char *to_find);
// Extract first rune (32 bit UTF-8 code) in string.
// Return its encoded length in bytes or < 0 if invalid.
int str_to_rune(char *s, uint32_t *rune);
#endif
================================================
FILE: src/utils_cairo.c
================================================
#include "utils_cairo.h"
#include
void cairo_set_source_u32(void *cairo, uint32_t color) {
cairo_set_source_rgba(
(cairo_t *)cairo, (color >> 24 & 0xff) / 255.0,
(color >> 16 & 0xff) / 255.0, (color >> 8 & 0xff) / 255.0,
(color & 0xff) / 255.0
);
}
================================================
FILE: src/utils_cairo.h
================================================
#ifndef __CAIRO_UTILS_H_INCLUDED__
#define __CAIRO_UTILS_H_INCLUDED__
#include
void cairo_set_source_u32(void *cairo, uint32_t color);
#endif
================================================
FILE: src/utils_wayland.c
================================================
#include "utils_wayland.h"
#include "state.h"
#include "wlr-virtual-pointer-unstable-v1-client-protocol.h"
#include
static void _apply_transform(
uint32_t *x, uint32_t *y, uint32_t *width, uint32_t *height,
enum wl_output_transform transform
) {
uint32_t temp;
switch (transform) {
case WL_OUTPUT_TRANSFORM_NORMAL:
break;
case WL_OUTPUT_TRANSFORM_90:
temp = *x;
*x = *y;
*y = *width - temp;
temp = *width;
*width = *height;
*height = temp;
break;
case WL_OUTPUT_TRANSFORM_180:
*x = *width - *x;
*y = *height - *y;
break;
case WL_OUTPUT_TRANSFORM_270:
temp = *x;
*x = *height - *y;
*y = temp;
temp = *width;
*width = *height;
*height = temp;
break;
case WL_OUTPUT_TRANSFORM_FLIPPED:
*x = *width - *x;
break;
case WL_OUTPUT_TRANSFORM_FLIPPED_90:
*x = *width - *x;
_apply_transform(x, y, width, height, WL_OUTPUT_TRANSFORM_90);
break;
case WL_OUTPUT_TRANSFORM_FLIPPED_180:
*x = *width - *x;
_apply_transform(x, y, width, height, WL_OUTPUT_TRANSFORM_180);
break;
case WL_OUTPUT_TRANSFORM_FLIPPED_270:
*x = *width - *x;
_apply_transform(x, y, width, height, WL_OUTPUT_TRANSFORM_270);
break;
}
}
void move_pointer(
struct state *state, uint32_t x, uint32_t y, enum click click
) {
if (!state->wl_virtual_pointer_mgr) {
// We running in `--print-only` mode.
return;
}
wl_display_roundtrip(state->wl_display);
struct zwlr_virtual_pointer_v1 *virt_pointer =
zwlr_virtual_pointer_manager_v1_create_virtual_pointer_with_output(
state->wl_virtual_pointer_mgr,
((struct seat *)state->seats.next)->wl_seat,
state->current_output->wl_output
);
uint32_t output_width = state->current_output->width;
uint32_t output_height = state->current_output->height;
_apply_transform(
&x, &y, &output_width, &output_height, state->current_output->transform
);
zwlr_virtual_pointer_v1_motion_absolute(
virt_pointer, 0, x, y, output_width, output_height
);
zwlr_virtual_pointer_v1_frame(virt_pointer);
wl_display_roundtrip(state->wl_display);
if (state->click != CLICK_NONE) {
int btn = 271 + click;
zwlr_virtual_pointer_v1_button(
virt_pointer, 0, btn, WL_POINTER_BUTTON_STATE_PRESSED
);
zwlr_virtual_pointer_v1_frame(virt_pointer);
wl_display_roundtrip(state->wl_display);
zwlr_virtual_pointer_v1_button(
virt_pointer, 0, btn, WL_POINTER_BUTTON_STATE_RELEASED
);
zwlr_virtual_pointer_v1_frame(virt_pointer);
wl_display_roundtrip(state->wl_display);
}
zwlr_virtual_pointer_v1_destroy(virt_pointer);
}
================================================
FILE: src/utils_wayland.h
================================================
#ifndef __UTILS_WAYLAND_H_INCLUDED__
#define __UTILS_WAYLAND_H_INCLUDED__
#include "state.h"
void move_pointer(
struct state *state, uint32_t x, uint32_t y, enum click click
);
#endif