[
  {
    "path": ".clang-format",
    "content": "---\nLanguage:        Cpp\nAlignAfterOpenBracket: BlockIndent\nAlignArrayOfStructures: None\nAlignConsecutiveAssignments:\n  Enabled:         true\n  AcrossEmptyLines: false\n  AcrossComments:  true\n  AlignCompound:   true\n  PadOperators:    true\nAlignConsecutiveBitFields:\n  Enabled:         false\n  AcrossEmptyLines: false\n  AcrossComments:  false\n  AlignCompound:   false\n  PadOperators:    false\nAlignConsecutiveDeclarations:\n  Enabled:         true\n  AcrossEmptyLines: false\n  AcrossComments:  true\n  AlignCompound:   true\n  PadOperators:    true\nAlignConsecutiveMacros:\n  Enabled:         true\n  AcrossEmptyLines: false\n  AcrossComments:  true\n  AlignCompound:   true\n  PadOperators:    true\nAlignEscapedNewlines: Left\nAlignOperands:   Align\nAlignTrailingComments: true\nAllowAllArgumentsOnNextLine: false\nAllowAllParametersOfDeclarationOnNextLine: true\nAllowShortEnumsOnASingleLine: true\nAllowShortBlocksOnASingleLine: Empty\nAllowShortCaseLabelsOnASingleLine: false\nAllowShortFunctionsOnASingleLine: Empty\nAllowShortLambdasOnASingleLine: All\nAllowShortIfStatementsOnASingleLine: WithoutElse\nAllowShortLoopsOnASingleLine: false\nAlwaysBreakAfterDefinitionReturnType: None\nAlwaysBreakAfterReturnType: None\nAlwaysBreakBeforeMultilineStrings: false\nAttributeMacros:\n  - __capability\nBinPackArguments: true\nBinPackParameters: true\nBraceWrapping:\n  AfterCaseLabel:  false\n  AfterClass:      false\n  AfterControlStatement: Never\n  AfterEnum:       false\n  AfterFunction:   false\n  AfterNamespace:  false\n  AfterObjCDeclaration: false\n  AfterStruct:     true\n  AfterUnion:      false\n  AfterExternBlock: false\n  BeforeCatch:     false\n  BeforeElse:      false\n  BeforeLambdaBody: false\n  BeforeWhile:     false\n  IndentBraces:    false\n  SplitEmptyFunction: true\n  SplitEmptyRecord: true\n  SplitEmptyNamespace: true\nBreakBeforeBinaryOperators: None\nBreakBeforeConceptDeclarations: Always\nBreakBeforeBraces: Attach\nBreakBeforeInheritanceComma: false\nBreakInheritanceList: BeforeColon\nBreakBeforeTernaryOperators: true\nBreakConstructorInitializersBeforeComma: false\nBreakConstructorInitializers: BeforeColon\nBreakAfterJavaFieldAnnotations: false\nBreakStringLiterals: true\nColumnLimit:     80\nCommentPragmas:  '^ IWYU pragma:'\nQualifierAlignment: Leave\nCompactNamespaces: false\nConstructorInitializerIndentWidth: 4\nContinuationIndentWidth: 4\nCpp11BracedListStyle: true\nDeriveLineEnding: true\nDerivePointerAlignment: false\nDisableFormat:   false\nEmptyLineAfterAccessModifier: Never\nEmptyLineBeforeAccessModifier: LogicalBlock\nExperimentalAutoDetectBinPacking: false\nPackConstructorInitializers: BinPack\nBasedOnStyle:    ''\nConstructorInitializerAllOnOneLineOrOnePerLine: false\nAllowAllConstructorInitializersOnNextLine: true\nFixNamespaceComments: true\nForEachMacros:\n  - foreach\n  - wl_list_for_each\n  - wl_list_for_each_safe\nIncludeBlocks:   Regroup\nIncludeCategories:\n  - Regex:           '^\"(llvm|llvm-c|clang|clang-c)/'\n    Priority:        2\n    SortPriority:    0\n    CaseSensitive:   false\n  - Regex:           '^(<|\"(gtest|gmock|isl|json)/)'\n    Priority:        3\n    SortPriority:    0\n    CaseSensitive:   false\n  - Regex:           '.*'\n    Priority:        1\n    SortPriority:    0\n    CaseSensitive:   false\nIncludeIsMainRegex: '(Test)?$'\nIncludeIsMainSourceRegex: ''\nIndentAccessModifiers: false\nIndentCaseLabels: false\nIndentCaseBlocks: false\nIndentGotoLabels: true\nIndentPPDirectives: None\nIndentExternBlock: AfterExternBlock\nIndentRequiresClause: true\nIndentWidth:     4\nIndentWrappedFunctionNames: false\nInsertBraces:    true\nInsertTrailingCommas: None\nJavaScriptQuotes: Leave\nJavaScriptWrapImports: true\nKeepEmptyLinesAtTheStartOfBlocks: true\nLambdaBodyIndentation: Signature\nMacroBlockBegin: ''\nMacroBlockEnd:   ''\nMaxEmptyLinesToKeep: 1\nNamespaceIndentation: None\nObjCBinPackProtocolList: Auto\nObjCBlockIndentWidth: 2\nObjCBreakBeforeNestedBlockParam: true\nObjCSpaceAfterProperty: false\nObjCSpaceBeforeProtocolList: true\nPenaltyBreakAssignment: 2\nPenaltyBreakBeforeFirstCallParameter: 19\nPenaltyBreakComment: 300\nPenaltyBreakFirstLessLess: 120\nPenaltyBreakOpenParenthesis: 0\nPenaltyBreakString: 1000\nPenaltyBreakTemplateDeclaration: 10\nPenaltyExcessCharacter: 1000000\nPenaltyReturnTypeOnItsOwnLine: 60\nPenaltyIndentedWhitespace: 0\nPointerAlignment: Right\nPPIndentWidth:   -1\nReferenceAlignment: Pointer\nReflowComments:  true\nRemoveBracesLLVM: false\nRequiresClausePosition: OwnLine\nSeparateDefinitionBlocks: Leave\nShortNamespaceLines: 1\nSortIncludes:    CaseSensitive\nSortJavaStaticImport: Before\nSortUsingDeclarations: true\nSpaceAfterCStyleCast: false\nSpaceAfterLogicalNot: false\nSpaceAfterTemplateKeyword: true\nSpaceBeforeAssignmentOperators: true\nSpaceBeforeCaseColon: false\nSpaceBeforeCpp11BracedList: false\nSpaceBeforeCtorInitializerColon: true\nSpaceBeforeInheritanceColon: true\nSpaceBeforeParens: ControlStatements\nSpaceBeforeParensOptions:\n  AfterControlStatements: true\n  AfterForeachMacros: true\n  AfterFunctionDefinitionName: false\n  AfterFunctionDeclarationName: false\n  AfterIfMacros:   true\n  AfterOverloadedOperator: false\n  AfterRequiresInClause: false\n  AfterRequiresInExpression: false\n  BeforeNonEmptyParentheses: false\nSpaceAroundPointerQualifiers: Default\nSpaceBeforeRangeBasedForLoopColon: true\nSpaceInEmptyBlock: false\nSpaceInEmptyParentheses: false\nSpacesBeforeTrailingComments: 1\nSpacesInAngles:  Never\nSpacesInConditionalStatement: false\nSpacesInContainerLiterals: true\nSpacesInCStyleCastParentheses: false\nSpacesInLineCommentPrefix:\n  Minimum:         1\n  Maximum:         -1\nSpacesInParentheses: false\nSpacesInSquareBrackets: false\nSpaceBeforeSquareBrackets: false\nBitFieldColonSpacing: Both\nStandard:        Latest\nStatementAttributeLikeMacros:\n  - Q_EMIT\nStatementMacros:\n  - Q_UNUSED\n  - QT_REQUIRE_VERSION\nTabWidth:        8\nUseCRLF:         false\nUseTab:          Never\nWhitespaceSensitiveMacros:\n  - STRINGIZE\n  - PP_STRINGIZE\n  - BOOST_PP_STRINGIZE\n  - NS_SWIFT_NAME\n  - CF_SWIFT_NAME\n...\n\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\nFirst describe the bug.\n\nYou should be able to answer the following questions:\n - How to reproduce the bug?\n - What is going wrong?\n - What is the expected behaviour?\n\nIt is helpful to provide screenshots and screencasts.\n\nThen give the following information:\n\n- **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.\n- **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.\n- **Distribution** used. Whilst it might not always be relevant, distributions can package the program differently or apply patches.\n- You **display settings** (optional). Sometimes some bug only happen with some display settings. You can get this information with `wlr-randr` on `wlroots` compositors.\n\nIf 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.\n"
  },
  {
    "path": ".gitignore",
    "content": ".cache\n*.gch\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# wl-kbptr\n\n`wl-kbptr` &mdash; short for Wayland Keyboard Pointer &mdash; is a utility to help move the mouse pointer with the keyboard.\n\nSee [Supported compositors](#supported-compositors) section for compatibility.\n\n## Modes\n\nTo enable to select a target and click, it has four different modes:\n- [`floating`](#floating-mode) &mdash; which uses arbitrary areas either given by the user or detected,\n- [`tile`](#tile-mode) &mdash; which uses a grid to select areas,\n- [`bisect`](#bisect-mode) &mdash; which enables to bisect an area,\n- [`split`](#split-mode) &mdash; which enables to successively split an area,\n- and [`click`](#click-mode) &mdash; which triggers a click in the middle of an area.\n\nThese are set with the `modes` configuration field and can be chained, e.g. `wl-kbptr -o modes=tile,bisect`.\n\nNote that if you make a mistake &mdash; e.g. select the wrong area &mdash; you can always go back on step by pressing the `Backspace` key. This even works between modes.\n\n### Floating mode\n[Floating Mode Demo](https://github.com/user-attachments/assets/1598128b-e03b-4d06-b47a-bc8a0021f4da)\n\nThe `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.\n\n#### Auto-detection\nThe 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`.\n\nThis requires the `wl-kbptr` binary to be built with the `opencv` feature and the compositor to support the [`wlr-screencopy-unstable-v1`](https://wayland.app/protocols/wlr-screencopy-unstable-v1) protocol &mdash; see the [supported compositors](#supported-compositors) section and [build instructions](#from-sources) for details. Whilst it doesn't noticeably change the size of the program itself, OpenCV is a 100 MB+ dependency which is not ideal if you want a very small system which is why this is an optional feature.\n\nMost distributions will package the program with the option enabled. If not, they will usually provide two packages. You can check if the binary you have has been built with it with `wl-kbptr --version` &mdash; it should print `opencv` if supported.\n\n### Tile mode\n[Tile Mode Demo](https://github.com/user-attachments/assets/d8c9c8dc-2733-4835-9d82-d0f5b093c382)\n\nThe `tile` mode displays a grid. To select an area, simply type the label associated with the tile you want to select.\n\n### Bisect mode\n[Bisect Mode Demo](https://github.com/user-attachments/assets/8f8f7fb4-1bb9-4180-9eda-78ee1ff14181)\n\nThe `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`.\n\nA 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.\n\n### Split mode\n[Split Mode Demo](https://github.com/user-attachments/assets/760fa154-ce50-47b4-8f9a-26c5ac79a55b)\n\nThe `split` mode enables to successively split an area with the arrow keys.\n\nJust 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.\n\n### Click mode\n\nThe `click` mode simply triggers a click in the middle of the selection area.\n\n## Supported compositors\n\nFor `wl-kbptr` to work, it requires the following protocols:\n - [`wlr-layer-shell-unstable-v1`](https://wayland.app/protocols/wlr-layer-shell-unstable-v1) for the program to display on top,\n - [`wlr-virtual-pointer-unstable-v1`](https://wayland.app/protocols/wlr-virtual-pointer-unstable-v1) to control the mouse pointer,\n - 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.\n\nHere are the compositors with which it has been tested:\n\n| Compositor |     | Notes |\n| ---------- | --- | ----- |\n| [Sway](https://swaywm.org) | ✅ | - |\n| [Hyprland](https://hyprland.org) | ✅ | - |\n| [niri](https://github.com/YaLTeR/niri) | ✅ | - |\n| [dwl](https://codeberg.org/dwl/dwl) | ✅ | - |\n| [labwc](https://labwc.github.io) | ✅ | - |\n| [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). |\n| [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. |\n| [Mutter](https://mutter.gnome.org) | ❌ | The compositor doesn't support any of the required protocols. |\n\n## Installation\n\n### Arch Linux\n\nIf you are using Arch Linux, you can install the [`wl-kbptr` AUR package](https://aur.archlinux.org/packages/wl-kbptr).\n\nRecommended way to build and install the package directly from the AUR (gets all required files):\n```bash\ngit clone https://aur.archlinux.org/wl-kbptr.git\ncd wl-kbptr\nmakepkg -si\n```\n\nAlternatively, if you only want the `PKGBUILD`:\n```bash\ncurl -L 'https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=wl-kbptr' -o PKGBUILD\nmakepkg -si\n```\n\n### NixOS\n\nIf 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.\n\n### Chimera Linux\n\nIf 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).\n\n```bash\napk add chimera-repo-contrib\napk add wl-kbptr\n```\n### Fedora\n\nAs 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.\n\n```bash\nsudo dnf install -y \\\n    meson \\\n    wayland-protocols-devel \\\n    gcc \\\n    libwayland-client  \\\n    cmake \\\n    wayland-devel \\\n    libxkbcommon-devel \\\n    cairo-devel\n```\n\n### From sources\n\nYou can build from sources with:\n\n```bash\nmeson setup build --buildtype=release\nmeson compile -C build\n```\n\nIf you want to build the target detection feature (see [floating mode](#floating-mode)), you need to enable the `opencv` feature:\n\n```bash\nmeson setup build --buildtype=release -Dopencv=enabled\nmeson compile -C build\n```\n\nThen install with:\n\n```bash\nmeson install -C build\n```\n\n## Setting the bindings\n\n### Sway\n\n```\nmode Mouse {\n    bindsym a mode default, exec 'wl-kbptr-sway-active-win; swaymsg mode Mouse'\n    bindsym Shift+a mode default, exec 'wl-kbptr; swaymsg mode Mouse'\n\n    # Mouse move\n    bindsym h seat seat0 cursor move -15 0\n    bindsym j seat seat0 cursor move 0 15\n    bindsym k seat seat0 cursor move 0 -15\n    bindsym l seat seat0 cursor move 15 0\n\n    # Left button\n    bindsym s seat seat0 cursor press button1\n    bindsym --release s seat seat0 cursor release button1\n\n    # Middle button\n    bindsym d seat seat0 cursor press button2\n    bindsym --release d seat seat0 cursor release button2\n\n    # Right button\n    bindsym f seat seat0 cursor press button3\n    bindsym --release f seat seat0 cursor release button3\n\n    bindsym Escape mode default\n}\n\nbindsym $mod+g exec wl-kbptr-sway-active-win -o modes=floating','click -o mode_floating.source=detect\nbindsym $mod+Shift+g mode Mouse\n```\n\n### Hyprland\n\n```\n# Cursor submap (similar to the Mouse mode in Sway)\nsubmap=cursor\n\n# Jump cursor to a position\nbind=,a,exec,hyprctl dispatch submap reset && wl-kbptr && hyprctl dispatch submap cursor\n\n# Cursor movement\nbinde=,j,exec,wlrctl pointer move 0 10\nbinde=,k,exec,wlrctl pointer move 0 -10\nbinde=,l,exec,wlrctl pointer move 10 0\nbinde=,h,exec,wlrctl pointer move -10 0\n\n# Left button\nbind=,s,exec,wlrctl pointer click left\n# Middle button\nbind=,d,exec,wlrctl pointer click middle\n# Right button\nbind=,f,exec,wlrctl pointer click right\n\n# Scroll up and down\nbinde=,e,exec,wlrctl pointer scroll 10 0\nbinde=,r,exec,wlrctl pointer scroll -10 0\n\n# Scroll left and right\nbinde=,t,exec,wlrctl pointer scroll 0 -10\nbinde=,g,exec,wlrctl pointer scroll 0 10\n\n# Exit cursor submap\n# If you do not use cursor timeout or cursor:hide_on_key_press, you can delete its respective calls.\nbind=,escape,exec,hyprctl keyword cursor:inactive_timeout 3; hyprctl keyword cursor:hide_on_key_press true; hyprctl dispatch submap reset \n\nsubmap = reset\n\n# Entrypoint\n# If you do not use cursor timeout or cursor:hide_on_key_press, you can delete its respective calls.\nbind=$mainMod,g,exec,hyprctl keyword cursor:inactive_timeout 0; hyprctl keyword cursor:hide_on_key_press false; hyprctl dispatch submap cursor\n```\n\n## Configuration\n\n`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.\n\n## Dependencies\n\n- [`xkbcommon`](https://xkbcommon.org)\n- [`cairo`](https://cairographics.org)\n- [`wayland`](https://wayland.freedesktop.org)\n- [`wayland-protocols`](https://gitlab.freedesktop.org/wayland/wayland-protocols)\n- With the `opencv` feature enabled:\n  - C++ compiler\n  - [`OpenCV`](https://opencv.org)\n  - [`Pixman`](https://www.pixman.org)\n\n\n## License\n\n[GPL-3.0](./LICENSE)\n"
  },
  {
    "path": "config.example",
    "content": "# wl-kbptr can be configured with a configuration file.\n# The file location can be passed with the -c parameter.\n# Othewise the `$XDG_CONFIG_HOME/wl-kbptr/config` file will\n# be loaded if it exits. Below is the default configuration.\n\n[general]\nhome_row_keys=\nmodes=tile,bisect\ncancellation_status_code=0\n\n[mode_tile]\nlabel_color=#fffd\nlabel_select_color=#fd0d\nunselectable_bg_color=#2226\nselectable_bg_color=#0304\nselectable_border_color=#040c\nlabel_font_family=sans-serif\nlabel_font_size=8 50% 100\nlabel_symbols=abcdefghijklmnopqrstuvwxyz\n\n[mode_floating]\nsource=stdin\nlabel_color=#fffd\nlabel_select_color=#fd0d\nunselectable_bg_color=#2226\nselectable_bg_color=#1718\nselectable_border_color=#040c\nlabel_font_family=sans-serif\nlabel_font_size=12 50% 100\nlabel_symbols=abcdefghijklmnopqrstuvwxyz\n\n[mode_bisect]\nlabel_color=#fffd\nlabel_font_size=20\nlabel_font_family=sans-serif\nlabel_padding=12\npointer_size=20\npointer_color=#e22d\nunselectable_bg_color=#2226\neven_area_bg_color=#0304\neven_area_border_color=#0408\nodd_area_bg_color=#0034\nodd_area_border_color=#0048\nhistory_border_color=#3339\n\n[mode_split]\npointer_size=20\npointer_color=#e22d\nbg_color=#2226\narea_bg_color=#11111188\nvertical_color=#8888ffcc\nhorizontal_color=#008800cc\nhistory_border_color=#3339\n\n[mode_click]\nbutton=left\n"
  },
  {
    "path": "helpers/wl-kbptr-sway-active-win",
    "content": "#!/bin/sh\n\nactive_area=$(swaymsg -t get_tree | jq --raw-output \\\n\t'.. | (.nodes? + .floating_nodes? // empty)[] | select (.focused) | .rect | \"\\(.width)x\\(.height)+\\(.x)+\\(.y)\"')\nwl-kbptr --restrict \"$active_area\" $@\n"
  },
  {
    "path": "meson.build",
    "content": "project(\n  'wl-kbptr',\n  'c',\n  meson_version: '>=1.1',\n  default_options: ['c_std=c11'],\n  license: 'GPL-3.0',\n  version: '0.4.1',\n)\n\nuse_opencv = get_option('opencv').enabled()\nversion_suffix = ''\n\nif get_option('buildtype') == 'debug'\n  add_project_arguments('-DDEBUG', language: ['c', 'cpp'])\n  version_suffix = '-debug'\nendif\n\nadd_project_arguments(\n  '-D_GNU_SOURCE=200809L',\n  '-DVERSION=\"@0@@1@\"'.format(meson.project_version(), version_suffix),\n  language: 'c',\n)\n\ncc = meson.get_compiler('c')\n\nif use_opencv\n  add_project_arguments('-DOPENCV_ENABLED=1', language: ['c', 'cpp'])\n  add_languages('cpp', native: false)\n  opencv = dependency('opencv4')\n  pixman = dependency('pixman-1')\nendif\n\nwayland_client = dependency('wayland-client')\nwayland_protos = dependency('wayland-protocols')\nxkbcommon = dependency('xkbcommon')\ncairo = dependency('cairo')\nmath = cc.find_library('m')\n\nsubdir('protocol')\n\ndependencies = [\n  wayland_client,\n  xkbcommon,\n  cairo,\n  math,\n]\n\nsources = [\n  'src/main.c',\n  'src/surface_buffer.c',\n  'src/mode.c',\n  'src/mode_tile.c',\n  'src/mode_floating.c',\n  'src/mode_bisect.c',\n  'src/mode_split.c',\n  'src/mode_click.c',\n  'src/utils.c',\n  'src/utils_cairo.c',\n  'src/utils_wayland.c',\n  'src/config.c',\n  'src/label.c',\n  protos_src,\n]\n\nif use_opencv\n  sources += [\n    'src/screencopy.c',\n    'src/target_detection.cpp',\n  ]\n  dependencies += [opencv, pixman]\nendif\n\nexecutable(\n  'wl-kbptr',\n  sources,\n  dependencies: dependencies,\n  install: true,\n)\n\nlabel_test_exec = executable(\n  'test_label',\n  [\n    'src/test_label.c',\n    'src/label.c',\n    'src/utils.c',\n  ],\n)\n\ntest('test_label', label_test_exec)\n\ninstall_data(\n  'share/wl-kbptr.desktop',\n  rename: 'wl-kbptr.desktop',\n  install_dir: 'share/applications',\n)\n"
  },
  {
    "path": "meson.options",
    "content": "option('opencv', type: 'feature', value: 'disabled')\n"
  },
  {
    "path": "protocol/fractional-scale-v1.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<protocol name=\"fractional_scale_v1\">\n  <copyright>\n    Copyright © 2022 Kenny Levinsen\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice (including the next\n    paragraph) shall be included in all copies or substantial portions of the\n    Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n  </copyright>\n\n  <description summary=\"Protocol for requesting fractional surface scales\">\n    This protocol allows a compositor to suggest for surfaces to render at\n    fractional scales.\n\n    A client can submit scaled content by utilizing wp_viewport. This is done by\n    creating a wp_viewport object for the surface and setting the destination\n    rectangle to the surface size before the scale factor is applied.\n\n    The buffer size is calculated by multiplying the surface size by the\n    intended scale.\n\n    The wl_surface buffer scale should remain set to 1.\n\n    If a surface has a surface-local size of 100 px by 50 px and wishes to\n    submit buffers with a scale of 1.5, then a buffer of 150px by 75 px should\n    be used and the wp_viewport destination rectangle should be 100 px by 50 px.\n\n    For toplevel surfaces, the size is rounded halfway away from zero. The\n    rounding algorithm for subsurface position and size is not defined.\n  </description>\n\n  <interface name=\"wp_fractional_scale_manager_v1\" version=\"1\">\n    <description summary=\"fractional surface scale information\">\n      A global interface for requesting surfaces to use fractional scales.\n    </description>\n\n    <request name=\"destroy\" type=\"destructor\">\n      <description summary=\"unbind the fractional surface scale interface\">\n        Informs the server that the client will not be using this protocol\n        object anymore. This does not affect any other objects,\n        wp_fractional_scale_v1 objects included.\n      </description>\n    </request>\n\n    <enum name=\"error\">\n      <entry name=\"fractional_scale_exists\" value=\"0\"\n        summary=\"the surface already has a fractional_scale object associated\"/>\n    </enum>\n\n    <request name=\"get_fractional_scale\">\n      <description summary=\"extend surface interface for scale information\">\n        Create an add-on object for the the wl_surface to let the compositor\n        request fractional scales. If the given wl_surface already has a\n        wp_fractional_scale_v1 object associated, the fractional_scale_exists\n        protocol error is raised.\n      </description>\n      <arg name=\"id\" type=\"new_id\" interface=\"wp_fractional_scale_v1\"\n           summary=\"the new surface scale info interface id\"/>\n      <arg name=\"surface\" type=\"object\" interface=\"wl_surface\"\n           summary=\"the surface\"/>\n    </request>\n  </interface>\n\n  <interface name=\"wp_fractional_scale_v1\" version=\"1\">\n    <description summary=\"fractional scale interface to a wl_surface\">\n      An additional interface to a wl_surface object which allows the compositor\n      to inform the client of the preferred scale.\n    </description>\n\n    <request name=\"destroy\" type=\"destructor\">\n      <description summary=\"remove surface scale information for surface\">\n        Destroy the fractional scale object. When this object is destroyed,\n        preferred_scale events will no longer be sent.\n      </description>\n    </request>\n\n    <event name=\"preferred_scale\">\n      <description summary=\"notify of new preferred scale\">\n        Notification of a new preferred scale for this surface that the\n        compositor suggests that the client should use.\n\n        The sent scale is the numerator of a fraction with a denominator of 120.\n      </description>\n      <arg name=\"scale\" type=\"uint\" summary=\"the new preferred scale\"/>\n    </event>\n  </interface>\n</protocol>\n"
  },
  {
    "path": "protocol/meson.build",
    "content": "wayland_scanner_dep = dependency('wayland-scanner', native: true)\nwayland_scanner = find_program(\n  wayland_scanner_dep.get_variable('wayland_scanner'), native: true,\n)\n\nwl_protocol_dir = wayland_protos.get_variable('pkgdatadir')\n\nwayland_scanner_code = generator(\n  wayland_scanner, output: '@BASENAME@-protocol.c',\n  arguments: ['private-code', '@INPUT@', '@OUTPUT@'],\n)\n\nwayland_scanner_header = generator(\n  wayland_scanner, output: '@BASENAME@-client-protocol.h',\n  arguments: ['client-header', '@INPUT@', '@OUTPUT@'],\n)\n\nclient_protocols = [\n  wl_protocol_dir / 'stable/xdg-shell/xdg-shell.xml',\n  wl_protocol_dir / 'unstable/xdg-output/xdg-output-unstable-v1.xml',\n  wl_protocol_dir / 'stable/viewporter/viewporter.xml',\n  'wlr-layer-shell-unstable-v1.xml',\n  'wlr-virtual-pointer-unstable-v1.xml',\n  'wlr-screencopy-unstable-v1.xml',\n  'fractional-scale-v1.xml',\n]\n\nprotos_src = []\nforeach xml : client_protocols\n\tprotos_src += wayland_scanner_code.process(xml)\n\tprotos_src += wayland_scanner_header.process(xml)\nendforeach\n"
  },
  {
    "path": "protocol/wlr-layer-shell-unstable-v1.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<protocol name=\"wlr_layer_shell_unstable_v1\">\n  <copyright>\n    Copyright © 2017 Drew DeVault\n\n    Permission to use, copy, modify, distribute, and sell this\n    software and its documentation for any purpose is hereby granted\n    without fee, provided that the above copyright notice appear in\n    all copies and that both that copyright notice and this permission\n    notice appear in supporting documentation, and that the name of\n    the copyright holders not be used in advertising or publicity\n    pertaining to distribution of the software without specific,\n    written prior permission.  The copyright holders make no\n    representations about the suitability of this software for any\n    purpose.  It is provided \"as is\" without express or implied\n    warranty.\n\n    THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS\n    SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n    FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY\n    SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN\n    AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,\n    ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF\n    THIS SOFTWARE.\n  </copyright>\n\n  <interface name=\"zwlr_layer_shell_v1\" version=\"4\">\n    <description summary=\"create surfaces that are layers of the desktop\">\n      Clients can use this interface to assign the surface_layer role to\n      wl_surfaces. Such surfaces are assigned to a \"layer\" of the output and\n      rendered with a defined z-depth respective to each other. They may also be\n      anchored to the edges and corners of a screen and specify input handling\n      semantics. This interface should be suitable for the implementation of\n      many desktop shell components, and a broad number of other applications\n      that interact with the desktop.\n    </description>\n\n    <request name=\"get_layer_surface\">\n      <description summary=\"create a layer_surface from a surface\">\n        Create a layer surface for an existing surface. This assigns the role of\n        layer_surface, or raises a protocol error if another role is already\n        assigned.\n\n        Creating a layer surface from a wl_surface which has a buffer attached\n        or committed is a client error, and any attempts by a client to attach\n        or manipulate a buffer prior to the first layer_surface.configure call\n        must also be treated as errors.\n\n        After creating a layer_surface object and setting it up, the client\n        must perform an initial commit without any buffer attached.\n        The compositor will reply with a layer_surface.configure event.\n        The client must acknowledge it and is then allowed to attach a buffer\n        to map the surface.\n\n        You may pass NULL for output to allow the compositor to decide which\n        output to use. Generally this will be the one that the user most\n        recently interacted with.\n\n        Clients can specify a namespace that defines the purpose of the layer\n        surface.\n      </description>\n      <arg name=\"id\" type=\"new_id\" interface=\"zwlr_layer_surface_v1\"/>\n      <arg name=\"surface\" type=\"object\" interface=\"wl_surface\"/>\n      <arg name=\"output\" type=\"object\" interface=\"wl_output\" allow-null=\"true\"/>\n      <arg name=\"layer\" type=\"uint\" enum=\"layer\" summary=\"layer to add this surface to\"/>\n      <arg name=\"namespace\" type=\"string\" summary=\"namespace for the layer surface\"/>\n    </request>\n\n    <enum name=\"error\">\n      <entry name=\"role\" value=\"0\" summary=\"wl_surface has another role\"/>\n      <entry name=\"invalid_layer\" value=\"1\" summary=\"layer value is invalid\"/>\n      <entry name=\"already_constructed\" value=\"2\" summary=\"wl_surface has a buffer attached or committed\"/>\n    </enum>\n\n    <enum name=\"layer\">\n      <description summary=\"available layers for surfaces\">\n        These values indicate which layers a surface can be rendered in. They\n        are ordered by z depth, bottom-most first. Traditional shell surfaces\n        will typically be rendered between the bottom and top layers.\n        Fullscreen shell surfaces are typically rendered at the top layer.\n        Multiple surfaces can share a single layer, and ordering within a\n        single layer is undefined.\n      </description>\n\n      <entry name=\"background\" value=\"0\"/>\n      <entry name=\"bottom\" value=\"1\"/>\n      <entry name=\"top\" value=\"2\"/>\n      <entry name=\"overlay\" value=\"3\"/>\n    </enum>\n\n    <!-- Version 3 additions -->\n\n    <request name=\"destroy\" type=\"destructor\" since=\"3\">\n      <description summary=\"destroy the layer_shell object\">\n        This request indicates that the client will not use the layer_shell\n        object any more. Objects that have been created through this instance\n        are not affected.\n      </description>\n    </request>\n  </interface>\n\n  <interface name=\"zwlr_layer_surface_v1\" version=\"4\">\n    <description summary=\"layer metadata interface\">\n      An interface that may be implemented by a wl_surface, for surfaces that\n      are designed to be rendered as a layer of a stacked desktop-like\n      environment.\n\n      Layer surface state (layer, size, anchor, exclusive zone,\n      margin, interactivity) is double-buffered, and will be applied at the\n      time wl_surface.commit of the corresponding wl_surface is called.\n\n      Attaching a null buffer to a layer surface unmaps it.\n\n      Unmapping a layer_surface means that the surface cannot be shown by the\n      compositor until it is explicitly mapped again. The layer_surface\n      returns to the state it had right after layer_shell.get_layer_surface.\n      The client can re-map the surface by performing a commit without any\n      buffer attached, waiting for a configure event and handling it as usual.\n    </description>\n\n    <request name=\"set_size\">\n      <description summary=\"sets the size of the surface\">\n        Sets the size of the surface in surface-local coordinates. The\n        compositor will display the surface centered with respect to its\n        anchors.\n\n        If you pass 0 for either value, the compositor will assign it and\n        inform you of the assignment in the configure event. You must set your\n        anchor to opposite edges in the dimensions you omit; not doing so is a\n        protocol error. Both values are 0 by default.\n\n        Size is double-buffered, see wl_surface.commit.\n      </description>\n      <arg name=\"width\" type=\"uint\"/>\n      <arg name=\"height\" type=\"uint\"/>\n    </request>\n\n    <request name=\"set_anchor\">\n      <description summary=\"configures the anchor point of the surface\">\n        Requests that the compositor anchor the surface to the specified edges\n        and corners. If two orthogonal edges are specified (e.g. 'top' and\n        'left'), then the anchor point will be the intersection of the edges\n        (e.g. the top left corner of the output); otherwise the anchor point\n        will be centered on that edge, or in the center if none is specified.\n\n        Anchor is double-buffered, see wl_surface.commit.\n      </description>\n      <arg name=\"anchor\" type=\"uint\" enum=\"anchor\"/>\n    </request>\n\n    <request name=\"set_exclusive_zone\">\n      <description summary=\"configures the exclusive geometry of this surface\">\n        Requests that the compositor avoids occluding an area with other\n        surfaces. The compositor's use of this information is\n        implementation-dependent - do not assume that this region will not\n        actually be occluded.\n\n        A positive value is only meaningful if the surface is anchored to one\n        edge or an edge and both perpendicular edges. If the surface is not\n        anchored, anchored to only two perpendicular edges (a corner), anchored\n        to only two parallel edges or anchored to all edges, a positive value\n        will be treated the same as zero.\n\n        A positive zone is the distance from the edge in surface-local\n        coordinates to consider exclusive.\n\n        Surfaces that do not wish to have an exclusive zone may instead specify\n        how they should interact with surfaces that do. If set to zero, the\n        surface indicates that it would like to be moved to avoid occluding\n        surfaces with a positive exclusive zone. If set to -1, the surface\n        indicates that it would not like to be moved to accommodate for other\n        surfaces, and the compositor should extend it all the way to the edges\n        it is anchored to.\n\n        For example, a panel might set its exclusive zone to 10, so that\n        maximized shell surfaces are not shown on top of it. A notification\n        might set its exclusive zone to 0, so that it is moved to avoid\n        occluding the panel, but shell surfaces are shown underneath it. A\n        wallpaper or lock screen might set their exclusive zone to -1, so that\n        they stretch below or over the panel.\n\n        The default value is 0.\n\n        Exclusive zone is double-buffered, see wl_surface.commit.\n      </description>\n      <arg name=\"zone\" type=\"int\"/>\n    </request>\n\n    <request name=\"set_margin\">\n      <description summary=\"sets a margin from the anchor point\">\n        Requests that the surface be placed some distance away from the anchor\n        point on the output, in surface-local coordinates. Setting this value\n        for edges you are not anchored to has no effect.\n\n        The exclusive zone includes the margin.\n\n        Margin is double-buffered, see wl_surface.commit.\n      </description>\n      <arg name=\"top\" type=\"int\"/>\n      <arg name=\"right\" type=\"int\"/>\n      <arg name=\"bottom\" type=\"int\"/>\n      <arg name=\"left\" type=\"int\"/>\n    </request>\n\n    <enum name=\"keyboard_interactivity\">\n      <description summary=\"types of keyboard interaction possible for a layer shell surface\">\n        Types of keyboard interaction possible for layer shell surfaces. The\n        rationale for this is twofold: (1) some applications are not interested\n        in keyboard events and not allowing them to be focused can improve the\n        desktop experience; (2) some applications will want to take exclusive\n        keyboard focus.\n      </description>\n\n      <entry name=\"none\" value=\"0\">\n        <description summary=\"no keyboard focus is possible\">\n          This value indicates that this surface is not interested in keyboard\n          events and the compositor should never assign it the keyboard focus.\n\n          This is the default value, set for newly created layer shell surfaces.\n\n          This is useful for e.g. desktop widgets that display information or\n          only have interaction with non-keyboard input devices.\n        </description>\n      </entry>\n      <entry name=\"exclusive\" value=\"1\">\n        <description summary=\"request exclusive keyboard focus\">\n          Request exclusive keyboard focus if this surface is above the shell surface layer.\n\n          For the top and overlay layers, the seat will always give\n          exclusive keyboard focus to the top-most layer which has keyboard\n          interactivity set to exclusive. If this layer contains multiple\n          surfaces with keyboard interactivity set to exclusive, the compositor\n          determines the one receiving keyboard events in an implementation-\n          defined manner. In this case, no guarantee is made when this surface\n          will receive keyboard focus (if ever).\n\n          For the bottom and background layers, the compositor is allowed to use\n          normal focus semantics.\n\n          This setting is mainly intended for applications that need to ensure\n          they receive all keyboard events, such as a lock screen or a password\n          prompt.\n        </description>\n      </entry>\n      <entry name=\"on_demand\" value=\"2\" since=\"4\">\n        <description summary=\"request regular keyboard focus semantics\">\n          This requests the compositor to allow this surface to be focused and\n          unfocused by the user in an implementation-defined manner. The user\n          should be able to unfocus this surface even regardless of the layer\n          it is on.\n\n          Typically, the compositor will want to use its normal mechanism to\n          manage keyboard focus between layer shell surfaces with this setting\n          and regular toplevels on the desktop layer (e.g. click to focus).\n          Nevertheless, it is possible for a compositor to require a special\n          interaction to focus or unfocus layer shell surfaces (e.g. requiring\n          a click even if focus follows the mouse normally, or providing a\n          keybinding to switch focus between layers).\n\n          This setting is mainly intended for desktop shell components (e.g.\n          panels) that allow keyboard interaction. Using this option can allow\n          implementing a desktop shell that can be fully usable without the\n          mouse.\n        </description>\n      </entry>\n    </enum>\n\n    <request name=\"set_keyboard_interactivity\">\n      <description summary=\"requests keyboard events\">\n        Set how keyboard events are delivered to this surface. By default,\n        layer shell surfaces do not receive keyboard events; this request can\n        be used to change this.\n\n        This setting is inherited by child surfaces set by the get_popup\n        request.\n\n        Layer surfaces receive pointer, touch, and tablet events normally. If\n        you do not want to receive them, set the input region on your surface\n        to an empty region.\n\n        Keyboard interactivity is double-buffered, see wl_surface.commit.\n      </description>\n      <arg name=\"keyboard_interactivity\" type=\"uint\" enum=\"keyboard_interactivity\"/>\n    </request>\n\n    <request name=\"get_popup\">\n      <description summary=\"assign this layer_surface as an xdg_popup parent\">\n        This assigns an xdg_popup's parent to this layer_surface.  This popup\n        should have been created via xdg_surface::get_popup with the parent set\n        to NULL, and this request must be invoked before committing the popup's\n        initial state.\n\n        See the documentation of xdg_popup for more details about what an\n        xdg_popup is and how it is used.\n      </description>\n      <arg name=\"popup\" type=\"object\" interface=\"xdg_popup\"/>\n    </request>\n\n    <request name=\"ack_configure\">\n      <description summary=\"ack a configure event\">\n        When a configure event is received, if a client commits the\n        surface in response to the configure event, then the client\n        must make an ack_configure request sometime before the commit\n        request, passing along the serial of the configure event.\n\n        If the client receives multiple configure events before it\n        can respond to one, it only has to ack the last configure event.\n\n        A client is not required to commit immediately after sending\n        an ack_configure request - it may even ack_configure several times\n        before its next surface commit.\n\n        A client may send multiple ack_configure requests before committing, but\n        only the last request sent before a commit indicates which configure\n        event the client really is responding to.\n      </description>\n      <arg name=\"serial\" type=\"uint\" summary=\"the serial from the configure event\"/>\n    </request>\n\n    <request name=\"destroy\" type=\"destructor\">\n      <description summary=\"destroy the layer_surface\">\n        This request destroys the layer surface.\n      </description>\n    </request>\n\n    <event name=\"configure\">\n      <description summary=\"suggest a surface change\">\n        The configure event asks the client to resize its surface.\n\n        Clients should arrange their surface for the new states, and then send\n        an ack_configure request with the serial sent in this configure event at\n        some point before committing the new surface.\n\n        The client is free to dismiss all but the last configure event it\n        received.\n\n        The width and height arguments specify the size of the window in\n        surface-local coordinates.\n\n        The size is a hint, in the sense that the client is free to ignore it if\n        it doesn't resize, pick a smaller size (to satisfy aspect ratio or\n        resize in steps of NxM pixels). If the client picks a smaller size and\n        is anchored to two opposite anchors (e.g. 'top' and 'bottom'), the\n        surface will be centered on this axis.\n\n        If the width or height arguments are zero, it means the client should\n        decide its own window dimension.\n      </description>\n      <arg name=\"serial\" type=\"uint\"/>\n      <arg name=\"width\" type=\"uint\"/>\n      <arg name=\"height\" type=\"uint\"/>\n    </event>\n\n    <event name=\"closed\">\n      <description summary=\"surface should be closed\">\n        The closed event is sent by the compositor when the surface will no\n        longer be shown. The output may have been destroyed or the user may\n        have asked for it to be removed. Further changes to the surface will be\n        ignored. The client should destroy the resource after receiving this\n        event, and create a new surface if they so choose.\n      </description>\n    </event>\n\n    <enum name=\"error\">\n      <entry name=\"invalid_surface_state\" value=\"0\" summary=\"provided surface state is invalid\"/>\n      <entry name=\"invalid_size\" value=\"1\" summary=\"size is invalid\"/>\n      <entry name=\"invalid_anchor\" value=\"2\" summary=\"anchor bitfield is invalid\"/>\n      <entry name=\"invalid_keyboard_interactivity\" value=\"3\" summary=\"keyboard interactivity is invalid\"/>\n    </enum>\n\n    <enum name=\"anchor\" bitfield=\"true\">\n      <entry name=\"top\" value=\"1\" summary=\"the top edge of the anchor rectangle\"/>\n      <entry name=\"bottom\" value=\"2\" summary=\"the bottom edge of the anchor rectangle\"/>\n      <entry name=\"left\" value=\"4\" summary=\"the left edge of the anchor rectangle\"/>\n      <entry name=\"right\" value=\"8\" summary=\"the right edge of the anchor rectangle\"/>\n    </enum>\n\n    <!-- Version 2 additions -->\n\n    <request name=\"set_layer\" since=\"2\">\n      <description summary=\"change the layer of the surface\">\n        Change the layer that the surface is rendered on.\n\n        Layer is double-buffered, see wl_surface.commit.\n      </description>\n      <arg name=\"layer\" type=\"uint\" enum=\"zwlr_layer_shell_v1.layer\" summary=\"layer to move this surface to\"/>\n    </request>\n  </interface>\n</protocol>\n"
  },
  {
    "path": "protocol/wlr-screencopy-unstable-v1.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<protocol name=\"wlr_screencopy_unstable_v1\">\n  <copyright>\n    Copyright © 2018 Simon Ser\n    Copyright © 2019 Andri Yngvason\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice (including the next\n    paragraph) shall be included in all copies or substantial portions of the\n    Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n  </copyright>\n\n  <description summary=\"screen content capturing on client buffers\">\n    This protocol allows clients to ask the compositor to copy part of the\n    screen content to a client buffer.\n\n    Warning! The protocol described in this file is experimental and\n    backward incompatible changes may be made. Backward compatible changes\n    may be added together with the corresponding interface version bump.\n    Backward incompatible changes are done by bumping the version number in\n    the protocol and interface names and resetting the interface version.\n    Once the protocol is to be declared stable, the 'z' prefix and the\n    version number in the protocol and interface names are removed and the\n    interface version number is reset.\n  </description>\n\n  <interface name=\"zwlr_screencopy_manager_v1\" version=\"3\">\n    <description summary=\"manager to inform clients and begin capturing\">\n      This object is a manager which offers requests to start capturing from a\n      source.\n    </description>\n\n    <request name=\"capture_output\">\n      <description summary=\"capture an output\">\n        Capture the next frame of an entire output.\n      </description>\n      <arg name=\"frame\" type=\"new_id\" interface=\"zwlr_screencopy_frame_v1\"/>\n      <arg name=\"overlay_cursor\" type=\"int\"\n        summary=\"composite cursor onto the frame\"/>\n      <arg name=\"output\" type=\"object\" interface=\"wl_output\"/>\n    </request>\n\n    <request name=\"capture_output_region\">\n      <description summary=\"capture an output's region\">\n        Capture the next frame of an output's region.\n\n        The region is given in output logical coordinates, see\n        xdg_output.logical_size. The region will be clipped to the output's\n        extents.\n      </description>\n      <arg name=\"frame\" type=\"new_id\" interface=\"zwlr_screencopy_frame_v1\"/>\n      <arg name=\"overlay_cursor\" type=\"int\"\n        summary=\"composite cursor onto the frame\"/>\n      <arg name=\"output\" type=\"object\" interface=\"wl_output\"/>\n      <arg name=\"x\" type=\"int\"/>\n      <arg name=\"y\" type=\"int\"/>\n      <arg name=\"width\" type=\"int\"/>\n      <arg name=\"height\" type=\"int\"/>\n    </request>\n\n    <request name=\"destroy\" type=\"destructor\">\n      <description summary=\"destroy the manager\">\n        All objects created by the manager will still remain valid, until their\n        appropriate destroy request has been called.\n      </description>\n    </request>\n  </interface>\n\n  <interface name=\"zwlr_screencopy_frame_v1\" version=\"3\">\n    <description summary=\"a frame ready for copy\">\n      This object represents a single frame.\n\n      When created, a series of buffer events will be sent, each representing a\n      supported buffer type. The \"buffer_done\" event is sent afterwards to\n      indicate that all supported buffer types have been enumerated. The client\n      will then be able to send a \"copy\" request. If the capture is successful,\n      the compositor will send a \"flags\" followed by a \"ready\" event.\n\n      For objects version 2 or lower, wl_shm buffers are always supported, ie.\n      the \"buffer\" event is guaranteed to be sent.\n\n      If the capture failed, the \"failed\" event is sent. This can happen anytime\n      before the \"ready\" event.\n\n      Once either a \"ready\" or a \"failed\" event is received, the client should\n      destroy the frame.\n    </description>\n\n    <event name=\"buffer\">\n      <description summary=\"wl_shm buffer information\">\n        Provides information about wl_shm buffer parameters that need to be\n        used for this frame. This event is sent once after the frame is created\n        if wl_shm buffers are supported.\n      </description>\n      <arg name=\"format\" type=\"uint\" enum=\"wl_shm.format\" summary=\"buffer format\"/>\n      <arg name=\"width\" type=\"uint\" summary=\"buffer width\"/>\n      <arg name=\"height\" type=\"uint\" summary=\"buffer height\"/>\n      <arg name=\"stride\" type=\"uint\" summary=\"buffer stride\"/>\n    </event>\n\n    <request name=\"copy\">\n      <description summary=\"copy the frame\">\n        Copy the frame to the supplied buffer. The buffer must have a the\n        correct size, see zwlr_screencopy_frame_v1.buffer and\n        zwlr_screencopy_frame_v1.linux_dmabuf. The buffer needs to have a\n        supported format.\n\n        If the frame is successfully copied, a \"flags\" and a \"ready\" events are\n        sent. Otherwise, a \"failed\" event is sent.\n      </description>\n      <arg name=\"buffer\" type=\"object\" interface=\"wl_buffer\"/>\n    </request>\n\n    <enum name=\"error\">\n      <entry name=\"already_used\" value=\"0\"\n        summary=\"the object has already been used to copy a wl_buffer\"/>\n      <entry name=\"invalid_buffer\" value=\"1\"\n        summary=\"buffer attributes are invalid\"/>\n    </enum>\n\n    <enum name=\"flags\" bitfield=\"true\">\n      <entry name=\"y_invert\" value=\"1\" summary=\"contents are y-inverted\"/>\n    </enum>\n\n    <event name=\"flags\">\n      <description summary=\"frame flags\">\n        Provides flags about the frame. This event is sent once before the\n        \"ready\" event.\n      </description>\n      <arg name=\"flags\" type=\"uint\" enum=\"flags\" summary=\"frame flags\"/>\n    </event>\n\n    <event name=\"ready\">\n      <description summary=\"indicates frame is available for reading\">\n        Called as soon as the frame is copied, indicating it is available\n        for reading. This event includes the time at which presentation happened\n        at.\n\n        The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples,\n        each component being an unsigned 32-bit value. Whole seconds are in\n        tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo,\n        and the additional fractional part in tv_nsec as nanoseconds. Hence,\n        for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part\n        may have an arbitrary offset at start.\n\n        After receiving this event, the client should destroy the object.\n      </description>\n      <arg name=\"tv_sec_hi\" type=\"uint\"\n           summary=\"high 32 bits of the seconds part of the timestamp\"/>\n      <arg name=\"tv_sec_lo\" type=\"uint\"\n           summary=\"low 32 bits of the seconds part of the timestamp\"/>\n      <arg name=\"tv_nsec\" type=\"uint\"\n           summary=\"nanoseconds part of the timestamp\"/>\n    </event>\n\n    <event name=\"failed\">\n      <description summary=\"frame copy failed\">\n        This event indicates that the attempted frame copy has failed.\n\n        After receiving this event, the client should destroy the object.\n      </description>\n    </event>\n\n    <request name=\"destroy\" type=\"destructor\">\n      <description summary=\"delete this object, used or not\">\n        Destroys the frame. This request can be sent at any time by the client.\n      </description>\n    </request>\n\n    <!-- Version 2 additions -->\n    <request name=\"copy_with_damage\" since=\"2\">\n      <description summary=\"copy the frame when it's damaged\">\n        Same as copy, except it waits until there is damage to copy.\n      </description>\n      <arg name=\"buffer\" type=\"object\" interface=\"wl_buffer\"/>\n    </request>\n\n    <event name=\"damage\" since=\"2\">\n      <description summary=\"carries the coordinates of the damaged region\">\n        This event is sent right before the ready event when copy_with_damage is\n        requested. It may be generated multiple times for each copy_with_damage\n        request.\n\n        The arguments describe a box around an area that has changed since the\n        last copy request that was derived from the current screencopy manager\n        instance.\n\n        The union of all regions received between the call to copy_with_damage\n        and a ready event is the total damage since the prior ready event.\n      </description>\n      <arg name=\"x\" type=\"uint\" summary=\"damaged x coordinates\"/>\n      <arg name=\"y\" type=\"uint\" summary=\"damaged y coordinates\"/>\n      <arg name=\"width\" type=\"uint\" summary=\"current width\"/>\n      <arg name=\"height\" type=\"uint\" summary=\"current height\"/>\n    </event>\n\n    <!-- Version 3 additions -->\n    <event name=\"linux_dmabuf\" since=\"3\">\n      <description summary=\"linux-dmabuf buffer information\">\n        Provides information about linux-dmabuf buffer parameters that need to\n        be used for this frame. This event is sent once after the frame is\n        created if linux-dmabuf buffers are supported.\n      </description>\n      <arg name=\"format\" type=\"uint\" summary=\"fourcc pixel format\"/>\n      <arg name=\"width\" type=\"uint\" summary=\"buffer width\"/>\n      <arg name=\"height\" type=\"uint\" summary=\"buffer height\"/>\n    </event>\n\n    <event name=\"buffer_done\" since=\"3\">\n      <description summary=\"all buffer types reported\">\n        This event is sent once after all buffer events have been sent.\n\n        The client should proceed to create a buffer of one of the supported\n        types, and send a \"copy\" request.\n      </description>\n    </event>\n  </interface>\n</protocol>\n"
  },
  {
    "path": "protocol/wlr-virtual-pointer-unstable-v1.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<protocol name=\"wlr_virtual_pointer_unstable_v1\">\n  <copyright>\n    Copyright © 2019 Josef Gajdusek\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice (including the next\n    paragraph) shall be included in all copies or substantial portions of the\n    Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n  </copyright>\n\n  <interface name=\"zwlr_virtual_pointer_v1\" version=\"2\">\n    <description summary=\"virtual pointer\">\n      This protocol allows clients to emulate a physical pointer device. The\n      requests are mostly mirror opposites of those specified in wl_pointer.\n    </description>\n\n    <enum name=\"error\">\n      <entry name=\"invalid_axis\" value=\"0\"\n        summary=\"client sent invalid axis enumeration value\" />\n      <entry name=\"invalid_axis_source\" value=\"1\"\n        summary=\"client sent invalid axis source enumeration value\" />\n    </enum>\n\n    <request name=\"motion\">\n      <description summary=\"pointer relative motion event\">\n        The pointer has moved by a relative amount to the previous request.\n\n        Values are in the global compositor space.\n      </description>\n      <arg name=\"time\" type=\"uint\" summary=\"timestamp with millisecond granularity\"/>\n      <arg name=\"dx\" type=\"fixed\" summary=\"displacement on the x-axis\"/>\n      <arg name=\"dy\" type=\"fixed\" summary=\"displacement on the y-axis\"/>\n    </request>\n\n    <request name=\"motion_absolute\">\n      <description summary=\"pointer absolute motion event\">\n        The pointer has moved in an absolute coordinate frame.\n\n        Value of x can range from 0 to x_extent, value of y can range from 0\n        to y_extent.\n      </description>\n      <arg name=\"time\" type=\"uint\" summary=\"timestamp with millisecond granularity\"/>\n      <arg name=\"x\" type=\"uint\" summary=\"position on the x-axis\"/>\n      <arg name=\"y\" type=\"uint\" summary=\"position on the y-axis\"/>\n      <arg name=\"x_extent\" type=\"uint\" summary=\"extent of the x-axis\"/>\n      <arg name=\"y_extent\" type=\"uint\" summary=\"extent of the y-axis\"/>\n    </request>\n\n    <request name=\"button\">\n      <description summary=\"button event\">\n        A button was pressed or released.\n      </description>\n      <arg name=\"time\" type=\"uint\" summary=\"timestamp with millisecond granularity\"/>\n      <arg name=\"button\" type=\"uint\" summary=\"button that produced the event\"/>\n      <arg name=\"state\" type=\"uint\" enum=\"wl_pointer.button_state\" summary=\"physical state of the button\"/>\n    </request>\n\n    <request name=\"axis\">\n      <description summary=\"axis event\">\n        Scroll and other axis requests.\n      </description>\n      <arg name=\"time\" type=\"uint\" summary=\"timestamp with millisecond granularity\"/>\n      <arg name=\"axis\" type=\"uint\" enum=\"wl_pointer.axis\" summary=\"axis type\"/>\n      <arg name=\"value\" type=\"fixed\" summary=\"length of vector in touchpad coordinates\"/>\n    </request>\n\n    <request name=\"frame\">\n      <description summary=\"end of a pointer event sequence\">\n        Indicates the set of events that logically belong together.\n      </description>\n    </request>\n\n    <request name=\"axis_source\">\n      <description summary=\"axis source event\">\n        Source information for scroll and other axis.\n      </description>\n      <arg name=\"axis_source\" type=\"uint\" enum=\"wl_pointer.axis_source\" summary=\"source of the axis event\"/>\n    </request>\n\n    <request name=\"axis_stop\">\n      <description summary=\"axis stop event\">\n        Stop notification for scroll and other axes.\n      </description>\n      <arg name=\"time\" type=\"uint\" summary=\"timestamp with millisecond granularity\"/>\n      <arg name=\"axis\" type=\"uint\" enum=\"wl_pointer.axis\" summary=\"the axis stopped with this event\"/>\n    </request>\n\n    <request name=\"axis_discrete\">\n      <description summary=\"axis click event\">\n        Discrete step information for scroll and other axes.\n\n        This event allows the client to extend data normally sent using the axis\n        event with discrete value.\n      </description>\n      <arg name=\"time\" type=\"uint\" summary=\"timestamp with millisecond granularity\"/>\n      <arg name=\"axis\" type=\"uint\" enum=\"wl_pointer.axis\" summary=\"axis type\"/>\n      <arg name=\"value\" type=\"fixed\" summary=\"length of vector in touchpad coordinates\"/>\n      <arg name=\"discrete\" type=\"int\" summary=\"number of steps\"/>\n    </request>\n\n    <request name=\"destroy\" type=\"destructor\" since=\"1\">\n      <description summary=\"destroy the virtual pointer object\"/>\n    </request>\n  </interface>\n\n  <interface name=\"zwlr_virtual_pointer_manager_v1\" version=\"2\">\n    <description summary=\"virtual pointer manager\">\n      This object allows clients to create individual virtual pointer objects.\n    </description>\n\n    <request name=\"create_virtual_pointer\">\n      <description summary=\"Create a new virtual pointer\">\n        Creates a new virtual pointer. The optional seat is a suggestion to the\n        compositor.\n      </description>\n      <arg name=\"seat\" type=\"object\" interface=\"wl_seat\" allow-null=\"true\"/>\n      <arg name=\"id\" type=\"new_id\" interface=\"zwlr_virtual_pointer_v1\"/>\n    </request>\n\n    <request name=\"destroy\" type=\"destructor\" since=\"1\">\n      <description summary=\"destroy the virtual pointer manager\"/>\n    </request>\n\n    <!-- Version 2 additions -->\n    <request name=\"create_virtual_pointer_with_output\" since=\"2\">\n      <description summary=\"Create a new virtual pointer\">\n        Creates a new virtual pointer. The seat and the output arguments are\n        optional. If the seat argument is set, the compositor should assign the\n        input device to the requested seat. If the output argument is set, the\n        compositor should map the input device to the requested output.\n      </description>\n      <arg name=\"seat\" type=\"object\" interface=\"wl_seat\" allow-null=\"true\"/>\n      <arg name=\"output\" type=\"object\" interface=\"wl_output\" allow-null=\"true\"/>\n      <arg name=\"id\" type=\"new_id\" interface=\"zwlr_virtual_pointer_v1\"/>\n    </request>\n  </interface>\n</protocol>\n"
  },
  {
    "path": "share/wl-kbptr.desktop",
    "content": "[Desktop Entry]\nVersion=1.0\nName=wl-kbptr\nComment=Control the mouse pointer with the keyboard\nExec=wl-kbptr\nTerminal=false\nType=Application\n"
  },
  {
    "path": "src/config.c",
    "content": "#include \"config.h\"\n\n#include \"log.h\"\n#include \"state.h\"\n\n#include <errno.h>\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n/**\n * `field_color_parse` parses color field values, e.g.:\n *  - 6-digit hex color code (RRGGBB): `#123456`, `123456`\n *  - 8-digit hex color code (RRGGBBAA): `#12345678`, `12345678`\n *  - 3-digit hex color code (RGB): `#123`, `123`\n *  - 4-digit hex color code (RGBA): `#1234`, `1234`\n */\nstatic int parse_color(void *dest, char *value) {\n    if (value[0] == '#') {\n        value++;\n    }\n\n    char digits[8];\n    int  len = 0;\n    for (int i = 0; value[i] != '\\0'; i++) {\n        if (++len > 8) {\n            return 1;\n        }\n\n        char c = value[i];\n        if (c >= '0' && c <= '9') {\n            digits[i] = c - '0';\n            continue;\n        }\n\n        c |= 1 << 5; // Makes the character lower case.\n        if (c >= 'a' && c <= 'f') {\n            digits[i] = c - 'a' + 10;\n            continue;\n        }\n\n        return 2;\n    }\n\n    switch (len) {\n    case 8:;\n        *((uint32_t *)dest) = digits[7] | digits[6] << 4 |\n                              digits[5] << (4 * 2) | digits[4] << (4 * 3) |\n                              digits[3] << (4 * 4) | digits[2] << (4 * 5) |\n                              digits[1] << (4 * 6) | digits[0] << (4 * 7);\n        break;\n\n    case 6:\n        *((uint32_t *)dest) = 0xff | digits[5] << (4 * 2) |\n                              digits[4] << (4 * 3) | digits[3] << (4 * 4) |\n                              digits[2] << (4 * 5) | digits[1] << (4 * 6) |\n                              digits[0] << (4 * 7);\n        break;\n\n    case 4:\n        *((uint32_t *)dest) = digits[3] | digits[3] << 4 |\n                              digits[2] << (4 * 2) | digits[2] << (4 * 3) |\n                              digits[1] << (4 * 4) | digits[1] << (4 * 5) |\n                              digits[0] << (4 * 6) | digits[0] << (4 * 7);\n        break;\n\n    case 3:\n        *((uint32_t *)dest) = 0xff | digits[2] << (4 * 2) |\n                              digits[2] << (4 * 3) | digits[1] << (4 * 4) |\n                              digits[1] << (4 * 5) | digits[0] << (4 * 6) |\n                              digits[0] << (4 * 7);\n        break;\n\n    default:\n        return 4;\n    }\n\n    return 0;\n}\n\nstatic int parse_double(void *dest, char *value) {\n    *((double *)dest) = atof(value);\n    // TODO: handle errors better.\n    return 0;\n}\n\nstatic int parse_uint8(void *dest, char *value) {\n    int decoded = atoi(value);\n    if (decoded < 0 || decoded >= 256) {\n        LOG_ERR(\"Value should be between 0 and 255 (included).\");\n        return 1;\n    }\n\n    *((uint8_t *)dest) = (uint8_t)decoded;\n    return 0;\n}\n\nstatic int parse_relative_font_size(void *dest, char *value) {\n    struct relative_font_size *rfs = dest;\n\n    static const char delims[] = \" \\t\";\n\n    int  s_len = strlen(value);\n    char buf[s_len + 1];\n    strcpy(buf, value);\n    buf[s_len] = '\\0';\n\n    char *strtok_p;\n    char *token = strtok_r(buf, delims, &strtok_p);\n\n    if (token == NULL) {\n        LOG_ERR(\"No minimum size.\");\n        return 1;\n    }\n\n    errno    = 0;\n    rfs->min = strtod(token, NULL);\n    if (errno) {\n        LOG_ERR(\"Invalid minimum size.\");\n        return 1;\n    }\n\n    token = strtok_r(NULL, delims, &strtok_p);\n    if (token == NULL) {\n        LOG_ERR(\"No relative size.\");\n        return 1;\n    }\n\n    errno           = 0;\n    rfs->proportion = strtod(token, NULL);\n    if (token[strlen(token) - 1] == '%') {\n        rfs->proportion /= 100.;\n    }\n    if (errno) {\n        LOG_ERR(\"Invalid relative size.\");\n        return 1;\n    }\n\n    token = strtok_r(NULL, delims, &strtok_p);\n    if (token == NULL) {\n        LOG_ERR(\"No maximum size.\");\n        return 1;\n    }\n\n    errno    = 0;\n    rfs->max = strtod(token, NULL);\n    if (errno) {\n        LOG_ERR(\"Invalid maximum size.\");\n        return 1;\n    }\n\n    if (rfs->min < 0) {\n        LOG_ERR(\"Minimum size can't be negative.\");\n        return 1;\n    }\n\n    if (rfs->max < 0) {\n        LOG_ERR(\"Maximum size can't be negative.\");\n        return 1;\n    }\n\n    if (rfs->proportion < 0) {\n        LOG_ERR(\"Proportion can't be negative.\");\n        return 1;\n    }\n\n    if (rfs->min > rfs->max) {\n        LOG_ERR(\"Minimum size can't be greater than maximum size.\");\n        return 1;\n    }\n\n    return 0;\n}\n\nstatic int parse_home_row_keys(void *dest, char *value) {\n    char ***home_row_keys_ptr = dest;\n\n    if (value[0] == '\\0') {\n        *home_row_keys_ptr = NULL;\n        return 0;\n    }\n\n#define ASSERT_FOLLOW_UP_BYTE(c)           \\\n    if ((*c & 0b11000000) != 0b10000000) { \\\n        LOG_ERR(\"Encoding error.\");        \\\n        goto err;                          \\\n    }\n\n    char  *b    = malloc(HOME_ROW_LEN_WITH_BTN * 5);\n    char **keys = malloc(HOME_ROW_LEN_WITH_BTN * sizeof(char *));\n\n    char *c = value;\n\n    for (int i = 0; i < HOME_ROW_LEN_WITH_BTN; i++) {\n        if (*c == 0) {\n            LOG_ERR(\"Could not parse home row keys. Not enough characters.\");\n            LOG_ERR(\n                \"Exactly 11 are required. The first 8 are used to select \"\n                \"the sub-areas in the bisect mode.\"\n            );\n            LOG_ERR(\n                \"The next three characters are used for left, right and \"\n                \"middle click respectively.\"\n            );\n            goto err;\n        }\n\n        if ((*c & 0b10000000) == 0) {\n            b[i * 5]     = *c++;\n            b[i * 5 + 1] = 0;\n        } else if ((*c & 0b11100000) == 0b11000000) {\n            b[i * 5] = *c++;\n            ASSERT_FOLLOW_UP_BYTE(c);\n            b[i * 5 + 1] = *c++;\n            b[i * 5 + 2] = 0;\n        } else if ((*c & 0b11110000) == 0b11100000) {\n            b[i * 5] = *c++;\n            ASSERT_FOLLOW_UP_BYTE(c);\n            b[i * 5 + 1] = *c++;\n            ASSERT_FOLLOW_UP_BYTE(c);\n            b[i * 5 + 2] = *c++;\n            b[i * 5 + 3] = 0;\n        } else if ((*c & 0b11111000) == 0b11110000) {\n            b[i * 5] = *c++;\n            ASSERT_FOLLOW_UP_BYTE(c);\n            b[i * 5 + 1] = *c++;\n            ASSERT_FOLLOW_UP_BYTE(c);\n            b[i * 5 + 2] = *c++;\n            ASSERT_FOLLOW_UP_BYTE(c);\n            b[i * 5 + 3] = *c++;\n            b[i * 5 + 4] = 0;\n        }\n\n        keys[i] = &b[i * 5];\n    }\n\n    if (*c != '\\0') {\n        LOG_ERR(\"Too many characters. Exactly 11 are required.\");\n        goto err;\n    }\n\n    *home_row_keys_ptr = keys;\n\n    return 0;\n\nerr:\n    free(b);\n    free(keys);\n    return 1;\n}\n\nstatic int parse_str(void *dest, char *value) {\n    *((char **)dest) = strdup(value);\n    return 0;\n}\n\nstatic int parse_floating_mode_source_value(void *dest, char *value) {\n    enum floating_mode_source *out = dest;\n    if (strcmp(value, \"stdin\") == 0) {\n        *out = FLOATING_MODE_SOURCE_STDIN;\n    } else if (strcmp(value, \"detect\") == 0) {\n#if OPENCV_ENABLED\n        *out = FLOATING_MODE_SOURCE_DETECT;\n#else\n        LOG_ERR(\"Binary not build with OpenCV. 'detect' source not supported.\");\n        return 2;\n#endif\n    } else {\n        LOG_ERR(\"Invalid source '%s'. Should be 'stdin' or 'detect'.\", value);\n        return 1;\n    }\n\n    return 0;\n}\n\nstatic int parse_click(void *dest, char *value) {\n    enum click *out = dest;\n    if (strcmp(value, \"none\") == 0) {\n        *out = CLICK_NONE;\n    } else if (strcmp(value, \"left\") == 0) {\n        *out = CLICK_LEFT_BTN;\n    } else if (strcmp(value, \"right\") == 0) {\n        *out = CLICK_RIGHT_BTN;\n    } else if (strcmp(value, \"middle\") == 0) {\n        *out = CLICK_MIDDLE_BTN;\n    } else {\n        LOG_ERR(\n            \"Invalid click button '%s'. Should be 'left', 'right', 'middle' or \"\n            \"'none'.\",\n            value\n        );\n        return 1;\n    }\n\n    return 0;\n}\n\nstatic void free_home_row_keys(void *field_value) {\n    char ***home_row_keys_ptr = field_value;\n    if (*home_row_keys_ptr == NULL) {\n        return;\n    }\n\n    free(**home_row_keys_ptr);\n    free(*home_row_keys_ptr);\n\n    *home_row_keys_ptr = NULL;\n}\n\nstatic void free_str(void *field_value) {\n    free(*((char **)field_value));\n}\n\nstruct field_def {\n    char  *name;\n    size_t offset;\n    char  *default_value;\n    int (*parse)(void *dest, char *value);\n    void (*free)(void *value);\n};\n\nstruct section_def {\n    char              *name;\n    size_t             offset;\n    struct field_def **fields;\n};\n\n#define SECTION(name, ...)                                             \\\n    (struct section_def) {                                             \\\n        #name, offsetof(struct config, name), (struct field_def *[]) { \\\n            __VA_ARGS__, NULL                                          \\\n        }                                                              \\\n    }\n\n#define FIELD(type, name, default_value, parse, free)           \\\n    (struct field_def[]) {                                      \\\n        #name, offsetof(type, name), default_value, parse, free \\\n    }\n\n#define G_FIELD(name, default_value, parse, free) \\\n    FIELD(struct general_config, name, default_value, parse, free)\n#define MT_FIELD(name, default_value, parse, free) \\\n    FIELD(struct mode_tile_config, name, default_value, parse, free)\n#define MF_FIELD(name, default_value, parse, free) \\\n    FIELD(struct mode_floating_config, name, default_value, parse, free)\n#define MB_FIELD(name, default_value, parse, free) \\\n    FIELD(struct mode_bisect_config, name, default_value, parse, free)\n#define MS_FIELD(name, default_value, parse, free) \\\n    FIELD(struct mode_split_config, name, default_value, parse, free)\n#define MC_FIELD(name, default_value, parse, free) \\\n    FIELD(struct mode_click_config, name, default_value, parse, free)\n\nstatic void noop() {}\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmissing-braces\"\nstatic struct section_def section_defs[] = {\n    SECTION(\n        general,\n        G_FIELD(home_row_keys, \"\", parse_home_row_keys, free_home_row_keys),\n        G_FIELD(modes, \"tile,bisect\", parse_str, free_str),\n        G_FIELD(cancellation_status_code, \"0\", parse_uint8, noop)\n    ),\n    SECTION(\n        mode_tile, MT_FIELD(label_color, \"#fffd\", parse_color, noop),\n        MT_FIELD(label_select_color, \"#fd0d\", parse_color, noop),\n        MT_FIELD(unselectable_bg_color, \"#2226\", parse_color, noop),\n        MT_FIELD(selectable_bg_color, \"#0304\", parse_color, noop),\n        MT_FIELD(selectable_border_color, \"#040c\", parse_color, noop),\n        MT_FIELD(label_font_family, \"sans-serif\", parse_str, free_str),\n        MT_FIELD(label_font_size, \"8 50% 100\", parse_relative_font_size, noop),\n        MT_FIELD(\n            label_symbols, \"abcdefghijklmnopqrstuvwxyz\", parse_str, free_str\n        )\n    ),\n    SECTION(\n        mode_floating,\n        MF_FIELD(source, \"stdin\", parse_floating_mode_source_value, noop),\n        MF_FIELD(label_color, \"#fffd\", parse_color, noop),\n        MF_FIELD(label_select_color, \"#fd0d\", parse_color, noop),\n        MF_FIELD(unselectable_bg_color, \"#2226\", parse_color, noop),\n        MF_FIELD(selectable_bg_color, \"#1718\", parse_color, noop),\n        MF_FIELD(selectable_border_color, \"#040c\", parse_color, noop),\n        MF_FIELD(label_font_family, \"sans-serif\", parse_str, free_str),\n        MF_FIELD(label_font_size, \"12 50% 100\", parse_relative_font_size, noop),\n        MF_FIELD(\n            label_symbols, \"abcdefghijklmnopqrstuvwxyz\", parse_str, free_str\n        )\n    ),\n    SECTION(\n        mode_bisect, MB_FIELD(label_color, \"#fffd\", parse_color, noop),\n        // TODO: we should set minimums for numbers.\n        MB_FIELD(label_font_size, \"20\", parse_double, noop),\n        MB_FIELD(label_font_family, \"sans-serif\", parse_str, free_str),\n        MB_FIELD(label_padding, \"12\", parse_double, noop),\n        MB_FIELD(pointer_size, \"20\", parse_double, noop),\n        MB_FIELD(pointer_color, \"#e22d\", parse_color, noop),\n        MB_FIELD(unselectable_bg_color, \"#2226\", parse_color, noop),\n        MB_FIELD(even_area_bg_color, \"#0304\", parse_color, noop),\n        MB_FIELD(even_area_border_color, \"#0408\", parse_color, noop),\n        MB_FIELD(odd_area_bg_color, \"#0034\", parse_color, noop),\n        MB_FIELD(odd_area_border_color, \"#0048\", parse_color, noop),\n        MB_FIELD(history_border_color, \"#3339\", parse_color, noop)\n    ),\n    SECTION(\n        mode_split, MS_FIELD(pointer_size, \"20\", parse_double, noop),\n        MS_FIELD(pointer_color, \"#e22d\", parse_color, noop),\n        MS_FIELD(bg_color, \"#2226\", parse_color, noop),\n        MS_FIELD(area_bg_color, \"#11111188\", parse_color, noop),\n        MS_FIELD(vertical_color, \"#8888ffcc\", parse_color, noop),\n        MS_FIELD(horizontal_color, \"#008800cc\", parse_color, noop),\n        MS_FIELD(history_border_color, \"#3339\", parse_color, noop)\n    ),\n    SECTION(mode_click, MC_FIELD(button, \"left\", parse_click, noop)),\n};\n#pragma GCC diagnostic pop\n\nvoid print_default_config() {\n    puts(\"# wl-kbptr can be configured with a configuration file.\");\n    puts(\"# The file location can be passed with the -c parameter.\");\n    puts(\"# Othewise the `$XDG_CONFIG_HOME/wl-kbptr/config` file will\");\n    puts(\"# be loaded if it exits. Below is the default configuration.\");\n\n    for (int i = 0; i < sizeof(section_defs) / sizeof(section_defs[0]); i++) {\n        struct section_def *section_def = &section_defs[i];\n\n        printf(\"\\n[%s]\\n\", section_def->name);\n\n        for (struct field_def **field_def_ptr = section_def->fields;\n             *field_def_ptr != NULL; field_def_ptr++) {\n            struct field_def *field_def = *field_def_ptr;\n\n            printf(\"%s=%s\\n\", field_def->name, field_def->default_value);\n        }\n    }\n}\n\nvoid config_loader_init(struct config_loader *loader, struct config *config) {\n    loader->config           = config;\n    loader->curr_section_def = &section_defs[0];\n}\n\nint config_loader_enter_section(struct config_loader *loader, char *section) {\n    for (int i = 0; i < sizeof(section_defs) / sizeof(section_defs[0]); i++) {\n        struct section_def *section_def = &section_defs[i];\n\n        if (strcmp(section, section_def->name) == 0) {\n            loader->curr_section_def = section_def;\n            return 0;\n        }\n    }\n\n    LOG_ERR(\"Configuration section `%s` does not exist.\", section);\n    return 1;\n}\n\nint config_loader_load_field(\n    struct config_loader *loader, char *name, char *value\n) {\n    struct section_def *section_def = loader->curr_section_def;\n\n    for (struct field_def **field_defs = section_def->fields;\n         *field_defs != NULL; field_defs++) {\n        struct field_def *field_def = *field_defs;\n\n        if (strcmp(name, field_def->name) == 0) {\n            void *dest = ((void *)loader->config) + section_def->offset +\n                         field_def->offset;\n            field_def->free(dest);\n            int err = field_def->parse(dest, value);\n            if (err != 0) {\n                LOG_ERR(\"Invalid value for %s.%s.\", section_def->name, name);\n                return 2;\n            }\n\n            return 0;\n        }\n    }\n\n    LOG_ERR(\n        \"Configuration option `%s.%s` does not exist.\", section_def->name, name\n    );\n    return 1;\n}\n\nint config_loader_load_cli_param(struct config_loader *loader, char *value) {\n    // `buf` will hold a copy of the section and field name as\n    // `section\\0field\\0`.\n    char buf[strlen(value)];\n\n    // `bc` holds the current position in `buf`. Each time we write to `buf`\n    // this pointer is incremented.\n    char *bc = buf;\n\n    // `c` holds the current position in `value`.\n    char *c = value;\n\n    char *section = buf;\n    while (*c != '\\0' && *c != '.' && *c != '=') {\n        *(bc++) = *(c++);\n    }\n\n    char *field_name;\n\n    if (*c == '.') {\n        *(bc++) = '\\0';\n        c++;\n\n        field_name = bc;\n        while (*c != '\\0' && *c != '=') {\n            *(bc++) = *(c++);\n        }\n    } else {\n        field_name = section;\n        section    = \"general\";\n    }\n\n    if (*c != '=') {\n        LOG_ERR(\"Invalid configuration parameter `%s`.\", value);\n        return 1;\n    }\n\n    *(bc++) = '\\0';\n    c++;\n\n    int err = config_loader_enter_section(loader, section);\n    if (err != 0) {\n        return 2;\n    }\n\n    char *field_value = c;\n    err = config_loader_load_field(loader, field_name, field_value);\n    if (err != 0) {\n        return 3;\n    }\n\n    return 0;\n}\n\nvoid config_set_default(struct config *config) {\n    for (int i = 0; i < sizeof(section_defs) / sizeof(section_defs[0]); i++) {\n        struct section_def *section_def = &section_defs[i];\n        for (struct field_def **field_def_ptr = section_def->fields;\n             *field_def_ptr != NULL; field_def_ptr++) {\n            struct field_def *field_def = *field_def_ptr;\n\n            int err = field_def->parse(\n                ((void *)config) + section_def->offset + field_def->offset,\n                field_def->default_value\n            );\n            if (err != 0) {\n                LOG_ERR(\n                    \"Could not set default value '%s' for %s.%s.\",\n                    field_def->default_value, section_def->name, field_def->name\n                );\n            }\n        }\n    }\n}\n\nvoid config_free_values(struct config *config) {\n    for (int i = 0; i < sizeof(section_defs) / sizeof(section_defs[0]); i++) {\n        struct section_def *section_def = &section_defs[i];\n        for (struct field_def **field_def_ptr = section_def->fields;\n             *field_def_ptr != NULL; field_def_ptr++) {\n            struct field_def *field_def = *field_def_ptr;\n\n            field_def->free(\n                ((void *)config) + section_def->offset + field_def->offset\n            );\n        }\n    }\n}\n\nstatic const char *XDG_PATH_FMT = \"%s/wl-kbptr/config\";\n\nstatic FILE *open_config_file(char *file_name) {\n    FILE *f = NULL;\n\n    if (file_name != NULL) {\n        f = fopen(file_name, \"r\");\n        if (f == NULL) {\n            LOG_ERR(\"Could not open config file '%s'\", file_name);\n            return NULL;\n        }\n\n        LOG_INFO(\"Loading config file '%s'\", file_name);\n        return f;\n    }\n\n    char       *xdg_config_home     = getenv(\"XDG_CONFIG_HOME\");\n    const char *home                = getenv(\"HOME\");\n    size_t      config_home_buf_len = 0;\n\n    if (xdg_config_home == NULL && home != NULL) {\n        config_home_buf_len = strlen(home) + sizeof(\"/.config\");\n    }\n\n    char config_home_buf[config_home_buf_len];\n\n    if (xdg_config_home == NULL && home != NULL) {\n        snprintf(config_home_buf, config_home_buf_len, \"%s/.config\", home);\n        xdg_config_home = config_home_buf;\n    }\n\n    if (xdg_config_home != NULL) {\n        int  path_len = snprintf(NULL, 0, XDG_PATH_FMT, xdg_config_home) + 1;\n        char file_path[path_len];\n        snprintf(file_path, path_len, XDG_PATH_FMT, xdg_config_home);\n\n        f = fopen(file_path, \"r\");\n        if (f == NULL) {\n            LOG_WARN(\"Could not open config file '%s'\", file_path);\n            return NULL;\n        }\n\n        LOG_INFO(\"Loading config file '%s'\", file_path);\n    }\n\n    return f;\n}\n\nstatic const char *WHITE_SPACES = \"\\r\\t \";\n\nint config_loader_load_file(struct config_loader *loader, char *file_name) {\n    FILE *f = open_config_file(file_name);\n    if (f == NULL) {\n        return file_name == NULL ? 0 : 1;\n    }\n\n    char buf[256];\n    int  c = 0, i, err;\n\n    for (int line; c != EOF; line++) {\n        do {\n            c = getc(f);\n        } while (strchr(WHITE_SPACES, c) != NULL);\n\n        switch (c) {\n        // Comment\n        case '#':\n            do {\n                c = getc(f);\n            } while (c != '\\n' && c != EOF);\n            break;\n\n        // Section\n        case '[':\n            for (i = 0; i < (sizeof(buf) - 1) && (c = getc(f)) != ']'; i++) {\n                if (c == EOF) {\n                    LOG_ERR(\n                        \"Unexpected end of file. Section was not terminated.\"\n                    );\n                    goto err;\n                } else if (c == '\\n') {\n                    LOG_ERR(\n                        \"Unexpected end of line. Section was not terminated.\"\n                    );\n                    goto err;\n                }\n                buf[i] = c;\n            }\n\n            if (c != ']') {\n                LOG_ERR(\"Line is too long.\");\n                goto err;\n            }\n\n            buf[i] = '\\0';\n\n            do {\n                c = getc(f);\n                if (strchr(WHITE_SPACES, c) != NULL) {\n                    LOG_ERR(\n                        \"Only whitespaces are allowed after a section's ending \"\n                        \"delimiter.\"\n                    );\n                    goto err;\n                }\n            } while (c != '\\n' && c != EOF);\n\n            err = config_loader_enter_section(loader, buf) != 0;\n            if (err) {\n                goto err;\n            }\n            break;\n\n        // Empty line\n        case '\\n':\n            break;\n\n        case EOF:\n            goto success;\n\n        // key=value\n        default:\n            buf[0] = c;\n            for (i = 1; i < (sizeof(buf) - 1) && (c = getc(f)) != '='; i++) {\n                if (c == EOF) {\n                    LOG_ERR(\"Unexpected end of file. Expected equal operator.\");\n                    goto err;\n                } else if (c == '\\n') {\n                    LOG_ERR(\"Unexpected end of line. Expected equal operator.\");\n                    goto err;\n                }\n                buf[i] = c;\n            }\n\n            if (c != '=') {\n                LOG_ERR(\"Line is too long\");\n                goto err;\n            }\n\n            buf[i++] = '\\0';\n\n            char *value = &buf[i];\n            for (; i < (sizeof(buf)); i++) {\n                c = getc(f);\n                if (c == EOF || c == '\\n') {\n                    break;\n                } else if (c == '\\r') {\n                    continue;\n                }\n\n                buf[i] = c;\n            }\n\n            if (i == sizeof(buf)) {\n                LOG_ERR(\"Line is too long\");\n            }\n\n            buf[i] = '\\0';\n\n            err = config_loader_load_field(loader, buf, value);\n            if (err) {\n                goto err;\n            }\n        }\n    }\n\nsuccess:\n    fclose(f);\n    return 0;\n\nerr:\n    fclose(f);\n    return 1;\n}\n\ndouble\ncompute_relative_font_size(struct relative_font_size *rfs, double height) {\n    double value = height * rfs->proportion;\n    if (value < rfs->min) {\n        return rfs->min;\n    }\n\n    if (value > rfs->max) {\n        return rfs->max;\n    }\n\n    return value;\n}\n"
  },
  {
    "path": "src/config.h",
    "content": "#ifndef __CONFIG_H_INCLUDED__\n#define __CONFIG_H_INCLUDED__\n\n#include \"utils.h\"\n\n#include <stdint.h>\n\nstruct general_config {\n    char  **home_row_keys;\n    char   *modes;\n    uint8_t cancellation_status_code;\n};\n\nstruct relative_font_size {\n    double proportion;\n    double min;\n    double max;\n};\n\nstruct mode_tile_config {\n    uint32_t                  label_color;\n    uint32_t                  label_select_color;\n    uint32_t                  unselectable_bg_color;\n    uint32_t                  selectable_bg_color;\n    uint32_t                  selectable_border_color;\n    char                     *label_font_family;\n    struct relative_font_size label_font_size;\n    char                     *label_symbols;\n};\n\nenum floating_mode_source {\n    FLOATING_MODE_SOURCE_STDIN,\n    FLOATING_MODE_SOURCE_DETECT,\n};\n\nstruct mode_floating_config {\n    enum floating_mode_source source;\n    uint32_t                  label_color;\n    uint32_t                  label_select_color;\n    uint32_t                  unselectable_bg_color;\n    uint32_t                  selectable_bg_color;\n    uint32_t                  selectable_border_color;\n    char                     *label_font_family;\n    struct relative_font_size label_font_size;\n    char                     *label_symbols;\n};\n\nstruct mode_bisect_config {\n    uint32_t label_color;\n    double   label_font_size;\n    char    *label_font_family;\n    double   label_padding;\n\n    double  pointer_size;\n    int32_t pointer_color;\n\n    uint32_t unselectable_bg_color;\n    uint32_t even_area_bg_color;\n    uint32_t even_area_border_color;\n    uint32_t odd_area_bg_color;\n    uint32_t odd_area_border_color;\n\n    uint32_t history_border_color;\n};\n\nstruct mode_split_config {\n    double  pointer_size;\n    int32_t pointer_color;\n\n    uint32_t bg_color;\n    uint32_t area_bg_color;\n    uint32_t vertical_color;\n    uint32_t horizontal_color;\n\n    uint32_t history_border_color;\n};\n\nstruct mode_click_config {\n    enum click button;\n};\n\nstruct config {\n    struct general_config       general;\n    struct mode_tile_config     mode_tile;\n    struct mode_floating_config mode_floating;\n    struct mode_bisect_config   mode_bisect;\n    struct mode_split_config    mode_split;\n    struct mode_click_config    mode_click;\n};\n\n/**\n * The `config_loader` structure stores needed states to set parse values.\n */\nstruct config_loader {\n    struct config *config;\n    void          *curr_section_def;\n};\n\nvoid print_default_config();\n\n/**\n * `config_set_default` sets default values set in the configuration's\n * definitions.\n */\nvoid config_set_default(struct config *config);\n\n/**\n * `config_free_values` frees configuration fields' values. This doesn't free\n * the `config` structure itself.\n */\nvoid config_free_values(struct config *config);\n\n/**\n * `config_loader_init` initialise the `config_loader` structure.\n */\nvoid config_loader_init(\n    struct config_loader *config_loader, struct config *config\n);\n\n/**\n * `config_loader_enter_section` sets the current section's state. Following\n * calls to `config_loader_load_field` will load fields for the given section.\n */\nint config_loader_enter_section(struct config_loader *loader, char *section);\n\n/**\n * `config_loader_load_field` loads the give field value from the current\n * section.\n */\nint config_loader_load_field(\n    struct config_loader *loader, char *name, char *value\n);\n\n/**\n * `config_loader_load_cli_param` loads a configuration value from a CLI\n * parameter value, e.g. `mode_bisect.label_color=#66666666`.\n */\nint config_loader_load_cli_param(struct config_loader *loader, char *value);\n\n/**\n * `config_loader_load_file` loads configuration values from the given file or\n * from one of the default locations (if `file_name` is NULL).\n */\nint config_loader_load_file(struct config_loader *loader, char *file_name);\n\ndouble\ncompute_relative_font_size(struct relative_font_size *rfs, double height);\n\n#endif\n"
  },
  {
    "path": "src/label.c",
    "content": "#include \"label.h\"\n\n#include \"log.h\"\n#include \"utils.h\"\n\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n\nlabel_symbols_t *label_symbols_from_str(char *s) {\n    char *c = s;\n\n    uint32_t r;\n    int      c_len;\n\n    int len         = sizeof(label_symbols_t);\n    int num_symbols = 0;\n\n    while ((c_len = str_to_rune(c, &r)) > 0) {\n        // One byte for the indices and one of the end of string (`\\0`).\n        c           += c_len;\n        len         += c_len + 2;\n        num_symbols += 1;\n    }\n\n    if (c_len < 0) {\n        LOG_ERR(\"Invalid UTF-8 input.\");\n        return NULL;\n    }\n\n    if (num_symbols < 2) {\n        LOG_ERR(\n            \"Not enough characters (%d). Must have at least 2.\", num_symbols\n        );\n        return NULL;\n    }\n\n    if (num_symbols >= 255) {\n        LOG_ERR(\"Too many characters (%d).\", num_symbols);\n        return NULL;\n    }\n\n    label_symbols_t *label_symbols = malloc(len);\n\n    label_symbols->num_symbols = num_symbols;\n    unsigned char *indices     = (unsigned char *)label_symbols->data;\n    char          *str         = &label_symbols->data[num_symbols];\n\n    c              = s;\n    int str_offset = 0;\n    for (int i = 0; i < num_symbols; i++) {\n        c_len      = str_to_rune(c, &r);\n        indices[i] = str_offset;\n        memcpy(str + str_offset, c, c_len);\n        str[str_offset + c_len] = '\\0';\n\n        str_offset += c_len + 1;\n        c          += c_len;\n    }\n\n    return label_symbols;\n}\n\nvoid label_symbols_free(label_symbols_t *ls) {\n    free(ls);\n}\n\nchar *label_symbols_idx_to_ptr(label_symbols_t *label_symbols, int idx) {\n    if (idx < 0 || idx >= label_symbols->num_symbols) {\n        LOG_ERR(\"Label symbols index (%d) out of bound.\", idx);\n        return NULL;\n    }\n\n    return ((char *)label_symbols->data) + label_symbols->num_symbols +\n           ((unsigned char *)label_symbols->data)[idx];\n}\n\nint label_symbols_find_idx(label_symbols_t *label_symbols, char *s) {\n    for (int i = 0; i < label_symbols->num_symbols; i++) {\n        if (strcmp(label_symbols_idx_to_ptr(label_symbols, i), s) == 0) {\n            return i;\n        }\n    }\n\n    return -1;\n}\n\nlabel_selection_t *\nlabel_selection_new(label_symbols_t *label_symbols, int num_labels) {\n    label_selection_t *l = malloc(sizeof(*l) + label_symbols->num_symbols);\n\n    l->num_labels = num_labels;\n\n    l->len = 0;\n    while (num_labels > 0) {\n        l->len++;\n        num_labels /= label_symbols->num_symbols;\n    }\n\n    l->next          = 0;\n    l->label_symbols = label_symbols;\n    return l;\n}\n\nvoid label_selection_clear(label_selection_t *label_selection) {\n    label_selection->next = 0;\n}\n\nstatic int label_selection_to_partial_idx(label_selection_t *label_selection) {\n    int idx         = 0;\n    int factor      = 1;\n    int num_symbols = label_selection->label_symbols->num_symbols;\n\n    for (int i = 0; i < label_selection->next; i++) {\n        idx    += label_selection->input[i] * factor;\n        factor *= num_symbols;\n    }\n\n    return idx;\n}\n\nenum label_selection_append_ret\nlabel_selection_append(label_selection_t *label_selection, int idx) {\n    if (label_selection->next >= label_selection->label_symbols->num_symbols) {\n        return LABEL_SELECTION_APPEND_FULL;\n    }\n\n    label_selection->input[label_selection->next++] = idx;\n\n    if (label_selection_to_partial_idx(label_selection) >=\n        label_selection->num_labels) {\n        label_selection->next--;\n        return LABEL_SELECTION_APPEND_IDX_OVERFLOW;\n    }\n\n    return LABEL_SELECTION_APPEND_SUCCESS;\n}\n\nbool label_selection_back(label_selection_t *label_selection) {\n    if (label_selection->next == 0) {\n        return false;\n    }\n\n    label_selection->next--;\n    return true;\n}\n\nbool label_selection_is_included(\n    label_selection_t *reference, label_selection_t *start\n) {\n    if (reference->label_symbols != start->label_symbols ||\n        reference->len != start->len || reference->next < start->next) {\n        return false;\n    }\n\n    for (int i = 0; i < start->next; i++) {\n        if (reference->input[i] != start->input[i]) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint label_selection_to_idx(label_selection_t *label_selection) {\n    if (label_selection->next != label_selection->len) {\n        return -1;\n    }\n\n    return label_selection_to_partial_idx(label_selection);\n}\n\nint label_selection_set_from_idx(label_selection_t *label_selection, int idx) {\n    int num_symbols = label_selection->label_symbols->num_symbols;\n\n    for (label_selection->next = 0;\n         label_selection->next < label_selection->len;\n         label_selection->next++) {\n        label_selection->input[label_selection->next]  = idx % num_symbols;\n        idx                                           /= num_symbols;\n    }\n\n    return idx == 0;\n}\n\nint label_selection_incr(label_selection_t *label_selection) {\n    int num_symbols = label_selection->label_symbols->num_symbols;\n\n    for (int i = 0; i < label_selection->len; i++) {\n        label_selection->input[i] += 1;\n\n        if (label_selection->input[i] < num_symbols) {\n            return 1;\n        }\n\n        label_selection->input[i] %= num_symbols;\n    }\n\n    return 0;\n}\n\nstatic int label_symbols_max_str_len(label_symbols_t *label_symbols) {\n    unsigned char *indices = (unsigned char *)label_symbols->data;\n    int            i;\n\n    int max_len  = 0;\n    int curr_len = 0;\n\n    for (i = 1; i < label_symbols->num_symbols; i++) {\n        curr_len = indices[i] - indices[i - 1] - 1;\n        if (curr_len > max_len) {\n            max_len = curr_len;\n        }\n    }\n\n    curr_len = strlen(\n        label_symbols_idx_to_ptr(label_symbols, label_symbols->num_symbols - 1)\n    );\n    if (curr_len > max_len) {\n        max_len = curr_len;\n    }\n\n    return max_len;\n}\n\nint label_selection_str_max_len(label_selection_t *label_selection) {\n    return label_symbols_max_str_len(label_selection->label_symbols) *\n           label_selection->len;\n}\n\nvoid label_selection_str(label_selection_t *label_selection, char *out) {\n    label_symbols_t *label_symbols = label_selection->label_symbols;\n    for (int i = 0; i < label_selection->next; i++) {\n        out = stpcpy(\n            out,\n            label_symbols_idx_to_ptr(label_symbols, label_selection->input[i])\n        );\n    }\n\n    *out = '\\0';\n}\n\nvoid label_selection_str_split(\n    label_selection_t *label_selection, char *prefix, char *suffix, int cut\n) {\n    if (cut < 0) {\n        cut = 0;\n    } else if (cut >= label_selection->next) {\n        cut = label_selection->next;\n    }\n\n    label_symbols_t *label_symbols = label_selection->label_symbols;\n    for (int i = 0; i < cut; i++) {\n        prefix = stpcpy(\n            prefix,\n            label_symbols_idx_to_ptr(label_symbols, label_selection->input[i])\n        );\n    }\n    *prefix = '\\0';\n\n    for (int i = cut; i < label_selection->next; i++) {\n        suffix = stpcpy(\n            suffix,\n            label_symbols_idx_to_ptr(label_symbols, label_selection->input[i])\n        );\n    }\n    *suffix = '\\0';\n}\n\nvoid label_selection_free(label_selection_t *label_selection) {\n    free(label_selection);\n}\n"
  },
  {
    "path": "src/label.h",
    "content": "#ifndef __LABEL_H_INCLUDED__\n#define __LABEL_H_INCLUDED__\n\n#include <stdbool.h>\n\ntypedef struct {\n    /*         data             data[num_symbols]\n     *         |                |\n     *  | 4 || 0 | 2 | 4 | 6 ||`a`| 0 |`b`| 0 |`c`| 0 |`d`| 0 |\n     *    ^    ^-----------^    ^---------------------------^\n     *    |       offsets               strings\n     *    |\n     *  number of symbols\n     */\n    unsigned char num_symbols;\n    char          data[];\n} label_symbols_t;\n\ntypedef struct {\n    label_symbols_t *label_symbols;\n    int              num_labels;\n    unsigned char    len;\n    unsigned char    next;\n    unsigned char    input[];\n} label_selection_t;\n\n// Create a `label_symbols_t` from a string of characters.\n// Returns `NULL` upon error.\nlabel_symbols_t *label_symbols_from_str(char *s);\n\n// Free memory of a `label_symbols_t`.\nvoid label_symbols_free(label_symbols_t *ls);\n\n// Get pointer to string of the symbol at given index.\n// Returns value <0 upon error.\nchar *label_symbols_idx_to_ptr(label_symbols_t *label_symbols, int idx);\n\n// Find symbol index from given string.\n// Returns value <0 upon error.\nint label_symbols_find_idx(label_symbols_t *label_symbols, char *s);\n\n// Create a `label_selection_t`.\nlabel_selection_t *\nlabel_selection_new(label_symbols_t *label_symbols, int num_labels);\n\n// Clear selection.\nvoid label_selection_clear(label_selection_t *label_selection);\n\nenum label_selection_append_ret {\n    LABEL_SELECTION_APPEND_SUCCESS      = 0,\n    LABEL_SELECTION_APPEND_IDX_OVERFLOW = 1,\n    LABEL_SELECTION_APPEND_FULL         = 2\n};\n// Append to selection.\nenum label_selection_append_ret\nlabel_selection_append(label_selection_t *label_selection, int idx);\n\n// Erase last symbol.\n// Returns true if it did else false.\nbool label_selection_back(label_selection_t *label_selection);\n\n// Returns true if `start` is the same as `reference` beginning else false.\nbool label_selection_is_included(\n    label_selection_t *reference, label_selection_t *start\n);\n\n// Returns associated label index.\nint label_selection_to_idx(label_selection_t *label_selection);\n\n// Set selection from associated index.\nint label_selection_set_from_idx(label_selection_t *label_selection, int idx);\n\n// Set to selection with incremented associated index.\nint label_selection_incr(label_selection_t *label_selection);\n\n// Get size of buffer needed to store label's string.\nint label_selection_str_max_len(label_selection_t *label_selection);\n\n// Get label's string.\nvoid label_selection_str(label_selection_t *label_selection, char *out);\n\n// Get label string split at `cut`.\nvoid label_selection_str_split(\n    label_selection_t *label_selection, char *prefix, char *suffix, int cut\n);\n\n// Free memory of `label_selection_t`.\nvoid label_selection_free(label_selection_t *label_selection);\n\n#endif\n"
  },
  {
    "path": "src/log.h",
    "content": "#ifndef __LOG_H_INCLUDED__\n#define __LOG_H_INCLUDED__\n\n#include <stdio.h>\n\n#define LOG_ERR(msg, ...) \\\n    fprintf(stderr, \"\\x1b[31merr:\\x1b[0m \" msg \"\\n\", ##__VA_ARGS__)\n\n#define LOG_WARN(msg, ...) \\\n    fprintf(stderr, \"\\x1b[33mwarn:\\x1b[0m \" msg \"\\n\", ##__VA_ARGS__)\n\n#define LOG_INFO(msg, ...) \\\n    fprintf(stderr, \"\\x1b[34minfo:\\x1b[0m \" msg \"\\n\", ##__VA_ARGS__)\n\n#ifdef DEBUG\n#define LOG_DEBUG(msg, ...) \\\n    fprintf(stderr, \"\\x1b[35mdebug:\\x1b[0m \" msg \"\\n\", ##__VA_ARGS__)\n#else\n#define LOG_DEBUG(msg, ...) ((void)0)\n#endif\n\n#endif\n"
  },
  {
    "path": "src/main.c",
    "content": "#include \"config.h\"\n#include \"fractional-scale-v1-client-protocol.h\"\n#include \"log.h\"\n#include \"mode.h\"\n#include \"state.h\"\n#include \"surface_buffer.h\"\n#include \"utils_wayland.h\"\n#include \"viewporter-client-protocol.h\"\n#include \"wlr-layer-shell-unstable-v1-client-protocol.h\"\n#include \"wlr-screencopy-unstable-v1-client-protocol.h\"\n#include \"wlr-virtual-pointer-unstable-v1-client-protocol.h\"\n#include \"xdg-output-unstable-v1-client-protocol.h\"\n\n#include <cairo/cairo.h>\n#include <getopt.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/mman.h>\n#include <unistd.h>\n#include <wayland-client-protocol.h>\n#include <wayland-client.h>\n#include <wayland-util.h>\n#include <xkbcommon/xkbcommon-keysyms.h>\n#include <xkbcommon/xkbcommon.h>\n\nstatic void send_frame(struct state *state) {\n    int32_t scale_120 = state->fractional_scale;\n    if (scale_120 == 0) {\n        // Falling back to the output scale if fractional scale is not received.\n        scale_120 =\n            (state->current_output == NULL ? 1 : state->current_output->scale) *\n            120;\n    }\n\n    struct surface_buffer *surface_buffer = get_next_buffer(\n        state->wl_shm, &state->surface_buffer_pool,\n        state->surface_width * scale_120 / 120,\n        state->surface_height * scale_120 / 120\n    );\n    if (surface_buffer == NULL) {\n        return;\n    }\n    surface_buffer->state = SURFACE_BUFFER_BUSY;\n\n    cairo_t *cairo = surface_buffer->cairo;\n    cairo_identity_matrix(cairo);\n    cairo_scale(cairo, scale_120 / 120.0, scale_120 / 120.0);\n    mode_render(state, cairo);\n\n    wl_surface_set_buffer_scale(state->wl_surface, 1);\n\n    wl_surface_attach(state->wl_surface, surface_buffer->wl_buffer, 0, 0);\n    wp_viewport_set_destination(\n        state->wp_viewport, state->surface_width, state->surface_height\n    );\n    wl_surface_damage(\n        state->wl_surface, 0, 0, state->surface_width, state->surface_height\n    );\n    wl_surface_commit(state->wl_surface);\n}\n\n/**\n * Send a 1x1px transparent surface.\n *\n * This is used so that the surface is shown on the screen which triggers the\n * `surface.enter()` event callback.\n */\nstatic void send_transparent_frame(struct state *state) {\n    struct surface_buffer *surface_buffer =\n        get_next_buffer(state->wl_shm, &state->surface_buffer_pool, 1, 1);\n    if (surface_buffer == NULL) {\n        return;\n    }\n    surface_buffer->state = SURFACE_BUFFER_BUSY;\n    cairo_t *cairo        = surface_buffer->cairo;\n    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);\n    cairo_set_source_rgba(cairo, 0, 0, 0, 0);\n    cairo_fill(cairo);\n    wl_surface_attach(state->wl_surface, surface_buffer->wl_buffer, 0, 0);\n    wp_viewport_set_destination(\n        state->wp_viewport, state->surface_width, state->surface_height\n    );\n    wl_surface_damage(state->wl_surface, 0, 0, 1, 1);\n    wl_surface_commit(state->wl_surface);\n}\n\nstatic void surface_callback_done(\n    void *data, struct wl_callback *callback, uint32_t callback_data\n) {\n    struct state *state = data;\n    send_frame(state);\n\n    wl_callback_destroy(state->wl_surface_callback);\n    state->wl_surface_callback = NULL;\n}\n\nconst struct wl_callback_listener surface_callback_listener = {\n    .done = surface_callback_done,\n};\n\nstatic void request_frame(struct state *state) {\n    if (state->wl_surface_callback != NULL) {\n        return;\n    }\n\n    state->wl_surface_callback = wl_surface_frame(state->wl_surface);\n    wl_callback_add_listener(\n        state->wl_surface_callback, &surface_callback_listener, state\n    );\n    wl_surface_commit(state->wl_surface);\n}\n\nbool compute_initial_area(struct state *state, struct rect *initial_area) {\n    if (initial_area->w == -1) {\n        initial_area->x = 0;\n        initial_area->y = 0;\n        initial_area->w = state->surface_width;\n        initial_area->h = state->surface_height;\n    } else {\n        if (initial_area->x < 0) {\n            initial_area->w += initial_area->x;\n            initial_area->x  = 0;\n        }\n\n        if (initial_area->y < 0) {\n            initial_area->h += initial_area->y;\n            initial_area->y  = 0;\n        }\n\n        if (initial_area->w + initial_area->x > state->current_output->width) {\n            initial_area->w = state->current_output->width - initial_area->x;\n        }\n\n        if (initial_area->h + initial_area->y > state->current_output->height) {\n            initial_area->h = state->current_output->height - initial_area->y;\n        }\n    }\n\n    if (initial_area->w <= 0 || initial_area->h <= 0) {\n        LOG_ERR(\n            \"Initial area (%dx%d) is too small.\", initial_area->w,\n            initial_area->h\n        );\n        return false;\n    }\n\n    return true;\n}\n\nstatic void noop() {}\n\nstatic void load_home_row(\n    struct xkb_keymap *keymap, char **home_row, char *home_row_buffer\n) {\n    static const xkb_keycode_t key_codes[] = {\n        0x26, // a\n        0x27, // s\n        0x28, // d\n        0x29, // f\n        0x2c, // j\n        0x2d, // k\n        0x2e, // l\n        0x2f, // m\n        0x2a, // g\n        0x2b, // h\n        0x38, // b\n    };\n\n    struct xkb_state *xkb_state   = xkb_state_new(keymap);\n    char             *buffer      = home_row_buffer;\n    size_t            buffer_size = HOME_ROW_BUFFER_LEN;\n\n    for (int i = 0; i < sizeof(key_codes) / sizeof(key_codes[0]); i++) {\n        xkb_keysym_t keysym =\n            xkb_state_key_get_one_sym(xkb_state, key_codes[i]);\n        int char_len = xkb_keysym_to_utf8(keysym, buffer, buffer_size);\n        if (char_len < 0) {\n            LOG_ERR(\"Could not load home row keys. Buffer is too small.\");\n            exit(1);\n        }\n\n        if (char_len == 0) {\n            LOG_ERR(\n                \"0x%x symkey does not have a UTF-8 representation in given \"\n                \"keymap.\",\n                key_codes[i]\n            );\n            exit(1);\n        }\n\n        home_row[i]  = buffer;\n        buffer      += char_len;\n        buffer_size -= char_len;\n    }\n\n    xkb_state_unref(xkb_state);\n}\n\nstatic void handle_keyboard_keymap(\n    void *data, struct wl_keyboard *keyboard, uint32_t format, int fd,\n    uint32_t size\n) {\n    struct seat *seat = data;\n    if (seat->xkb_state != NULL) {\n        xkb_state_unref(seat->xkb_state);\n        seat->xkb_state = NULL;\n    }\n    if (seat->xkb_keymap != NULL) {\n        xkb_keymap_unref(seat->xkb_keymap);\n        seat->xkb_keymap = NULL;\n    }\n\n    switch (format) {\n    case WL_KEYBOARD_KEYMAP_FORMAT_NO_KEYMAP:\n        seat->xkb_keymap = xkb_keymap_new_from_names(\n            seat->xkb_context, NULL, XKB_KEYMAP_COMPILE_NO_FLAGS\n        );\n        break;\n\n    case WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1:;\n        void *buffer = mmap(NULL, size - 1, PROT_READ, MAP_PRIVATE, fd, 0);\n        if (buffer == MAP_FAILED) {\n            LOG_ERR(\"Could not mmap keymap data.\");\n            return;\n        }\n\n        seat->xkb_keymap = xkb_keymap_new_from_buffer(\n            seat->xkb_context, buffer, size - 1, XKB_KEYMAP_FORMAT_TEXT_V1,\n            XKB_KEYMAP_COMPILE_NO_FLAGS\n        );\n\n        munmap(buffer, size - 1);\n        close(fd);\n        break;\n    }\n\n    if (seat->state->config.general.home_row_keys == NULL) {\n        load_home_row(\n            seat->xkb_keymap, seat->state->home_row,\n            seat->state->home_row_buffer\n        );\n    }\n    seat->xkb_state = xkb_state_new(seat->xkb_keymap);\n}\n\nstatic void handle_keyboard_key(\n    void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time,\n    uint32_t key, uint32_t key_state\n) {\n    struct seat        *seat = data;\n    char                text[64];\n    const xkb_keycode_t key_code = key + 8;\n    const xkb_keysym_t  key_sym =\n        xkb_state_key_get_one_sym(seat->xkb_state, key_code);\n    xkb_keysym_to_utf8(key_sym, text, sizeof(text));\n\n    if (key_state == WL_KEYBOARD_KEY_STATE_PRESSED) {\n        bool redraw = mode_handle_key(seat->state, key_sym, text);\n        if (has_last_mode_returned(seat->state)) {\n            seat->state->running = false;\n        } else if (redraw) {\n            request_frame(seat->state);\n        }\n    }\n}\n\nstatic void handle_keyboard_modifiers(\n    void *data, struct wl_keyboard *keyboard, uint32_t serial,\n    uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked,\n    uint32_t group\n) {\n    struct seat *seat = data;\n    xkb_state_update_mask(\n        seat->xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group\n    );\n}\n\nstatic const struct wl_keyboard_listener wl_keyboard_listener = {\n    .keymap      = handle_keyboard_keymap,\n    .enter       = noop,\n    .leave       = noop,\n    .key         = handle_keyboard_key,\n    .modifiers   = handle_keyboard_modifiers,\n    .repeat_info = noop,\n};\n\nstatic void handle_seat_capabilities(\n    void *data, struct wl_seat *wl_seat, uint32_t capabilities\n) {\n    struct seat *seat = data;\n    if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {\n        seat->wl_keyboard = wl_seat_get_keyboard(seat->wl_seat);\n        wl_keyboard_add_listener(\n            seat->wl_keyboard, &wl_keyboard_listener, data\n        );\n    }\n}\n\nconst struct wl_seat_listener wl_seat_listener = {\n    .name         = noop,\n    .capabilities = handle_seat_capabilities,\n};\n\nstatic void free_seats(struct wl_list *seats) {\n    struct seat *seat;\n    struct seat *tmp;\n    wl_list_for_each_safe (seat, tmp, seats, link) {\n        if (seat->wl_keyboard != NULL) {\n            wl_keyboard_destroy(seat->wl_keyboard);\n        }\n\n        if (seat->xkb_state != NULL) {\n            xkb_state_unref(seat->xkb_state);\n        }\n        if (seat->xkb_keymap != NULL) {\n            xkb_keymap_unref(seat->xkb_keymap);\n        }\n        xkb_context_unref(seat->xkb_context);\n\n        wl_seat_destroy(seat->wl_seat);\n        wl_list_remove(&seat->link);\n        free(seat);\n    }\n}\n\nstatic void free_outputs(struct wl_list *outputs) {\n    struct output *output;\n    struct output *tmp;\n    wl_list_for_each_safe (output, tmp, outputs, link) {\n        wl_output_destroy(output->wl_output);\n        zxdg_output_v1_destroy(output->xdg_output);\n        wl_list_remove(&output->link);\n        free(output->name);\n        free(output);\n    }\n}\n\nstatic struct output *find_output_from_wl_output(\n    struct wl_list *outputs, struct wl_output *wl_output\n) {\n    struct output *output;\n    wl_list_for_each (output, outputs, link) {\n        if (wl_output == output->wl_output) {\n            return output;\n        }\n    }\n\n    return NULL;\n}\n\nstatic void\nhandle_output_scale(void *data, struct wl_output *wl_output, int32_t scale) {\n    struct output *output = data;\n    output->scale         = scale;\n}\n\nstatic void handle_output_geometry(\n    void *data, struct wl_output *wl_output, int32_t x, int32_t y,\n    int32_t physical_width, int32_t physical_height, int32_t subpixel,\n    const char *make, const char *model, int32_t transform\n) {\n    struct output *output = data;\n    output->transform     = transform;\n}\n\nconst static struct wl_output_listener output_listener = {\n    .name        = noop,\n    .geometry    = handle_output_geometry,\n    .mode        = noop,\n    .scale       = handle_output_scale,\n    .description = noop,\n    .done        = noop,\n};\n\nstatic void handle_xdg_output_logical_position(\n    void *data, struct zxdg_output_v1 *xdg_output, int32_t x, int32_t y\n) {\n    struct output *output = data;\n    output->x             = x;\n    output->y             = y;\n}\n\nstatic void handle_xdg_output_logical_size(\n    void *data, struct zxdg_output_v1 *xdg_output, int32_t w, int32_t h\n) {\n    struct output *output = data;\n    output->width         = w;\n    output->height        = h;\n}\n\nstatic void handle_xdg_output_name(\n    void *data, struct zxdg_output_v1 *xdg_output, const char *name\n) {\n    struct output *output = data;\n    output->name          = strdup(name);\n}\n\nconst static struct zxdg_output_v1_listener xdg_output_listener = {\n    .logical_position = handle_xdg_output_logical_position,\n    .logical_size     = handle_xdg_output_logical_size,\n    .done             = noop,\n    .name             = handle_xdg_output_name,\n    .description      = noop,\n};\n\nstatic void load_xdg_outputs(struct state *state) {\n    struct output *output;\n    wl_list_for_each (output, &state->outputs, link) {\n        output->xdg_output = zxdg_output_manager_v1_get_xdg_output(\n            state->xdg_output_manager, output->wl_output\n        );\n        zxdg_output_v1_add_listener(\n            output->xdg_output, &xdg_output_listener, output\n        );\n    }\n\n    wl_display_roundtrip(state->wl_display);\n}\n\nstatic void enter_first_mode(struct state *state) {\n    if (state->current_mode == NO_MODE_ENTERED) {\n        if (!compute_initial_area(state, &state->initial_area)) {\n            state->running = false;\n            return;\n        }\n\n        LOG_DEBUG(\n            \"Initial area: %dx%d+%d+%d\", state->initial_area.w,\n            state->initial_area.h, state->initial_area.x, state->initial_area.y\n        );\n\n        LOG_DEBUG(\n            \"Output: %s (position: %dx%d+%d+%d, transform: %d)\",\n            state->current_output->name, state->current_output->width,\n            state->current_output->height, state->current_output->x,\n            state->current_output->y, state->current_output->transform\n        );\n\n        enter_next_mode(state, state->initial_area);\n\n        if (state->running) {\n            send_frame(state);\n        }\n    }\n}\n\nstatic void handle_surface_enter(\n    void *data, struct wl_surface *surface, struct wl_output *wl_output\n) {\n    struct state  *state = data;\n    struct output *output =\n        find_output_from_wl_output(&state->outputs, wl_output);\n    state->current_output = output;\n\n    if (state->surface_configured) {\n        enter_first_mode(state);\n    }\n}\n\nstatic const struct wl_surface_listener surface_listener = {\n    .enter                      = handle_surface_enter,\n    .leave                      = noop,\n    .preferred_buffer_transform = noop,\n    .preferred_buffer_scale     = noop,\n};\n\nstatic void handle_registry_global(\n    void *data, struct wl_registry *registry, uint32_t name,\n    const char *interface, uint32_t version\n) {\n    struct state *state = data;\n\n    if (strcmp(interface, wl_compositor_interface.name) == 0) {\n        state->wl_compositor =\n            wl_registry_bind(registry, name, &wl_compositor_interface, 4);\n\n    } else if (strcmp(interface, wl_shm_interface.name) == 0) {\n        state->wl_shm = wl_registry_bind(registry, name, &wl_shm_interface, 1);\n\n    } else if (strcmp(interface, zwlr_layer_shell_v1_interface.name) == 0) {\n        state->wl_layer_shell =\n            wl_registry_bind(registry, name, &zwlr_layer_shell_v1_interface, 2);\n\n    } else if (strcmp(interface, wl_seat_interface.name) == 0) {\n        struct seat *seat = calloc(1, sizeof(struct seat));\n        seat->wl_seat = wl_registry_bind(registry, name, &wl_seat_interface, 7);\n        seat->wl_keyboard = NULL;\n        seat->xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);\n        seat->xkb_state   = NULL;\n        seat->xkb_keymap  = NULL;\n        seat->state       = state;\n\n        wl_seat_add_listener(seat->wl_seat, &wl_seat_listener, seat);\n        wl_list_insert(&state->seats, &seat->link);\n\n    } else if (strcmp(interface, wl_output_interface.name) == 0) {\n        struct wl_output *wl_output =\n            wl_registry_bind(registry, name, &wl_output_interface, 3);\n        struct output *output = calloc(1, sizeof(struct output));\n        output->wl_output     = wl_output;\n        output->scale         = 1;\n\n        wl_output_add_listener(output->wl_output, &output_listener, output);\n        wl_list_insert(&state->outputs, &output->link);\n\n    } else if (strcmp(interface, zxdg_output_manager_v1_interface.name) == 0) {\n        state->xdg_output_manager = wl_registry_bind(\n            registry, name, &zxdg_output_manager_v1_interface, 2\n        );\n\n    } else if (strcmp(\n                   interface, zwlr_virtual_pointer_manager_v1_interface.name\n               ) == 0) {\n        state->wl_virtual_pointer_mgr = wl_registry_bind(\n            registry, name, &zwlr_virtual_pointer_manager_v1_interface, 2\n        );\n    } else if (strcmp(interface, wp_viewporter_interface.name) == 0) {\n        state->wp_viewporter =\n            wl_registry_bind(registry, name, &wp_viewporter_interface, 1);\n    } else if (strcmp(\n                   interface, wp_fractional_scale_manager_v1_interface.name\n               ) == 0) {\n        state->fractional_scale_mgr = wl_registry_bind(\n            registry, name, &wp_fractional_scale_manager_v1_interface, 1\n        );\n#if OPENCV_ENABLED\n    } else if (strcmp(interface, zwlr_screencopy_manager_v1_interface.name) ==\n               0) {\n        state->wl_screencopy_manager = wl_registry_bind(\n            registry, name, &zwlr_screencopy_manager_v1_interface, 1\n        );\n#endif\n    }\n}\n\nconst struct wl_registry_listener wl_registry_listener = {\n    .global        = handle_registry_global,\n    .global_remove = noop,\n};\n\nstatic void handle_layer_surface_configure(\n    void *data, struct zwlr_layer_surface_v1 *layer_surface, uint32_t serial,\n    uint32_t width, uint32_t height\n) {\n    struct state *state   = data;\n    state->surface_width  = width;\n    state->surface_height = height;\n    zwlr_layer_surface_v1_ack_configure(layer_surface, serial);\n\n    if (state->current_output != NULL) {\n        enter_first_mode(state);\n    } else if (!state->surface_configured) {\n        send_transparent_frame(state);\n    }\n\n    state->surface_configured = true;\n}\n\nstatic void handle_layer_surface_closed(\n    void *data, struct zwlr_layer_surface_v1 *layer_surface\n) {\n    struct state *state = data;\n    state->running      = false;\n}\n\nconst struct zwlr_layer_surface_v1_listener wl_layer_surface_listener = {\n    .configure = handle_layer_surface_configure,\n    .closed    = handle_layer_surface_closed,\n};\n\nstatic void fractional_scale_preferred(\n    void *data, struct wp_fractional_scale_v1 *fractional_scale, uint32_t scale\n) {\n    struct state *state     = data;\n    int32_t       old_scale = state->fractional_scale;\n    state->fractional_scale = scale;\n\n    if (old_scale != 0 && old_scale != scale) {\n        request_frame(state);\n    }\n}\n\nconst struct wp_fractional_scale_v1_listener fractional_scale_listener = {\n    .preferred_scale = fractional_scale_preferred,\n};\n\nstatic struct output *\nfind_output_from_rect(struct state *state, struct rect *rect) {\n    struct output *output;\n    wl_list_for_each (output, &state->outputs, link) {\n        if (output->x <= rect->x && output->y <= rect->y &&\n            output->x + output->width > rect->x &&\n            output->y + output->height > rect->y) {\n            return output;\n        }\n    }\n\n    return NULL;\n}\n\nstatic struct output *find_output_by_name(struct state *state, char *name) {\n    struct output *output;\n    wl_list_for_each (output, &state->outputs, link) {\n        if (strcmp(output->name, name) == 0) {\n            return output;\n        }\n    }\n\n    return NULL;\n}\n\nstatic void print_result(struct state *state) {\n    char click;\n    switch (state->click) {\n    case CLICK_LEFT_BTN:\n        click = 'l';\n        break;\n    case CLICK_MIDDLE_BTN:\n        click = 'm';\n        break;\n    case CLICK_RIGHT_BTN:\n        click = 'r';\n        break;\n    case CLICK_NONE:\n        click = 'n';\n    }\n\n    printf(\n        \"%dx%d+%d+%d +%d+%d %c\\n\", state->result.w, state->result.h,\n        state->result.x, state->result.y, state->current_output->x,\n        state->current_output->y, click\n    );\n}\n\nstatic void print_usage() {\n    puts(\"wl-kbptr [OPTION...]\\n\");\n\n    puts(\" -h, --help          show this help\");\n    puts(\" --help-config       show help on configuration\");\n    puts(\" -v, --version       show version\");\n    puts(\" -c, --config=FILE   use given configuration file\");\n    puts(\" -r, --restrict=AREA restrict to given area (wxh+x+y)\");\n    puts(\" -o, --option        set configuration option\");\n    puts(\" -O, --output        specify display output to use\");\n    puts(\" -p, --only-print    only print, don't move the cursor or click\");\n}\n\nstatic void print_version() {\n    printf(\"wl-kbptr %s\", VERSION);\n#if OPENCV_ENABLED\n    printf(\" (opencv)\");\n#endif\n    puts(\"\");\n}\n\nint main(int argc, char **argv) {\n    struct state state = {\n        .wl_display          = NULL,\n        .wl_registry         = NULL,\n        .wl_compositor       = NULL,\n        .wl_shm              = NULL,\n        .wl_layer_shell      = NULL,\n        .wl_surface          = NULL,\n        .wl_surface_callback = NULL,\n        .wl_layer_surface    = NULL,\n        .surface_configured  = false,\n#if OPENCV_ENABLED\n        .wl_screencopy_manager = NULL,\n#endif\n        .wp_viewporter        = NULL,\n        .fractional_scale_mgr = NULL,\n        .running              = true,\n        .fractional_scale     = 0,\n        .result               = (struct rect){-1, -1, -1, -1},\n        .initial_area         = (struct rect){-1, -1, -1, -1},\n        .home_row = (char *[]){\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"},\n        .click    = CLICK_NONE,\n    };\n\n    config_set_default(&state.config);\n    struct config_loader config_loader;\n    config_loader_init(&config_loader, &state.config);\n\n    static struct option long_options[] = {\n        {\"help\", no_argument, 0, 'h'},\n        {\"help-config\", no_argument, 0, 'H'},\n        {\"version\", no_argument, 0, 'v'},\n        {\"restrict\", required_argument, 0, 'r'},\n        {\"config\", required_argument, 0, 'c'},\n        {\"output\", required_argument, 0, 'O'},\n        {\"only-print\", no_argument, 0, 'p'},\n        {NULL, 0, NULL, 0}\n    };\n\n    int    num_cli_configs      = 0;\n    char **cli_configs          = malloc(10 * sizeof(char*));\n    int    cli_configs_len      = 10;\n    int    option_char          = 0;\n    int    option_index         = 0;\n    char  *config_filename      = NULL;\n    char  *selected_output_name = NULL;\n    bool   only_print           = false;\n    while ((option_char = getopt_long(\n                argc, argv, \"hvr:o:c:O:Rp\", long_options, &option_index\n            )) != -1) {\n        switch (option_char) {\n        case 'h':\n            print_usage();\n            config_free_values(&state.config);\n            return 0;\n\n        case 'v':\n            print_version();\n            config_free_values(&state.config);\n            return 0;\n\n        case 'r':\n            if (sscanf(\n                    optarg, \"%dx%d+%d+%d\", &state.initial_area.w,\n                    &state.initial_area.h, &state.initial_area.x,\n                    &state.initial_area.y\n                ) != 4) {\n                LOG_ERR(\"Could not parse --restrict argument.\");\n                return 1;\n            }\n            break;\n\n        case 'o':\n            if (num_cli_configs >= cli_configs_len) {\n                cli_configs_len += 10;\n                cli_configs =\n                    realloc(cli_configs, cli_configs_len * sizeof(char*));\n            }\n            cli_configs[num_cli_configs++] = optarg;\n            break;\n\n        case 'c':\n            config_filename = strdup(optarg);\n            break;\n\n        case 'H':\n            print_default_config();\n            config_free_values(&state.config);\n            return 0;\n\n        case 'O':\n            selected_output_name = strdup(optarg);\n            break;\n\n        case 'p':\n            only_print = true;\n            break;\n\n        default:\n            LOG_ERR(\"Unknown argument.\");\n            config_free_values(&state.config);\n            return 1;\n        }\n    }\n\n    int err = config_loader_load_file(&config_loader, config_filename);\n    if (err) {\n        LOG_ERR(\"Failed to read configuration file.\");\n        return 1;\n    }\n    if (config_filename != NULL) {\n        free(config_filename);\n        config_filename = NULL;\n    }\n\n    for (int i = 0; i < num_cli_configs; i++) {\n        if (config_loader_load_cli_param(&config_loader, cli_configs[i])) {\n            return 1;\n        }\n    }\n    free(cli_configs);\n    cli_configs = NULL;\n\n    if (state.config.general.home_row_keys != NULL) {\n        state.home_row = state.config.general.home_row_keys;\n    }\n\n    if (load_modes(&state, state.config.general.modes) != 0) {\n        LOG_ERR(\"Could not load modes.\");\n        return 1;\n    }\n\n    wl_list_init(&state.outputs);\n    wl_list_init(&state.seats);\n\n    state.wl_display = wl_display_connect(NULL);\n    if (state.wl_display == NULL) {\n        LOG_ERR(\"Failed to connect to Wayland compositor.\");\n        return 1;\n    }\n\n    state.wl_registry = wl_display_get_registry(state.wl_display);\n    if (state.wl_registry == NULL) {\n        LOG_ERR(\"Failed to get Wayland registry.\");\n        return 1;\n    }\n\n    wl_registry_add_listener(state.wl_registry, &wl_registry_listener, &state);\n    wl_display_roundtrip(state.wl_display);\n\n    if (state.wl_compositor == NULL) {\n        LOG_ERR(\"Failed to get wl_compositor object.\");\n        return 1;\n    }\n\n    if (state.wl_shm == NULL) {\n        LOG_ERR(\"Failed to get wl_shm object.\");\n        return 1;\n    }\n\n    if (state.wl_layer_shell == NULL) {\n        LOG_ERR(\"Failed to get zwlr_layer_shell_v1 object.\");\n        return 1;\n    }\n\n    if (state.wl_virtual_pointer_mgr == NULL && !only_print) {\n        LOG_ERR(\"Failed to get wlr_virtual_pointer_manager_v1 object.\");\n        return 1;\n    }\n\n    if (state.xdg_output_manager == NULL) {\n        LOG_ERR(\"Failed to get xdg_output_manager object.\");\n        return 1;\n    }\n\n    if (state.wp_viewporter == NULL) {\n        LOG_ERR(\"Failed to get wp_viewporter object.\");\n        return 1;\n    }\n\n    load_xdg_outputs(&state);\n\n    // This round trip should load the keymap which is needed to determine the\n    // home row keys.\n    wl_display_roundtrip(state.wl_display);\n\n    if (selected_output_name) {\n        state.current_output =\n            find_output_by_name(&state, selected_output_name);\n\n        if (!state.current_output) {\n            LOG_ERR(\"Could not find output '%s'.\", selected_output_name);\n            return 1;\n        }\n\n        free(selected_output_name);\n        selected_output_name = NULL;\n    } else if (state.initial_area.w != -1) {\n        state.current_output =\n            find_output_from_rect(&state, &state.initial_area);\n\n        if (!state.current_output) {\n            LOG_ERR(\"Could not find output containing given area.\");\n            return 1;\n        }\n\n        state.initial_area.x -= state.current_output->x;\n        state.initial_area.y -= state.current_output->y;\n    }\n\n    surface_buffer_pool_init(&state.surface_buffer_pool);\n\n    state.wl_surface = wl_compositor_create_surface(state.wl_compositor);\n    wl_surface_add_listener(state.wl_surface, &surface_listener, &state);\n    state.wl_layer_surface = zwlr_layer_shell_v1_get_layer_surface(\n        state.wl_layer_shell, state.wl_surface,\n        state.current_output == NULL ? NULL : state.current_output->wl_output,\n        ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY, \"selection\"\n    );\n    zwlr_layer_surface_v1_add_listener(\n        state.wl_layer_surface, &wl_layer_surface_listener, &state\n    );\n    zwlr_layer_surface_v1_set_exclusive_zone(state.wl_layer_surface, -1);\n    zwlr_layer_surface_v1_set_anchor(\n        state.wl_layer_surface, ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT |\n                                    ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT |\n                                    ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP |\n                                    ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM\n    );\n    zwlr_layer_surface_v1_set_keyboard_interactivity(\n        state.wl_layer_surface, true\n    );\n\n    struct wp_fractional_scale_v1 *fractional_scale = NULL;\n    if (state.fractional_scale_mgr) {\n        fractional_scale = wp_fractional_scale_manager_v1_get_fractional_scale(\n            state.fractional_scale_mgr, state.wl_surface\n        );\n        wp_fractional_scale_v1_add_listener(\n            fractional_scale, &fractional_scale_listener, &state\n        );\n    }\n\n    state.wp_viewport =\n        wp_viewporter_get_viewport(state.wp_viewporter, state.wl_surface);\n\n    struct wl_region *wl_region =\n        wl_compositor_create_region(state.wl_compositor);\n    wl_region_add(wl_region, 0, 0, 0, 0);\n    wl_surface_set_input_region(state.wl_surface, wl_region);\n\n    wl_surface_commit(state.wl_surface);\n    while (state.running && wl_display_dispatch(state.wl_display)) {}\n\n    wp_viewport_destroy(state.wp_viewport);\n\n    zwlr_layer_surface_v1_destroy(state.wl_layer_surface);\n    wl_surface_destroy(state.wl_surface);\n    wl_region_destroy(wl_region);\n\n    surface_buffer_pool_destroy(&state.surface_buffer_pool);\n    wl_display_roundtrip(state.wl_display);\n\n    int status_code = 0;\n    if (state.result.x != -1) {\n        print_result(&state);\n        if (!only_print) {\n            move_pointer(\n                &state, state.result.x + state.result.w / 2,\n                state.result.y + state.result.h / 2, state.click\n            );\n        }\n    } else {\n        status_code = state.config.general.cancellation_status_code;\n    }\n\n    if (state.wl_virtual_pointer_mgr != NULL) {\n        zwlr_virtual_pointer_manager_v1_destroy(state.wl_virtual_pointer_mgr);\n    }\n\n    free_seats(&state.seats);\n    free_outputs(&state.outputs);\n\n    zxdg_output_manager_v1_destroy(state.xdg_output_manager);\n\n    if (state.fractional_scale_mgr) {\n        wp_fractional_scale_v1_destroy(fractional_scale);\n        wp_fractional_scale_manager_v1_destroy(state.fractional_scale_mgr);\n    }\n\n    wp_viewporter_destroy(state.wp_viewporter);\n    wl_shm_destroy(state.wl_shm);\n    wl_compositor_destroy(state.wl_compositor);\n    wl_registry_destroy(state.wl_registry);\n    zwlr_layer_shell_v1_destroy(state.wl_layer_shell);\n\n#if OPENCV_ENABLED\n    if (state.wl_screencopy_manager) {\n        zwlr_screencopy_manager_v1_destroy(state.wl_screencopy_manager);\n    }\n#endif\n\n    wl_display_disconnect(state.wl_display);\n\n    config_free_values(&state.config);\n    free_mode_states(&state);\n\n#if DEBUG\n    cairo_debug_reset_static_data();\n#endif\n\n    return status_code;\n}\n"
  },
  {
    "path": "src/mode.c",
    "content": "#include \"mode.h\"\n\n#include \"log.h\"\n\n#include <stdlib.h>\n#include <string.h>\n\nextern struct mode_interface tile_mode_interface;\nextern struct mode_interface floating_mode_interface;\nextern struct mode_interface bisect_mode_interface;\nextern struct mode_interface split_mode_interface;\nextern struct mode_interface click_mode_interface;\n\nstruct mode_interface *mode_interfaces[] = {\n    &tile_mode_interface,  &floating_mode_interface, &bisect_mode_interface,\n    &split_mode_interface, &click_mode_interface,    NULL,\n};\n\nstatic struct mode_interface *find_mode_interface_by_name(char *name) {\n    struct mode_interface **curr_mode_interface = mode_interfaces;\n    while (*curr_mode_interface != NULL) {\n        if (strcmp(name, (*curr_mode_interface)->name) == 0) {\n            return *curr_mode_interface;\n        }\n\n        curr_mode_interface++;\n    }\n\n    return NULL;\n}\n\nint load_modes(struct state *state, char *modes) {\n    char buf[strlen(modes) + 1];\n    strcpy(buf, modes);\n\n    int mode_i = 0;\n\n    static const char *delim = \",\";\n    char              *tok   = strtok(buf, delim);\n    while (tok != NULL) {\n        if (mode_i >= MAX_NUM_MODES) {\n            LOG_ERR(\"Only %d modes can be specified.\", MAX_NUM_MODES);\n            return 1;\n        }\n\n        struct mode_interface *mode_interface =\n            find_mode_interface_by_name(tok);\n        if (mode_interface == NULL) {\n            LOG_ERR(\"Unknown mode '%s'.\", tok);\n            return 2;\n        }\n\n        state->mode_interfaces[mode_i++] = mode_interface;\n        tok                              = strtok(NULL, delim);\n    }\n\n    if (mode_i < MAX_NUM_MODES) {\n        state->mode_interfaces[mode_i] = NULL;\n    }\n\n    state->current_mode = NO_MODE_ENTERED;\n    return 0;\n}\n\nvoid enter_next_mode(struct state *state, struct rect area) {\n    if (has_last_mode_returned(state)) {\n        return;\n    }\n\n    state->current_mode += 1;\n\n    if (has_last_mode_returned(state)) {\n        memcpy(&state->result, &area, sizeof(struct rect));\n        return;\n    }\n\n    state->mode_states[state->current_mode] =\n        state->mode_interfaces[state->current_mode]->enter(state, area);\n}\n\nbool has_last_mode_returned(struct state *state) {\n    return state->current_mode >= MAX_NUM_MODES ||\n           state->mode_interfaces[state->current_mode] == NULL;\n}\n\nbool reenter_prev_mode(struct state *state) {\n    if (state->current_mode <= 0) {\n        return false;\n    }\n\n    void *current_mode_state = state->mode_states[state->current_mode];\n    if (current_mode_state != NULL) {\n        state->mode_interfaces[state->current_mode]->free(current_mode_state);\n    }\n\n    state->current_mode--;\n    state->mode_interfaces[state->current_mode]->reenter(\n        state, state->mode_states[state->current_mode]\n    );\n\n    return true;\n}\n\nvoid free_mode_states(struct state *state) {\n    if (state->current_mode == NO_MODE_ENTERED) {\n        return;\n    }\n\n    for (int i = 0; i <= state->current_mode; i++) {\n        if (state->mode_interfaces[i] == NULL ||\n            state->mode_states[i] == NULL) {\n            return;\n        }\n\n        state->mode_interfaces[i]->free(state->mode_states[i]);\n    }\n}\n\nbool mode_handle_key(struct state *state, xkb_keysym_t sym, char *text) {\n    if (has_last_mode_returned(state)) {\n        return false;\n    }\n\n    return state->mode_interfaces[state->current_mode]->key(\n        state, state->mode_states[state->current_mode], sym, text\n    );\n}\nvoid mode_render(struct state *state, cairo_t *cairo) {\n    if (has_last_mode_returned(state)) {\n        return;\n    }\n\n    return state->mode_interfaces[state->current_mode]->render(\n        state, state->mode_states[state->current_mode], cairo\n    );\n}\n"
  },
  {
    "path": "src/mode.h",
    "content": "#ifndef __MODE_H_INCLUDED__\n#define __MODE_H_INCLUDED__\n\n#include \"state.h\"\n\n#include <cairo.h>\n#include <stdbool.h>\n#include <xkbcommon/xkbcommon.h>\n\nstruct mode_interface {\n    char *name;\n    void *(*enter)(struct state *, struct rect area);\n    void (*reenter)(struct state *, void *mode_state);\n    bool (*key)(struct state *, void *mode_state, xkb_keysym_t, char *text);\n    void (*render)(struct state *, void *mode_state, cairo_t *);\n    void (*free)(void *mode_state);\n};\n\nextern struct mode_interface *mode_interfaces[];\n\n/**\n * Load modes from given coma seperated list of mode names.\n * Returns 0 on success.\n */\nint load_modes(struct state *, char *);\n\nvoid enter_next_mode(struct state *, struct rect area);\nbool has_last_mode_returned(struct state *);\nbool reenter_prev_mode(struct state *);\nvoid free_mode_states(struct state *);\nbool mode_handle_key(struct state *, xkb_keysym_t, char *text);\nvoid mode_render(struct state *, cairo_t *);\n\n#endif\n"
  },
  {
    "path": "src/mode_bisect.c",
    "content": "#include \"config.h\"\n#include \"mode.h\"\n#include \"state.h\"\n#include \"utils.h\"\n#include \"utils_cairo.h\"\n#include \"utils_wayland.h\"\n\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define DIVIDE_8_RATIO 1.8\n\nenum bisect_division {\n    /*\n     * The tiling mode should give us areas that are twice as wide as they are\n     * tall. In this case, we want to divide the area in 8 instead of 4 as to\n     * then get equal square areas.\n     *\n     *  +--+--+--+--+\n     *  | 0| 1| 2| 3|\n     *  +--+--+--+--+\n     *  | 4| 5| 6| 7|\n     *  +--+--+--+--+\n     */\n    DIVISION_8 = 0,\n    /*\n     * After the first pass, we should only get mostly square areas.\n     *\n     *  +--+--+\n     *  | 0| 1|\n     *  +--+--+\n     *  | 2| 3|\n     *  +--+--+\n     */\n    DIVISION_4,\n    /*\n     * Once we have divide the areas enough times, we will end up with a line,\n     * i.e. a area with a width or height of a single pixel. In this case we\n     * divide the area in two.\n     *\n     *    0  1\n     *  +--+--+\n     */\n    DIVISION_HORIZONTAL,\n    /*\n     *    +\n     *    | 0\n     *    +\n     *    | 1\n     *    +\n     */\n    DIVISION_VERTICAL,\n    /*\n     * Given enough divisions, we should end up with a single pixel.\n     *\n     *    +\n     */\n    UNDIVIDABLE,\n};\n\nstatic void\nbisect_mode_move_pointer(struct state *state, struct bisect_mode_state *ms) {\n    struct rect *r = &ms->areas[ms->current];\n    move_pointer(state, r->x + r->w / 2, r->y + r->h / 2, CLICK_NONE);\n}\n\nvoid *bisect_mode_enter(struct state *state, struct rect area) {\n    struct bisect_mode_state *ms = malloc(sizeof(*ms));\n    ms->areas[0]                 = area;\n    ms->current                  = 0;\n\n    ms->label_font_face = cairo_toy_font_face_create(\n        state->config.mode_bisect.label_font_family, CAIRO_FONT_SLANT_NORMAL,\n        CAIRO_FONT_WEIGHT_NORMAL\n    );\n\n    bisect_mode_move_pointer(state, ms);\n\n    return ms;\n}\n\nstatic enum bisect_division determine_division(struct rect *area) {\n    if (area->w <= 1 && area->h <= 1) {\n        return UNDIVIDABLE;\n    }\n\n    if (area->w <= 1) {\n        return DIVISION_VERTICAL;\n    }\n\n    if (area->h <= 1) {\n        return DIVISION_HORIZONTAL;\n    }\n\n    return area->w > area->h * DIVIDE_8_RATIO ? DIVISION_8 : DIVISION_4;\n}\n\nstruct division_interface {\n    void (*render)(\n        enum bisect_division, struct state *, struct bisect_mode_state *ms,\n        cairo_t *\n    );\n\n    // `idx_to_sub_area` returns the sub-area indicated by the given index in\n    // `rect` while also returning true. If the index does map to a sub-area,\n    // `rect` is left unchanged and it returns false.\n    bool (*idx_to_sub_area)(\n        enum bisect_division, int idx, struct rect *current_area,\n        struct rect *new_area\n    );\n};\n\nstatic void division_4_or_8_render(\n    enum bisect_division division, struct state *state,\n    struct bisect_mode_state *ms, cairo_t *cairo\n) {\n    struct mode_bisect_config *config = &state->config.mode_bisect;\n    struct rect               *area   = &ms->areas[ms->current];\n\n    bool divide_8 = division == DIVISION_8;\n\n    const int sub_area_columns = divide_8 ? 4 : 2;\n    const int sub_area_rows    = 2;\n\n    const int sub_area_width      = area->w / sub_area_columns;\n    const int sub_area_width_off  = area->w % sub_area_columns;\n    const int sub_area_height     = area->h / sub_area_rows;\n    const int sub_area_height_off = area->h % sub_area_rows;\n\n    const bool inner_labels = config->label_font_size < sub_area_height;\n    const int  font_size =\n        max(min(512, sub_area_height * .9), config->label_font_size);\n\n    cairo_set_font_face(cairo, ms->label_font_face);\n    cairo_set_font_size(cairo, font_size);\n\n    for (int i = 0; i < sub_area_columns; i++) {\n        for (int j = 0; j < sub_area_rows; j++) {\n            const int x =\n                area->x + i * sub_area_width + min(i, sub_area_width_off);\n            const int y =\n                area->y + j * sub_area_height + min(j, sub_area_height_off);\n            const int w = sub_area_width + (i < sub_area_width_off ? 1 : 0);\n            const int h = sub_area_height + (j < sub_area_height_off ? 1 : 0);\n\n            cairo_set_source_u32(\n                cairo, (i + j) % 2 == 0 ? config->even_area_bg_color\n                                        : config->odd_area_bg_color\n            );\n            cairo_rectangle(cairo, x, y, w, h);\n            cairo_fill(cairo);\n\n            cairo_set_line_width(cairo, 1);\n            cairo_rectangle(cairo, x + .5, y + .5, w - 1, h - 1);\n            cairo_set_source_u32(\n                cairo, (i + j) % 2 == 0 ? config->even_area_border_color\n                                        : config->odd_area_border_color\n            );\n            cairo_stroke(cairo);\n\n            if (inner_labels) {\n                cairo_set_source_u32(cairo, config->label_color);\n                char *label = state->home_row[i + j * sub_area_columns];\n                cairo_text_extents_t te;\n                cairo_text_extents(cairo, label, &te);\n                cairo_move_to(\n                    cairo, x + (int)(w / 2) - (int)(te.width / 2),\n                    y + (h + te.height) / 2\n                );\n                cairo_show_text(cairo, label);\n            }\n        }\n    }\n\n    if (!inner_labels) {\n        cairo_set_font_size(cairo, config->label_font_size);\n        cairo_set_source_u32(cairo, config->label_color);\n        char label[64];\n\n        // Top label\n        if (divide_8) {\n            snprintf(\n                label, sizeof(label), \"%s %s %s %s\", state->home_row[0],\n                state->home_row[1], state->home_row[2], state->home_row[3]\n            );\n        } else {\n            snprintf(\n                label, sizeof(label), \"%s %s\", state->home_row[0],\n                state->home_row[1]\n            );\n        }\n\n        cairo_text_extents_t te;\n        cairo_text_extents(cairo, label, &te);\n        cairo_move_to(\n            cairo, area->x + (int)(area->w / 2) - (int)(te.width / 2),\n            area->y - config->label_padding\n        );\n        cairo_show_text(cairo, label);\n\n        // Bottom label\n        if (divide_8) {\n            snprintf(\n                label, sizeof(label), \"%s %s %s %s\", state->home_row[4],\n                state->home_row[5], state->home_row[6], state->home_row[7]\n            );\n        } else {\n            snprintf(\n                label, sizeof(label), \"%s %s\", state->home_row[2],\n                state->home_row[3]\n            );\n        }\n\n        cairo_text_extents(cairo, label, &te);\n        cairo_move_to(\n            cairo, area->x + (int)(area->w / 2) - (int)(te.width / 2),\n            area->y + area->h + te.height + config->label_padding\n        );\n        cairo_show_text(cairo, label);\n    }\n}\n\nstatic bool division_4_or_8_idx_to_rect(\n    enum bisect_division division, int idx, struct rect *area, struct rect *rect\n) {\n    bool divide_8 = division == DIVISION_8;\n    if (!divide_8 && idx >= 4) {\n        return false;\n    }\n\n    const int sub_area_columns = divide_8 ? 4 : 2;\n    const int sub_area_rows    = 2;\n\n    const int sub_area_width      = area->w / sub_area_columns;\n    const int sub_area_width_off  = area->w % sub_area_columns;\n    const int sub_area_height     = area->h / sub_area_rows;\n    const int sub_area_height_off = area->h % sub_area_rows;\n\n    const int i = idx % sub_area_columns;\n    const int j = idx / sub_area_columns;\n\n    rect->x = area->x + i * sub_area_width + min(i, sub_area_width_off);\n    rect->y = area->y + j * sub_area_height + min(j, sub_area_height_off);\n    rect->w = sub_area_width + (i < sub_area_width_off ? 1 : 0);\n    rect->h = sub_area_height + (j < sub_area_height_off ? 1 : 0);\n\n    return true;\n}\n\nstatic void division_horizontal_render(\n    enum bisect_division division, struct state *state,\n    struct bisect_mode_state *ms, cairo_t *cairo\n) {\n    struct mode_bisect_config *config = &state->config.mode_bisect;\n    struct rect               *area   = &ms->areas[ms->current];\n\n    cairo_set_source_u32(cairo, config->even_area_border_color);\n    cairo_set_line_width(cairo, 1);\n    cairo_move_to(cairo, area->x + .5, area->y + .5);\n    cairo_line_to(cairo, area->x + (int)(area->w / 2) - .5, area->y + .5);\n    cairo_stroke(cairo);\n\n    cairo_set_source_u32(cairo, config->odd_area_border_color);\n    cairo_move_to(cairo, area->x + (int)(area->w / 2) + .5, area->y + .5);\n    cairo_line_to(cairo, area->x + area->w + .5, area->y + .5);\n    cairo_stroke(cairo);\n\n    cairo_set_source_u32(cairo, config->label_color);\n\n    cairo_text_extents_t te;\n    cairo_text_extents(cairo, state->home_row[0], &te);\n    cairo_move_to(\n        cairo, area->x - config->label_padding - te.width,\n        area->y + te.height / 2\n    );\n    cairo_show_text(cairo, state->home_row[0]);\n\n    cairo_text_extents(cairo, state->home_row[1], &te);\n    cairo_move_to(\n        cairo, area->x + area->w + config->label_padding,\n        area->y + te.height / 2\n    );\n    cairo_show_text(cairo, state->home_row[1]);\n}\n\nstatic bool division_horizontal_idx_to_rect(\n    enum bisect_division division, int idx, struct rect *area, struct rect *rect\n) {\n    if (idx > 1) {\n        return false;\n    }\n\n    rect->x = area->x + idx * area->w / 2;\n    rect->y = area->y;\n    rect->w = area->w / 2;\n    rect->h = area->h;\n\n    return true;\n}\n\nstatic void division_vertical_render(\n    enum bisect_division division, struct state *state,\n    struct bisect_mode_state *ms, cairo_t *cairo\n) {\n\n    struct mode_bisect_config *config = &state->config.mode_bisect;\n    struct rect               *area   = &ms->areas[ms->current];\n\n    cairo_set_source_u32(cairo, config->even_area_border_color);\n    cairo_set_line_width(cairo, 1);\n    cairo_move_to(cairo, area->x + .5, area->y + .5);\n    cairo_line_to(cairo, area->x + .5, area->y - .5 + (int)(area->h / 2));\n    cairo_stroke(cairo);\n\n    cairo_set_source_u32(cairo, config->odd_area_border_color);\n    cairo_move_to(cairo, area->x + .5, area->y + .5 + (int)(area->h / 2));\n    cairo_line_to(cairo, area->x + .5, area->y + .5 + area->h);\n    cairo_stroke(cairo);\n\n    cairo_set_source_u32(cairo, config->label_color);\n\n    cairo_text_extents_t te;\n    cairo_text_extents(cairo, state->home_row[0], &te);\n    cairo_move_to(\n        cairo, area->x - te.width / 2, area->y - config->label_padding\n    );\n    cairo_show_text(cairo, state->home_row[0]);\n\n    cairo_text_extents(cairo, state->home_row[1], &te);\n    cairo_move_to(\n        cairo, area->x - te.width / 2,\n        area->y + area->h + config->label_padding + te.height\n    );\n    cairo_show_text(cairo, state->home_row[1]);\n}\n\nstatic bool division_vertical_idx_to_rect(\n    enum bisect_division division, int idx, struct rect *area, struct rect *rect\n) {\n    if (idx > 1) {\n        return false;\n    }\n\n    rect->x = area->x;\n    rect->y = area->y + idx * area->h / 2;\n    rect->w = area->w;\n    rect->h = area->h / 2;\n\n    return true;\n}\n\nstatic void undividable_render(\n    enum bisect_division division, struct state *state,\n    struct bisect_mode_state *ms, cairo_t *cairo\n) {\n    struct mode_bisect_config *config = &state->config.mode_bisect;\n    struct rect               *area   = &ms->areas[ms->current];\n\n    cairo_set_source_u32(cairo, config->pointer_color);\n    cairo_arc(\n        cairo, area->x + .5, area->y + .5, config->pointer_size / 4., 0,\n        2 * M_PI\n    );\n    cairo_set_line_width(cairo, 1);\n    cairo_stroke(cairo);\n}\n\nstatic bool undividable_select_idx() {\n    return false;\n}\n\nstatic const struct division_interface division_interfaces[] = {\n    [DIVISION_8] =\n        {.render          = division_4_or_8_render,\n         .idx_to_sub_area = division_4_or_8_idx_to_rect},\n    [DIVISION_4] =\n        {.render          = division_4_or_8_render,\n         .idx_to_sub_area = division_4_or_8_idx_to_rect},\n    [DIVISION_VERTICAL] =\n        {.render          = division_vertical_render,\n         .idx_to_sub_area = division_vertical_idx_to_rect},\n    [DIVISION_HORIZONTAL] =\n        {.render          = division_horizontal_render,\n         .idx_to_sub_area = division_horizontal_idx_to_rect},\n    [UNDIVIDABLE] = {\n        .render = undividable_render, .idx_to_sub_area = undividable_select_idx\n    },\n};\n\nstatic void\nbisect_mode_render(struct state *state, void *mode_state, cairo_t *cairo) {\n    struct mode_bisect_config *config = &state->config.mode_bisect;\n    struct bisect_mode_state  *ms     = mode_state;\n    struct rect               *area   = &ms->areas[ms->current];\n\n    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);\n    cairo_set_source_u32(cairo, config->unselectable_bg_color);\n    cairo_paint(cairo);\n\n    cairo_set_source_u32(cairo, config->history_border_color);\n    cairo_set_line_width(cairo, 1);\n\n    for (int i = 0; i < ms->current; i++) {\n        struct rect *area = &ms->areas[i];\n        cairo_rectangle(\n            cairo, area->x + .5, area->y + .5, area->w - 1, area->h - 1\n        );\n        cairo_stroke(cairo);\n    }\n\n    if (ms->current < BISECT_MAX_HISTORY) {\n        enum bisect_division division = determine_division(area);\n        division_interfaces[division].render(division, state, ms, cairo);\n    }\n\n    cairo_set_line_width(cairo, 1);\n    cairo_set_source_u32(cairo, config->pointer_color);\n    const int pointer_x = area->x + area->w / 2;\n    const int pointer_y = area->y + area->h / 2;\n    cairo_move_to(\n        cairo, pointer_x + .5, pointer_y - (int)(config->pointer_size / 2) + .5\n    );\n    cairo_line_to(\n        cairo, pointer_x + .5, pointer_y + (int)(config->pointer_size / 2) + .5\n    );\n    cairo_stroke(cairo);\n    cairo_move_to(\n        cairo, pointer_x - (int)(config->pointer_size / 2) + .5, pointer_y + .5\n    );\n    cairo_line_to(\n        cairo, pointer_x + (int)(config->pointer_size / 2) + .5, pointer_y + .5\n    );\n    cairo_stroke(cairo);\n}\n\nstatic bool bisect_mode_key(\n    struct state *state, void *mode_state, xkb_keysym_t keysym, char *text\n) {\n    struct bisect_mode_state *ms = mode_state;\n\n    switch (keysym) {\n    case XKB_KEY_Escape:\n        state->running = false;\n        break;\n\n    case XKB_KEY_Return:\n    case XKB_KEY_space:\n        enter_next_mode(state, ms->areas[ms->current]);\n        return true;\n\n    case XKB_KEY_BackSpace:\n        if (ms->current > 0) {\n            ms->current--;\n        } else {\n            reenter_prev_mode(state);\n        }\n        return true;\n\n    default:\n        if (ms->current + 1 >= BISECT_MAX_HISTORY) {\n            return false;\n        }\n\n        struct rect         *area     = &ms->areas[ms->current];\n        enum bisect_division division = determine_division(area);\n\n        int matched_i = find_str(state->home_row, HOME_ROW_LEN_WITH_BTN, text);\n        if (matched_i < 0) {\n            return false;\n        }\n\n        if (matched_i >= HOME_ROW_LEN) {\n            switch (matched_i) {\n            case HOME_ROW_LEFT_CLICK:\n                state->click = CLICK_LEFT_BTN;\n                break;\n            case HOME_ROW_RIGHT_CLICK:\n                state->click = CLICK_RIGHT_BTN;\n                break;\n            case HOME_ROW_MIDDLE_CLICK:\n                state->click = CLICK_MIDDLE_BTN;\n                break;\n            }\n\n            enter_next_mode(state, ms->areas[ms->current]);\n            return false;\n        }\n\n        if (division == UNDIVIDABLE) {\n            return false;\n        }\n\n        struct rect *new_area = &ms->areas[ms->current + 1];\n        if (division_interfaces[division].idx_to_sub_area(\n                division, matched_i, area, new_area\n            )) {\n            ms->current++;\n            bisect_mode_move_pointer(state, ms);\n            return true;\n        }\n    }\n\n    return false;\n}\n\nvoid bisect_mode_reenter(struct state *state, void *mode_state) {\n    bisect_mode_move_pointer(state, mode_state);\n}\nvoid bisect_mode_free(void *mode_state) {\n    struct bisect_mode_state *ms = mode_state;\n    cairo_font_face_destroy(ms->label_font_face);\n    free(ms);\n}\n\nstruct mode_interface bisect_mode_interface = {\n    .name    = \"bisect\",\n    .enter   = bisect_mode_enter,\n    .reenter = bisect_mode_reenter,\n    .key     = bisect_mode_key,\n    .render  = bisect_mode_render,\n    .free    = bisect_mode_free,\n};\n"
  },
  {
    "path": "src/mode_click.c",
    "content": "#include \"mode.h\"\n\nstatic void *click_mode_enter(struct state *state, struct rect area) {\n    state->click = state->config.mode_click.button;\n    enter_next_mode(state, area);\n    return NULL;\n}\n\nstatic void click_mode_reenter(struct state *state, void *mode_state) {\n    reenter_prev_mode(state);\n}\n\nstatic bool click_mode_key(\n    struct state *state, void *mode_state, xkb_keysym_t keysym, char *text\n) {\n    return false;\n}\n\nstatic void\nclick_mode_render(struct state *state, void *mode_state, cairo_t *cairo) {}\n\nstatic void click_mode_free(void *mode_state) {}\n\nstruct mode_interface click_mode_interface = {\n    .name    = \"click\",\n    .enter   = click_mode_enter,\n    .reenter = click_mode_reenter,\n    .key     = click_mode_key,\n    .render  = click_mode_render,\n    .free    = click_mode_free,\n};\n"
  },
  {
    "path": "src/mode_floating.c",
    "content": "#include \"config.h\"\n#include \"log.h\"\n#include \"mode.h\"\n#include \"screencopy.h\"\n#include \"state.h\"\n#include \"target_detection.h\"\n#include \"utils.h\"\n#include \"utils_cairo.h\"\n\n#include <cairo.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <xkbcommon/xkbcommon.h>\n\n#define MIN_SUB_AREA_SIZE (25 * 50)\n\nstatic void get_areas_from_stdin(struct floating_mode_state *ms) {\n    size_t       areas_cap   = 256;\n    struct rect *areas       = malloc(sizeof(struct rect) * areas_cap);\n    int          areas_count = 0;\n    char        *buf         = NULL;\n    size_t       buf_n       = 0;\n\n    while (getline(&buf, &buf_n, stdin) >= 0) {\n        if (areas_count >= areas_cap) {\n            areas_cap *= 2;\n            areas      = realloc(areas, sizeof(struct rect) * areas_cap);\n        }\n\n        struct rect *curr_area     = &areas[areas_count];\n        int          matched_count = sscanf(\n            buf, \"%dx%d+%d+%d\", &curr_area->w, &curr_area->h, &curr_area->x,\n            &curr_area->y\n        );\n        if (matched_count < 4) {\n            LOG_ERR(\"Error parsing '%s'. Skipping.\", buf);\n            continue;\n        }\n\n        areas_count++;\n    }\n\n    free(buf);\n\n    LOG_INFO(\"Got %d areas.\", areas_count);\n\n    ms->areas     = areas;\n    ms->num_areas = areas_count;\n}\n\n#if OPENCV_ENABLED\n\nstatic void get_area_from_screenshot(\n    struct state *state, struct floating_mode_state *ms, struct rect area\n) {\n    // This is so that we don't capture window borders.\n    area.x += 1;\n    area.y += 1;\n    area.h -= 2;\n    area.w -= 2;\n\n    struct scrcpy_buffer    *scrcpy_buffer = query_screenshot(state, area);\n    enum wl_output_transform output_transform =\n        state->current_output->transform;\n    ms->num_areas = compute_target_from_img_buffer(\n        scrcpy_buffer->data, scrcpy_buffer->height, scrcpy_buffer->width,\n        scrcpy_buffer->stride, scrcpy_buffer->format, output_transform, area,\n        &ms->areas\n    );\n    destroy_scrcpy_buffer(scrcpy_buffer);\n}\n\n#endif\n\nvoid *floating_mode_enter(struct state *state, struct rect area) {\n    struct floating_mode_state *ms = malloc(sizeof(*ms));\n\n    ms->label_symbols =\n        label_symbols_from_str(state->config.mode_floating.label_symbols);\n\n    if (ms->label_symbols == NULL) {\n        ms->areas           = NULL;\n        ms->label_selection = NULL;\n        state->running      = false;\n        return ms;\n    }\n\n    switch (state->config.mode_floating.source) {\n    case FLOATING_MODE_SOURCE_STDIN:\n        get_areas_from_stdin(ms);\n        break;\n    case FLOATING_MODE_SOURCE_DETECT:\n#if OPENCV_ENABLED\n        get_area_from_screenshot(state, ms, area);\n#else\n        // This should not happen as the value is checked when loading the\n        // configuration.\n        LOG_ERR(\"Binary not built with OpenCV support.\");\n        exit(1);\n#endif\n        break;\n    }\n\n    ms->label_selection = label_selection_new(ms->label_symbols, ms->num_areas);\n\n    ms->label_font_face = cairo_toy_font_face_create(\n        state->config.mode_floating.label_font_family, CAIRO_FONT_SLANT_NORMAL,\n        CAIRO_FONT_WEIGHT_NORMAL\n    );\n\n    return ms;\n}\n\nvoid floating_mode_reenter(struct state *state, void *mode_state) {\n    struct floating_mode_state *ms = mode_state;\n    label_selection_back(ms->label_selection);\n}\n\nstatic bool floating_mode_key(\n    struct state *state, void *mode_state, xkb_keysym_t keysym, char *text\n) {\n    struct floating_mode_state *ms = mode_state;\n\n    switch (keysym) {\n    case XKB_KEY_BackSpace:\n        return label_selection_back(ms->label_selection) != 0;\n\n    case XKB_KEY_Escape:\n        state->running = false;\n        break;\n    default:;\n        int symbol_idx = label_symbols_find_idx(ms->label_symbols, text);\n        if (symbol_idx < 0) {\n            return false;\n        }\n\n        label_selection_append(ms->label_selection, symbol_idx);\n\n        int idx = label_selection_to_idx(ms->label_selection);\n        if (idx >= 0) {\n            enter_next_mode(state, ms->areas[idx]);\n        }\n        return true;\n    }\n\n    return false;\n}\n\nvoid floating_mode_render(\n    struct state *state, void *mode_state, cairo_t *cairo\n) {\n    struct floating_mode_state  *ms     = mode_state;\n    struct mode_floating_config *config = &state->config.mode_floating;\n\n    label_selection_t *curr_label =\n        label_selection_new(ms->label_symbols, ms->num_areas);\n    label_selection_set_from_idx(curr_label, 0);\n\n    int  label_str_max_len = label_selection_str_max_len(curr_label) + 1;\n    char label_selected_str[label_str_max_len];\n    char label_unselected_str[label_str_max_len];\n\n    cairo_set_font_face(cairo, ms->label_font_face);\n\n    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);\n    cairo_set_source_u32(cairo, config->unselectable_bg_color);\n    cairo_paint(cairo);\n\n    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);\n    for (int i = 0; i < ms->num_areas; i++) {\n        const bool selectable =\n            label_selection_is_included(curr_label, ms->label_selection);\n\n        if (selectable) {\n            struct rect a = ms->areas[i];\n            cairo_set_source_rgba(cairo, 0, 0, 0, 0);\n            cairo_rectangle(cairo, a.x, a.y, a.w, a.h);\n            cairo_fill(cairo);\n        }\n\n        label_selection_incr(curr_label);\n    }\n\n    label_selection_set_from_idx(curr_label, 0);\n    for (int i = 0; i < ms->num_areas; i++) {\n        struct rect a = ms->areas[i];\n\n        const bool selectable =\n            label_selection_is_included(curr_label, ms->label_selection);\n\n        if (selectable) {\n            cairo_set_operator(cairo, CAIRO_OPERATOR_OVER);\n            cairo_set_source_u32(cairo, config->selectable_bg_color);\n            cairo_rectangle(cairo, a.x, a.y, a.w, a.h);\n            cairo_fill(cairo);\n\n            cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);\n            cairo_set_source_u32(cairo, config->selectable_border_color);\n            cairo_rectangle(cairo, a.x + .5, a.y + .5, a.w - 1, a.h - 1);\n            cairo_set_line_width(cairo, 1);\n            cairo_stroke(cairo);\n\n            cairo_set_font_size(\n                cairo, compute_relative_font_size(&config->label_font_size, a.h)\n            );\n            cairo_text_extents_t te_all;\n            label_selection_str(curr_label, label_selected_str);\n            cairo_text_extents(cairo, label_selected_str, &te_all);\n\n            label_selection_str_split(\n                curr_label, label_selected_str, label_unselected_str,\n                ms->label_selection->next\n            );\n\n            cairo_text_extents_t te_selected, te_unselected;\n            cairo_text_extents(cairo, label_selected_str, &te_selected);\n            cairo_text_extents(cairo, label_unselected_str, &te_unselected);\n\n            cairo_move_to(\n                cairo,\n                a.x +\n                    (a.w - te_selected.x_advance - te_unselected.x_advance) / 2,\n                a.y + (int)((a.h + te_all.height) / 2)\n            );\n            cairo_set_operator(cairo, CAIRO_OPERATOR_OVER);\n            cairo_set_source_u32(cairo, config->label_select_color);\n            cairo_show_text(cairo, label_selected_str);\n            cairo_set_source_u32(cairo, config->label_color);\n            cairo_show_text(cairo, label_unselected_str);\n        }\n\n        label_selection_incr(curr_label);\n    }\n\n    label_selection_free(curr_label);\n}\n\nvoid floating_mode_free(void *mode_state) {\n    struct floating_mode_state *ms = mode_state;\n    free(ms->areas);\n    cairo_font_face_destroy(ms->label_font_face);\n    label_selection_free(ms->label_selection);\n    label_symbols_free(ms->label_symbols);\n    free(ms);\n}\n\nstruct mode_interface floating_mode_interface = {\n    .name    = \"floating\",\n    .enter   = floating_mode_enter,\n    .reenter = floating_mode_reenter,\n    .key     = floating_mode_key,\n    .render  = floating_mode_render,\n    .free    = floating_mode_free,\n};\n"
  },
  {
    "path": "src/mode_split.c",
    "content": "#include \"config.h\"\n#include \"mode.h\"\n#include \"state.h\"\n#include \"utils.h\"\n#include \"utils_cairo.h\"\n#include \"utils_wayland.h\"\n\n#include <stdlib.h>\n\n#define ARROW_SIZE 5\n\n// Split direction -- defines the \"shrink\" direction of the rectangle\nenum split_dir {\n    SPLIT_DIR_DOWN  = 0,\n    SPLIT_DIR_UP    = 1,\n    SPLIT_DIR_LEFT  = 2,\n    SPLIT_DIR_RIGHT = 3,\n};\n\nstatic void\nsplit_mode_move_pointer(struct state *state, struct split_mode_state *ms) {\n    struct rect *r = &ms->areas[ms->current];\n    move_pointer(state, r->x + r->w / 2, r->y + r->h / 2, CLICK_NONE);\n}\n\nvoid *split_mode_enter(struct state *state, struct rect area) {\n    struct split_mode_state *ms = malloc(sizeof(*ms));\n    ms->areas[0]                = area;\n    ms->current                 = 0;\n\n    split_mode_move_pointer(state, ms);\n\n    return ms;\n}\n\nstatic void split_mode_render_cursor(\n    struct state *state, void *mode_state, cairo_t *cairo\n) {\n    struct mode_split_config *config = &state->config.mode_split;\n    struct split_mode_state  *ms     = mode_state;\n    struct rect              *area   = &ms->areas[ms->current];\n\n    cairo_set_line_width(cairo, 1);\n    cairo_set_source_u32(cairo, config->pointer_color);\n    const int pointer_x = area->x + area->w / 2;\n    const int pointer_y = area->y + area->h / 2;\n    cairo_move_to(\n        cairo, pointer_x + .5, pointer_y - (int)(config->pointer_size / 2) + .5\n    );\n    cairo_line_to(\n        cairo, pointer_x + .5, pointer_y + (int)(config->pointer_size / 2) + .5\n    );\n    cairo_stroke(cairo);\n    cairo_move_to(\n        cairo, pointer_x - (int)(config->pointer_size / 2) + .5, pointer_y + .5\n    );\n    cairo_line_to(\n        cairo, pointer_x + (int)(config->pointer_size / 2) + .5, pointer_y + .5\n    );\n    cairo_stroke(cairo);\n\n    // Draw \"undividable\" marker, draw a red circle around the cursor\n    if (area->w <= 1 && area->h <= 1) {\n        cairo_set_source_u32(cairo, config->pointer_color);\n        cairo_arc(\n            cairo, area->x + .5, area->y + .5, config->pointer_size / 4., 0,\n            2 * M_PI\n        );\n        cairo_set_line_width(cairo, 1);\n        cairo_stroke(cairo);\n    }\n}\n\nstatic void render_split_render_arrow(\n    cairo_t *cairo, int x, int y, enum split_dir dir, uint32_t color\n) {\n    static const struct {\n        char dx1 : 2;\n        char dy1 : 2;\n        char dx2 : 2;\n        char dy2 : 2;\n    } arrow_points[] = {\n        [SPLIT_DIR_LEFT] =\n            {\n                .dx1 = 1,\n                .dy1 = 1,\n                .dx2 = 1,\n                .dy2 = -1,\n            },\n        [SPLIT_DIR_RIGHT] =\n            {\n                .dx1 = -1,\n                .dy1 = 1,\n                .dx2 = -1,\n                .dy2 = -1,\n            },\n        [SPLIT_DIR_UP] =\n            {\n                .dx1 = -1,\n                .dy1 = 1,\n                .dx2 = 1,\n                .dy2 = 1,\n            },\n\n        [SPLIT_DIR_DOWN] = {\n            .dx1 = -1,\n            .dy1 = -1,\n            .dx2 = 1,\n            .dy2 = -1,\n        },\n    };\n\n    if (dir < 0 || dir >= 4) {\n        return;\n    }\n\n    cairo_set_source_u32(cairo, color);\n    cairo_set_line_join(cairo, CAIRO_LINE_JOIN_ROUND);\n    cairo_set_line_width(cairo, 2);\n    cairo_move_to(\n        cairo, x + ARROW_SIZE * arrow_points[dir].dx1 + .5,\n        y + ARROW_SIZE * arrow_points[dir].dy1 + .5\n    );\n    cairo_line_to(cairo, x + .5, y + .5);\n    cairo_line_to(\n        cairo, x + ARROW_SIZE * arrow_points[dir].dx2 + .5,\n        y + ARROW_SIZE * arrow_points[dir].dy2 + .5\n    );\n    cairo_stroke(cairo);\n}\n\nstatic void split_mode_render_markers(\n    cairo_t *cairo, struct rect *area, uint32_t vcolor, uint32_t hcolor\n) {\n    uint32_t middle_x = area->x + area->w / 2;\n    uint32_t middle_y = area->y + area->h / 2;\n\n    cairo_set_source_u32(cairo, hcolor);\n    cairo_set_line_width(cairo, 1);\n    cairo_move_to(cairo, middle_x + .5, area->y + .5);\n    cairo_line_to(cairo, middle_x + .5, area->y + area->h + .5);\n    cairo_stroke(cairo);\n\n    cairo_set_source_u32(cairo, vcolor);\n    cairo_set_line_width(cairo, 1);\n    cairo_move_to(cairo, area->x + .5, middle_y + .5);\n    cairo_line_to(cairo, area->x + area->w + .5, middle_y + .5);\n    cairo_stroke(cairo);\n\n    /*\n\n   x  x+w/4    x+w\n   +--+-----+--+ y\n   |  .     .  |\n   +.....0.....+ y+h/4 (2)\n   |  .     .  |\n   |..2..*..3..|\n   |  .     .  |\n   +.....1.....+ y+3h/4 (3)\n   |  .     .  |\n   +--+-----+--+ y+h\n (0)    x+3w/4\n\n     */\n\n    if (area->w > 1) {\n        render_split_render_arrow(\n            cairo, area->x + area->w / 4, area->y + area->h / 2, SPLIT_DIR_LEFT,\n            hcolor\n        );\n        render_split_render_arrow(\n            cairo, area->x + area->w * 3 / 4, area->y + area->h / 2,\n            SPLIT_DIR_RIGHT, hcolor\n        );\n    }\n    if (area->h > 1) {\n        render_split_render_arrow(\n            cairo, area->x + area->w / 2, area->y + area->h / 4, SPLIT_DIR_UP,\n            vcolor\n        );\n        render_split_render_arrow(\n            cairo, area->x + area->w / 2, area->y + area->h * 3 / 4,\n            SPLIT_DIR_DOWN, vcolor\n        );\n    }\n}\n\nstatic void\nsplit_mode_render(struct state *state, void *mode_state, cairo_t *cairo) {\n    struct mode_split_config *config = &state->config.mode_split;\n    struct split_mode_state  *ms     = mode_state;\n\n    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);\n    cairo_set_source_u32(cairo, config->bg_color);\n    cairo_paint(cairo);\n\n    cairo_set_source_u32(cairo, config->history_border_color);\n    cairo_set_line_width(cairo, 1);\n\n    for (int i = 0; i <= ms->current; i++) {\n        struct rect *area = &ms->areas[i];\n        cairo_rectangle(\n            cairo, area->x + .5, area->y + .5, area->w - 1, area->h - 1\n        );\n        cairo_stroke(cairo);\n    }\n\n    struct rect *area = &ms->areas[ms->current];\n    cairo_set_source_u32(cairo, config->area_bg_color);\n    cairo_rectangle(\n        cairo, area->x + .5, area->y + .5, area->w - 1, area->h - 1\n    );\n    cairo_fill(cairo);\n    split_mode_render_markers(\n        cairo, area, config->vertical_color, config->horizontal_color\n    );\n    split_mode_render_cursor(state, mode_state, cairo);\n}\n\nstatic bool\nsplit_mode_split(struct state *state, void *mode_state, enum split_dir dir) {\n    struct split_mode_state *ms = mode_state;\n\n    if (ms->current + 1 >= SPLIT_MAX_HISTORY) {\n        return false;\n    }\n\n    struct rect *area     = &ms->areas[ms->current];\n    struct rect *new_area = &ms->areas[ms->current + 1];\n\n    *new_area = *area;\n\n    switch (dir) {\n    case SPLIT_DIR_RIGHT:\n        if (area->w <= 1) {\n            return false; /* Cannot split further */\n        }\n        new_area->w  = area->w / 2;\n        new_area->x += new_area->w;\n        break;\n\n    case SPLIT_DIR_LEFT:\n        if (area->w <= 1) {\n            return false; /* Cannot split further */\n        }\n        new_area->w = area->w / 2;\n        break;\n\n    case SPLIT_DIR_UP:\n        if (area->h <= 1) {\n            return false; /* Cannot split further */\n        }\n        new_area->h = area->h / 2;\n        break;\n\n    case SPLIT_DIR_DOWN:\n        if (area->h <= 1) {\n            return false; /* Cannot split further */\n        }\n        new_area->h  = area->h / 2;\n        new_area->y += new_area->h;\n        break;\n    }\n\n    ms->current++;\n    split_mode_move_pointer(state, ms);\n\n    return true;\n}\n\nstatic bool split_mode_key(\n    struct state *state, void *mode_state, xkb_keysym_t keysym, char *text\n) {\n    struct split_mode_state *ms = mode_state;\n\n    switch (keysym) {\n    case XKB_KEY_Escape:\n        state->running = false;\n        break;\n\n    case XKB_KEY_Return:\n    case XKB_KEY_space:\n        enter_next_mode(state, ms->areas[ms->current]);\n        return true;\n\n    case XKB_KEY_BackSpace:\n        if (ms->current > 0) {\n            ms->current--;\n            split_mode_move_pointer(state, ms);\n        } else {\n            reenter_prev_mode(state);\n        }\n        return true;\n\n    case XKB_KEY_Left:\n        return split_mode_split(state, mode_state, SPLIT_DIR_LEFT);\n\n    case XKB_KEY_Right:\n        return split_mode_split(state, mode_state, SPLIT_DIR_RIGHT);\n\n    case XKB_KEY_Up:\n        return split_mode_split(state, mode_state, SPLIT_DIR_UP);\n\n    case XKB_KEY_Down:\n        return split_mode_split(state, mode_state, SPLIT_DIR_DOWN);\n    }\n\n    int matched_i = find_str(state->home_row, HOME_ROW_LEN_WITH_BTN, text);\n    switch (matched_i) {\n    case HOME_ROW_LEFT_CLICK:\n        state->click = CLICK_LEFT_BTN;\n        enter_next_mode(state, ms->areas[ms->current]);\n        return false;\n\n    case HOME_ROW_RIGHT_CLICK:\n        state->click = CLICK_RIGHT_BTN;\n        enter_next_mode(state, ms->areas[ms->current]);\n        return false;\n\n    case HOME_ROW_MIDDLE_CLICK:\n        state->click = CLICK_MIDDLE_BTN;\n        enter_next_mode(state, ms->areas[ms->current]);\n        return false;\n\n    default:\n        break;\n    }\n\n    // Handle `wasd` and `hjkl` but only after home_row_keys\n    switch (text[0]) {\n    case 'a':\n    case 'h':\n        return split_mode_split(state, mode_state, SPLIT_DIR_LEFT);\n\n    case 'd':\n    case 'l':\n        return split_mode_split(state, mode_state, SPLIT_DIR_RIGHT);\n\n    case 'w':\n    case 'k':\n        return split_mode_split(state, mode_state, SPLIT_DIR_UP);\n\n    case 's':\n    case 'j':\n        return split_mode_split(state, mode_state, SPLIT_DIR_DOWN);\n    }\n\n    return false;\n}\n\nvoid split_mode_reenter(struct state *state, void *mode_state) {\n    split_mode_move_pointer(state, mode_state);\n}\nvoid split_mode_free(void *mode_state) {\n    free(mode_state);\n}\n\nstruct mode_interface split_mode_interface = {\n    .name    = \"split\",\n    .enter   = split_mode_enter,\n    .reenter = split_mode_reenter,\n    .key     = split_mode_key,\n    .render  = split_mode_render,\n    .free    = split_mode_free,\n};\n"
  },
  {
    "path": "src/mode_tile.c",
    "content": "#include \"config.h\"\n#include \"label.h\"\n#include \"mode.h\"\n#include \"state.h\"\n#include \"utils.h\"\n#include \"utils_cairo.h\"\n\n#include <cairo.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n#include <xkbcommon/xkbcommon.h>\n\n#define MIN_SUB_AREA_SIZE (25 * 50)\n\nvoid *tile_mode_enter(struct state *state, struct rect area) {\n    struct tile_mode_state *ms = malloc(sizeof(*ms));\n    ms->area                   = area;\n\n    const int max_num_sub_areas = 26 * 26;\n    const int area_size         = ms->area.w * ms->area.h;\n    const int sub_area_size =\n        max(area_size / max_num_sub_areas, MIN_SUB_AREA_SIZE);\n\n    ms->sub_area_height = sqrt(sub_area_size / 2.);\n    ms->sub_area_rows   = ms->area.h / ms->sub_area_height;\n    if (ms->sub_area_rows == 0) {\n        ms->sub_area_rows = 1;\n    }\n    ms->sub_area_height_off = ms->area.h % ms->sub_area_rows;\n    ms->sub_area_height     = ms->area.h / ms->sub_area_rows;\n\n    ms->sub_area_width   = sqrt(sub_area_size * 2);\n    ms->sub_area_columns = ms->area.w / ms->sub_area_width;\n    if (ms->sub_area_columns == 0) {\n        ms->sub_area_columns = 1;\n    }\n    ms->sub_area_width_off = ms->area.w % ms->sub_area_columns;\n    ms->sub_area_width     = ms->area.w / ms->sub_area_columns;\n\n    ms->label_symbols =\n        label_symbols_from_str(state->config.mode_tile.label_symbols);\n    if (ms->label_symbols == NULL) {\n        ms->label_selection = NULL;\n        state->running      = false;\n        return ms;\n    }\n\n    ms->label_selection = label_selection_new(\n        ms->label_symbols, ms->sub_area_rows * ms->sub_area_columns\n    );\n\n    ms->label_font_face = cairo_toy_font_face_create(\n        state->config.mode_tile.label_font_family, CAIRO_FONT_SLANT_NORMAL,\n        CAIRO_FONT_WEIGHT_NORMAL\n    );\n\n    return ms;\n}\n\n// `tile_mode_back` goes back in history. Returns true if there was something to\n// go back to.\nstatic bool tile_mode_back(struct tile_mode_state *mode_state) {\n    return label_selection_back(mode_state->label_selection) != 0;\n}\n\n// `tile_mode_reenter` reenters the tile mode. We assume that the saved state is\n// valid and goes back in history once.\nvoid tile_mode_reenter(struct state *state, void *mode_state) {\n    struct tile_mode_state *ms = mode_state;\n    tile_mode_back(ms);\n}\n\nstatic struct rect\nidx_to_rect(struct tile_mode_state *mode_state, int idx, int x_off, int y_off) {\n    int column = idx / mode_state->sub_area_rows;\n    int row    = idx % mode_state->sub_area_rows;\n\n    return (struct rect){\n        .x = column * mode_state->sub_area_width +\n             min(column, mode_state->sub_area_width_off) + x_off,\n        .w = mode_state->sub_area_width +\n             (column < mode_state->sub_area_width_off ? 1 : 0),\n        .y = row * mode_state->sub_area_height +\n             min(row, mode_state->sub_area_height_off) + y_off,\n        .h = mode_state->sub_area_height +\n             (row < mode_state->sub_area_height_off ? 1 : 0),\n    };\n}\n\nstatic bool tile_mode_key(\n    struct state *state, void *mode_state, xkb_keysym_t keysym, char *text\n) {\n    struct tile_mode_state *ms = mode_state;\n\n    switch (keysym) {\n    case XKB_KEY_BackSpace:\n        return tile_mode_back(ms);\n        break;\n\n    case XKB_KEY_Escape:\n        state->running = false;\n        break;\n    default:;\n        int symbol_idx = label_symbols_find_idx(ms->label_symbols, text);\n        if (symbol_idx < 0) {\n            return false;\n        }\n\n        label_selection_append(ms->label_selection, symbol_idx);\n\n        int idx = label_selection_to_idx(ms->label_selection);\n        if (idx >= 0) {\n            enter_next_mode(\n                state, idx_to_rect(ms, idx, ms->area.x, ms->area.y)\n            );\n        }\n        return true;\n    }\n\n    return false;\n}\n\nvoid tile_mode_render(struct state *state, void *mode_state, cairo_t *cairo) {\n    struct mode_tile_config *config = &state->config.mode_tile;\n    struct tile_mode_state  *ms     = mode_state;\n\n    cairo_set_font_face(cairo, ms->label_font_face);\n    cairo_set_font_size(\n        cairo, compute_relative_font_size(\n                   &config->label_font_size, ms->sub_area_height\n               )\n    );\n\n    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);\n    cairo_set_source_u32(cairo, config->unselectable_bg_color);\n    cairo_paint(cairo);\n\n    cairo_translate(cairo, ms->area.x, ms->area.y);\n\n    cairo_set_source_u32(cairo, config->unselectable_bg_color);\n    cairo_rectangle(cairo, .5, .5, ms->area.w - 1, ms->area.h - 1);\n    cairo_set_line_width(cairo, 1);\n    cairo_stroke(cairo);\n\n    label_selection_t *curr_label = label_selection_new(\n        ms->label_symbols, ms->sub_area_columns * ms->sub_area_rows\n    );\n    label_selection_set_from_idx(curr_label, 0);\n\n    int  label_str_max_len = label_selection_str_max_len(curr_label) + 1;\n    char label_selected_str[label_str_max_len];\n    char label_unselected_str[label_str_max_len];\n\n    for (int i = 0; i < ms->sub_area_columns; i++) {\n        for (int j = 0; j < ms->sub_area_rows; j++) {\n            const int x =\n                i * ms->sub_area_width + min(i, ms->sub_area_width_off);\n            const int w =\n                ms->sub_area_width + (i < ms->sub_area_width_off ? 1 : 0);\n            const int y =\n                j * ms->sub_area_height + min(j, ms->sub_area_height_off);\n            const int h =\n                ms->sub_area_height + (j < ms->sub_area_height_off ? 1 : 0);\n\n            const bool selectable =\n                label_selection_is_included(curr_label, ms->label_selection);\n\n            cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);\n            if (selectable) {\n                cairo_set_source_u32(cairo, config->selectable_bg_color);\n                cairo_rectangle(cairo, x, y, w, h);\n                cairo_fill(cairo);\n\n                cairo_set_source_u32(cairo, config->selectable_border_color);\n                cairo_rectangle(cairo, x + .5, y + .5, w - 1, h - 1);\n                cairo_set_line_width(cairo, 1);\n                cairo_stroke(cairo);\n\n                cairo_text_extents_t te_all;\n                label_selection_str(curr_label, label_selected_str);\n                cairo_text_extents(cairo, label_selected_str, &te_all);\n\n                label_selection_str_split(\n                    curr_label, label_selected_str, label_unselected_str,\n                    ms->label_selection->next\n                );\n\n                cairo_text_extents_t te_selected, te_unselected;\n                cairo_text_extents(cairo, label_selected_str, &te_selected);\n                cairo_text_extents(cairo, label_unselected_str, &te_unselected);\n\n                // Centers the label.\n                cairo_move_to(\n                    cairo,\n                    x + (w - te_selected.x_advance - te_unselected.x_advance) /\n                            2,\n                    y + (int)((h + te_all.height) / 2)\n                );\n                cairo_set_source_u32(cairo, config->label_select_color);\n                cairo_show_text(cairo, label_selected_str);\n                cairo_set_source_u32(cairo, config->label_color);\n                cairo_show_text(cairo, label_unselected_str);\n            }\n\n            label_selection_incr(curr_label);\n        }\n    }\n\n    label_selection_free(curr_label);\n    cairo_translate(cairo, -ms->area.x, -ms->area.y);\n}\n\nvoid tile_mode_state_free(void *mode_state) {\n    struct tile_mode_state *ms = mode_state;\n    cairo_font_face_destroy(ms->label_font_face);\n    label_selection_free(ms->label_selection);\n    label_symbols_free(ms->label_symbols);\n    free(ms);\n}\n\nstruct mode_interface tile_mode_interface = {\n    .name    = \"tile\",\n    .enter   = tile_mode_enter,\n    .reenter = tile_mode_reenter,\n    .key     = tile_mode_key,\n    .render  = tile_mode_render,\n    .free    = tile_mode_state_free,\n};\n"
  },
  {
    "path": "src/screencopy.c",
    "content": "#if OPENCV_ENABLED\n\n#include \"screencopy.h\"\n\n#include \"log.h\"\n#include \"state.h\"\n#include \"surface_buffer.h\"\n#include \"wlr-screencopy-unstable-v1-client-protocol.h\"\n\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/mman.h>\n#include <unistd.h>\n\nenum screen_capture_state {\n    CAPTURE_NOT_REQUESTED,\n    CAPTURE_REQUESTED,\n    CAPTURE_FAILED,\n    CAPTURE_SUCCESS,\n};\n\nstruct scrcpy_state {\n    struct wl_shm                   *wl_shm;\n    struct zwlr_screencopy_frame_v1 *wl_screencopy_frame;\n    struct scrcpy_buffer            *scrcpy_buffer;\n    enum screen_capture_state        screen_capture_state;\n};\n\nstatic struct scrcpy_buffer *create_scrcpy_buffer(\n    struct wl_shm *shm, enum wl_shm_format format, uint32_t width,\n    uint32_t height, uint32_t stride\n) {\n    size_t size = stride * height;\n\n    int fd = allocate_shm_file(size);\n    if (fd == -1) {\n        LOG_ERR(\"Could not allocate SHM file.\");\n        return NULL;\n    }\n\n    void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);\n    if (data == MAP_FAILED) {\n        LOG_ERR(\"Could not mmap shared buffer for surface buffer.\");\n\n        close(fd);\n        return NULL;\n    }\n\n    struct wl_shm_pool *wl_shm_pool = wl_shm_create_pool(shm, fd, size);\n    struct wl_buffer   *wl_buffer   = wl_shm_pool_create_buffer(\n        wl_shm_pool, 0, width, height, stride, format\n    );\n    wl_shm_pool_destroy(wl_shm_pool);\n\n    close(fd);\n\n    struct scrcpy_buffer *buffer = malloc(sizeof(*buffer));\n\n    buffer->wl_buffer = wl_buffer;\n    buffer->format    = format;\n    buffer->data      = data;\n    buffer->width     = width;\n    buffer->height    = height;\n    buffer->stride    = stride;\n\n    return buffer;\n}\n\nvoid destroy_scrcpy_buffer(struct scrcpy_buffer *buf) {\n    if (buf != NULL) {\n        munmap(buf->data, buf->stride * buf->height);\n        wl_buffer_destroy(buf->wl_buffer);\n        free(buf);\n    }\n}\n\nstatic void screencopy_frame_handle_buffer(\n    void *data, struct zwlr_screencopy_frame_v1 *frame, uint32_t format,\n    uint32_t width, uint32_t height, uint32_t stride\n) {\n    struct scrcpy_state *state = data;\n\n    LOG_DEBUG(\n        \"Copying capture buffer (format: 0x%08x, %dx%d, stride: %d)\", format,\n        width, height, stride\n    );\n\n    state->scrcpy_buffer =\n        create_scrcpy_buffer(state->wl_shm, format, width, height, stride);\n\n    zwlr_screencopy_frame_v1_copy(frame, state->scrcpy_buffer->wl_buffer);\n}\n\nstatic void screencopy_frame_handle_ready(\n    void *data, struct zwlr_screencopy_frame_v1 *frame, uint32_t tv_sec_hi,\n    uint32_t tv_sec_lo, uint32_t tv_nsec\n) {\n    struct scrcpy_state *state  = data;\n    state->screen_capture_state = CAPTURE_SUCCESS;\n}\n\nstatic void screencopy_frame_handle_failed(\n    void *data, struct zwlr_screencopy_frame_v1 *frame\n) {\n    struct scrcpy_state *state  = data;\n    state->screen_capture_state = CAPTURE_FAILED;\n    LOG_ERR(\"Could not capture screen.\");\n}\n\nstatic void noop() {}\n\nconst struct zwlr_screencopy_frame_v1_listener screencopy_frame_listener = {\n    .buffer       = screencopy_frame_handle_buffer,\n    .flags        = noop,\n    .ready        = screencopy_frame_handle_ready,\n    .failed       = screencopy_frame_handle_failed,\n    .buffer_done  = noop,\n    .damage       = noop,\n    .linux_dmabuf = noop,\n};\n\nstruct scrcpy_buffer *\nquery_screenshot(struct state *state, struct rect region) {\n    struct scrcpy_state scrcpy_state;\n    scrcpy_state.wl_shm = state->wl_shm;\n\n    if (state->wl_screencopy_manager == NULL) {\n        LOG_ERR(\"Could not load `zwlr_screencopy_manager_v1`.\");\n        exit(1);\n    }\n\n    LOG_DEBUG(\n        \"Capture region: %dx%d+%d+%d\", region.w, region.h, region.x, region.y\n    );\n\n    scrcpy_state.wl_screencopy_frame =\n        zwlr_screencopy_manager_v1_capture_output_region(\n            state->wl_screencopy_manager, false,\n            state->current_output->wl_output, region.x, region.y, region.w,\n            region.h\n        );\n    zwlr_screencopy_frame_v1_add_listener(\n        scrcpy_state.wl_screencopy_frame, &screencopy_frame_listener,\n        &scrcpy_state\n    );\n\n    scrcpy_state.screen_capture_state = CAPTURE_REQUESTED;\n    while (scrcpy_state.screen_capture_state == CAPTURE_REQUESTED) {\n        wl_display_roundtrip(state->wl_display);\n    }\n\n    zwlr_screencopy_frame_v1_destroy(scrcpy_state.wl_screencopy_frame);\n\n    return scrcpy_state.scrcpy_buffer;\n}\n\n#endif\n"
  },
  {
    "path": "src/screencopy.h",
    "content": "#ifndef __SCREENCOPY_H_INCLUDED__\n#define __SCREENCOPY_H_INCLUDED__\n\n#if OPENCV_ENABLED\n\n#include <wayland-client.h>\n\nstruct scrcpy_buffer {\n    struct wl_buffer  *wl_buffer;\n    void              *data;\n    enum wl_shm_format format;\n    int32_t            width;\n    int32_t            height;\n    int32_t            stride;\n};\n\nstruct state;\nstruct rect;\nstruct scrcpy_buffer *query_screenshot(struct state *state, struct rect region);\n\nvoid destroy_scrcpy_buffer(struct scrcpy_buffer *buf);\n\n#endif\n\n#endif\n"
  },
  {
    "path": "src/state.h",
    "content": "#ifndef __STATE_H_INCLUDED__\n#define __STATE_H_INCLUDED__\n\n#include \"config.h\"\n#include \"fractional-scale-v1-client-protocol.h\"\n#include \"label.h\"\n#include \"screencopy.h\"\n#include \"surface_buffer.h\"\n#include \"utils.h\"\n#include \"viewporter-client-protocol.h\"\n#include \"wlr-layer-shell-unstable-v1-client-protocol.h\"\n#include \"wlr-screencopy-unstable-v1-client-protocol.h\"\n#include \"wlr-virtual-pointer-unstable-v1-client-protocol.h\"\n\n#include <stdbool.h>\n#include <stdint.h>\n#include <wayland-client.h>\n#include <wayland-util.h>\n#include <xkbcommon/xkbcommon.h>\n\n#define NO_AREA_SELECTION     -1\n#define HOME_ROW_LEN          8\n#define HOME_ROW_LEN_WITH_BTN 11\n#define HOME_ROW_BUFFER_LEN   128\n#define HOME_ROW_LEFT_CLICK   8\n#define HOME_ROW_RIGHT_CLICK  9\n#define HOME_ROW_MIDDLE_CLICK 10\n\n// This should cover a initial maximum area with a width and height of 65536\n// pixels.\n#define BISECT_MAX_HISTORY 16\n\n// Split history of up to a resolution of 65536x65536 assuming equal number of\n// divisions each way.\n#define SPLIT_MAX_HISTORY 32\n\n#define MAX_NUM_MODES   3\n#define NO_MODE_ENTERED -1\n\nstruct mode_interface;\n\nstruct tile_mode_state {\n    struct rect area;\n\n    int sub_area_rows;\n    int sub_area_width;\n    int sub_area_width_off;\n\n    int sub_area_columns;\n    int sub_area_height;\n    int sub_area_height_off;\n\n    label_selection_t *label_selection;\n    label_symbols_t   *label_symbols;\n\n    cairo_font_face_t *label_font_face;\n};\n\nstruct floating_mode_state {\n    struct rect *areas;\n    int          num_areas;\n\n    label_selection_t *label_selection;\n    label_symbols_t   *label_symbols;\n\n    cairo_font_face_t *label_font_face;\n};\n\nstruct bisect_mode_state {\n    struct rect areas[BISECT_MAX_HISTORY];\n    int         current;\n\n    cairo_font_face_t *label_font_face;\n};\n\nstruct split_mode_state {\n    struct rect areas[SPLIT_MAX_HISTORY];\n    int         current;\n};\n\nstruct output {\n    struct wl_list           link; // type: struct output\n    struct wl_output        *wl_output;\n    struct zxdg_output_v1   *xdg_output;\n    char                    *name;\n    int32_t                  scale;\n    int32_t                  width;\n    int32_t                  height;\n    int32_t                  x;\n    int32_t                  y;\n    enum wl_output_transform transform;\n};\n\nstruct seat {\n    struct wl_list      link; // type: struct seat\n    struct wl_seat     *wl_seat;\n    struct wl_keyboard *wl_keyboard;\n    struct xkb_context *xkb_context;\n    struct xkb_keymap  *xkb_keymap;\n    struct xkb_state   *xkb_state;\n    struct state       *state;\n};\n\nstruct state {\n    struct config                           config;\n    struct wl_display                      *wl_display;\n    struct wl_registry                     *wl_registry;\n    struct wl_compositor                   *wl_compositor;\n    struct wl_shm                          *wl_shm;\n    struct zwlr_layer_shell_v1             *wl_layer_shell;\n    struct zwlr_virtual_pointer_manager_v1 *wl_virtual_pointer_mgr;\n    struct wp_viewporter                   *wp_viewporter;\n    struct wp_viewport                     *wp_viewport;\n    struct wp_fractional_scale_manager_v1  *fractional_scale_mgr;\n    struct surface_buffer_pool              surface_buffer_pool;\n    struct wl_surface                      *wl_surface;\n    struct wl_callback                     *wl_surface_callback;\n    struct zwlr_layer_surface_v1           *wl_layer_surface;\n    bool                                    surface_configured;\n#if OPENCV_ENABLED\n    struct zwlr_screencopy_manager_v1 *wl_screencopy_manager;\n#endif\n    struct zxdg_output_manager_v1 *xdg_output_manager;\n    struct wl_list                 outputs;\n    struct wl_list                 seats;\n    struct output                 *current_output;\n    uint32_t                       surface_height;\n    uint32_t                       surface_width;\n    uint32_t                       fractional_scale; // scale / 120\n    bool                           running;\n    struct rect                    initial_area;\n    char                           home_row_buffer[HOME_ROW_BUFFER_LEN];\n    char                         **home_row;\n    struct rect                    result;\n    struct mode_interface         *mode_interfaces[MAX_NUM_MODES];\n    void                          *mode_states[MAX_NUM_MODES];\n    int                            current_mode;\n    enum click                     click;\n};\n\n#endif\n"
  },
  {
    "path": "src/surface_buffer.c",
    "content": "#include \"surface_buffer.h\"\n\n#include \"log.h\"\n\n#include <cairo/cairo.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/mman.h>\n#include <unistd.h>\n\n#define CAIRO_SURFACE_FORMAT CAIRO_FORMAT_ARGB32\n\nstatic int create_shm_file(void) {\n    char name[] = \"/tmp/wl-shm-XXXXXX\";\n    int  fd     = mkostemp(name, O_CLOEXEC);\n    if (fd < 0) {\n        return -1;\n    }\n\n    unlink(name);\n    return fd;\n}\n\nint allocate_shm_file(size_t size) {\n    int fd = create_shm_file();\n    if (fd < 0) {\n        return -1;\n    }\n\n    int err;\n    while ((err = ftruncate(fd, size)) && errno == EINTR) {}\n    if (err) {\n        close(fd);\n        return -1;\n    }\n\n    return fd;\n}\n\nstatic void handle_buffer_release(void *data, struct wl_buffer *wl_buffer) {\n    ((struct surface_buffer *)data)->state = SURFACE_BUFFER_READY;\n}\n\nstatic const struct wl_buffer_listener wl_buffer_listener = {\n    .release = handle_buffer_release,\n};\n\nstatic struct surface_buffer *surface_buffer_init(\n    struct wl_shm *wl_shm, struct surface_buffer *buffer, int32_t width,\n    int32_t height\n) {\n    const uint32_t stride =\n        cairo_format_stride_for_width(CAIRO_SURFACE_FORMAT, width);\n    const uint32_t data_size = height * stride;\n    void          *data;\n\n    int fd = allocate_shm_file(data_size);\n    if (fd < 0) {\n        LOG_ERR(\"Could not allocate shared buffer for surface buffer.\");\n        return NULL;\n    }\n\n    data = mmap(NULL, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);\n    if (data == MAP_FAILED) {\n        LOG_ERR(\"Could not mmap shared buffer for surface buffer.\");\n\n        close(fd);\n        return NULL;\n    }\n\n    struct wl_shm_pool *wl_shm_pool = wl_shm_create_pool(wl_shm, fd, data_size);\n    buffer->wl_buffer               = wl_shm_pool_create_buffer(\n        wl_shm_pool, 0, width, height, stride, WL_SHM_FORMAT_ARGB8888\n    );\n    wl_buffer_add_listener(buffer->wl_buffer, &wl_buffer_listener, buffer);\n    wl_shm_pool_destroy(wl_shm_pool);\n\n    close(fd);\n\n    buffer->data      = data;\n    buffer->data_size = data_size;\n    buffer->width     = width;\n    buffer->height    = height;\n    buffer->state     = SURFACE_BUFFER_READY;\n\n    buffer->cairo_surface = cairo_image_surface_create_for_data(\n        buffer->data, CAIRO_SURFACE_FORMAT, width, height, stride\n    );\n    buffer->cairo = cairo_create(buffer->cairo_surface);\n\n    return buffer;\n}\n\nstatic void surface_buffer_destroy(struct surface_buffer *buffer) {\n    if (buffer->state == SURFACE_BUFFER_UNINITIALIZED) {\n        return;\n    }\n\n    if (buffer->cairo) {\n        cairo_destroy(buffer->cairo);\n    }\n\n    if (buffer->cairo_surface) {\n        cairo_surface_destroy(buffer->cairo_surface);\n    }\n\n    if (buffer->wl_buffer) {\n        wl_buffer_destroy(buffer->wl_buffer);\n    }\n\n    if (buffer->data) {\n        munmap(buffer->data, buffer->data_size);\n    }\n\n    memset(buffer, 0, sizeof(struct surface_buffer));\n}\n\nvoid surface_buffer_pool_init(struct surface_buffer_pool *pool) {\n    memset(pool, 0, sizeof(struct surface_buffer_pool));\n}\n\nvoid surface_buffer_pool_destroy(struct surface_buffer_pool *pool) {\n    surface_buffer_destroy(&pool->buffers[0]);\n    surface_buffer_destroy(&pool->buffers[1]);\n}\n\nstruct surface_buffer *get_next_buffer(\n    struct wl_shm *wl_shm, struct surface_buffer_pool *pool, uint32_t width,\n    uint32_t height\n) {\n    struct surface_buffer *buffer = NULL;\n    for (size_t i = 0; i < 2; i++) {\n        if (pool->buffers[i].state != SURFACE_BUFFER_BUSY) {\n            buffer = &pool->buffers[i];\n            break;\n        }\n    }\n\n    if (buffer == NULL) {\n        LOG_WARN(\"All surface buffers are busy.\");\n        return NULL;\n    }\n\n    if (buffer->width != width || buffer->height != height) {\n        surface_buffer_destroy(buffer);\n    }\n\n    if (buffer->state == SURFACE_BUFFER_UNINITIALIZED) {\n        if (surface_buffer_init(wl_shm, buffer, width, height) == NULL) {\n            LOG_ERR(\"Could not initialize next buffer.\");\n            return NULL;\n        }\n    }\n\n    return buffer;\n}\n"
  },
  {
    "path": "src/surface_buffer.h",
    "content": "#ifndef __SURFACE_BUFFER_H_INCLUDED__\n#define __SURFACE_BUFFER_H_INCLUDED__\n\n#include <cairo/cairo.h>\n#include <wayland-client.h>\n\nenum surface_buffer_state {\n    // This must be set to 0 as we set the whole structure to 0 when it's not\n    // initialized.\n    SURFACE_BUFFER_UNINITIALIZED = 0,\n\n    SURFACE_BUFFER_READY = 1,\n    SURFACE_BUFFER_BUSY  = 2,\n};\n\nstruct surface_buffer {\n    enum surface_buffer_state state;\n    struct wl_buffer         *wl_buffer;\n    cairo_surface_t          *cairo_surface;\n    cairo_t                  *cairo;\n    void                     *data;\n    size_t                    data_size;\n    uint32_t                  width;\n    uint32_t                  height;\n};\n\nstruct surface_buffer_pool {\n    struct surface_buffer buffers[2];\n};\n\nvoid surface_buffer_pool_init(struct surface_buffer_pool *pool);\nvoid surface_buffer_pool_destroy(struct surface_buffer_pool *pool);\n\nstruct surface_buffer *get_next_buffer(\n    struct wl_shm *wl_shm, struct surface_buffer_pool *pool, uint32_t width,\n    uint32_t height\n);\n\nint allocate_shm_file(size_t size);\n\n#endif\n"
  },
  {
    "path": "src/target_detection.cpp",
    "content": "#include \"target_detection.h\"\n\n#include \"log.h\"\n\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n#include <pixman.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <wayland-client.h>\n\nstatic pixman_format_code_t get_pixman_format(enum wl_shm_format format) {\n    switch (format) {\n    case WL_SHM_FORMAT_RGB332:\n        return PIXMAN_r3g3b2;\n    case WL_SHM_FORMAT_BGR233:\n        return PIXMAN_b2g3r3;\n    case WL_SHM_FORMAT_ARGB4444:\n        return PIXMAN_a4r4g4b4;\n    case WL_SHM_FORMAT_XRGB4444:\n        return PIXMAN_x4r4g4b4;\n    case WL_SHM_FORMAT_ABGR4444:\n        return PIXMAN_a4b4g4r4;\n    case WL_SHM_FORMAT_XBGR4444:\n        return PIXMAN_x4b4g4r4;\n    case WL_SHM_FORMAT_ARGB1555:\n        return PIXMAN_a1r5g5b5;\n    case WL_SHM_FORMAT_XRGB1555:\n        return PIXMAN_x1r5g5b5;\n    case WL_SHM_FORMAT_ABGR1555:\n        return PIXMAN_a1b5g5r5;\n    case WL_SHM_FORMAT_XBGR1555:\n        return PIXMAN_x1b5g5r5;\n    case WL_SHM_FORMAT_RGB565:\n        return PIXMAN_r5g6b5;\n    case WL_SHM_FORMAT_BGR565:\n        return PIXMAN_b5g6r5;\n    case WL_SHM_FORMAT_RGB888:\n        return PIXMAN_r8g8b8;\n    case WL_SHM_FORMAT_BGR888:\n        return PIXMAN_b8g8r8;\n    case WL_SHM_FORMAT_ARGB8888:\n        return PIXMAN_a8r8g8b8;\n    case WL_SHM_FORMAT_XRGB8888:\n        return PIXMAN_x8r8g8b8;\n    case WL_SHM_FORMAT_ABGR8888:\n        return PIXMAN_a8b8g8r8;\n    case WL_SHM_FORMAT_XBGR8888:\n        return PIXMAN_x8b8g8r8;\n    case WL_SHM_FORMAT_BGRA8888:\n        return PIXMAN_b8g8r8a8;\n    case WL_SHM_FORMAT_BGRX8888:\n        return PIXMAN_b8g8r8x8;\n    case WL_SHM_FORMAT_RGBA8888:\n        return PIXMAN_r8g8b8a8;\n    case WL_SHM_FORMAT_RGBX8888:\n        return PIXMAN_r8g8b8x8;\n    case WL_SHM_FORMAT_ARGB2101010:\n        return PIXMAN_a2r10g10b10;\n    case WL_SHM_FORMAT_ABGR2101010:\n        return PIXMAN_a2b10g10r10;\n    case WL_SHM_FORMAT_XRGB2101010:\n        return PIXMAN_x2r10g10b10;\n    case WL_SHM_FORMAT_XBGR2101010:\n        return PIXMAN_x2b10g10r10;\n    default:\n        return (pixman_format_code_t)0;\n    }\n}\n\nstatic pixman_image_t *make_pixman_image_a8r8g8b8(\n    void *data, uint32_t width, uint32_t height, uint32_t stride,\n    enum wl_shm_format format\n) {\n    pixman_format_code_t pixman_format = get_pixman_format(format);\n    if (pixman_format == 0) {\n        LOG_ERR(\"Unsupported format 0x%08x.\", format);\n        return NULL;\n    }\n\n    LOG_DEBUG(\n        \"Creating `pixman_image_t` for input image (w: %d, h: %d, stride: %d).\",\n        width, height, stride\n    );\n\n    pixman_image_t *in_image = pixman_image_create_bits(\n        pixman_format, width, height, (uint32_t *)data, stride\n    );\n    if (in_image == NULL) {\n        LOG_ERR(\"Failed to create pixman image.\");\n        return NULL;\n    }\n\n    int out_stride = width * sizeof(uint32_t);\n    LOG_DEBUG(\n        \"Creating `pixman_image_t` for ouput image (w: %d, h: %d, stride: %d).\",\n        width, height, out_stride\n    );\n\n    pixman_image_t *out_image = pixman_image_create_bits(\n        PIXMAN_a8r8g8b8, width, height, NULL, out_stride\n    );\n    if (out_image == NULL) {\n        LOG_ERR(\"Failed to create (out) pixman image.\");\n        return NULL;\n    }\n\n    pixman_image_composite32(\n        PIXMAN_OP_SRC, in_image, NULL, out_image, 0, 0, 0, 0, 0, 0, width,\n        height\n    );\n\n    pixman_image_unref(in_image);\n\n    return out_image;\n}\n\nstatic cv::Mat get_gray_scale_from_buffer(\n    void *data, uint32_t height, uint32_t width, uint32_t stride,\n    enum wl_shm_format format\n) {\n    pixman_image_t *image = NULL;\n    cv::Mat         buf;\n    int             in_out[3];\n\n    switch (format) {\n    case WL_SHM_FORMAT_ARGB8888:\n    case WL_SHM_FORMAT_XRGB8888:\n        buf       = cv::Mat(height, width, CV_8UC4, data);\n        in_out[0] = 1;\n        in_out[1] = 1;\n        in_out[2] = 2;\n        break;\n\n    case WL_SHM_FORMAT_XBGR8888:\n    case WL_SHM_FORMAT_ABGR8888:\n        buf       = cv::Mat(height, width, CV_8UC4, data);\n        in_out[0] = 2;\n        in_out[1] = 1;\n        in_out[2] = 0;\n        break;\n\n    default:\n        LOG_DEBUG(\"Converting buffer with Pixman\");\n        image = make_pixman_image_a8r8g8b8(data, width, height, stride, format);\n        if (image == NULL) {\n            exit(1);\n        }\n        buf = cv::Mat(height, width, CV_8UC4, pixman_image_get_data(image));\n        in_out[0] = 1;\n        in_out[1] = 1;\n        in_out[2] = 2;\n        break;\n    }\n\n    cv::Mat in_channels[4];\n    cv::split(buf, in_channels);\n\n    cv::Mat out_channels[3] = {\n        in_channels[in_out[0]],\n        in_channels[in_out[1]],\n        in_channels[in_out[2]],\n    };\n\n    cv::Mat out;\n    cv::merge(out_channels, 3, out);\n\n    cv::Mat grayed;\n    cv::cvtColor(out, grayed, cv::COLOR_BGR2GRAY);\n\n    if (image != NULL) {\n        pixman_image_unref(image);\n    }\n\n    return grayed;\n}\n\nstatic void apply_transform(\n    cv::Mat &m, enum wl_output_transform transform, uint32_t &width,\n    uint32_t &height\n) {\n    cv::Mat tmp;\n    bool    switch_width_height = false;\n\n    switch (transform) {\n    case WL_OUTPUT_TRANSFORM_NORMAL:\n        break;\n\n    case WL_OUTPUT_TRANSFORM_90:\n        cv::rotate(m, tmp, cv::ROTATE_90_CLOCKWISE);\n        m                   = tmp;\n        switch_width_height = true;\n        break;\n\n    case WL_OUTPUT_TRANSFORM_270:\n        cv::rotate(m, tmp, cv::ROTATE_90_COUNTERCLOCKWISE);\n        m                   = tmp;\n        switch_width_height = true;\n        break;\n\n    case WL_OUTPUT_TRANSFORM_180:\n        cv::rotate(m, tmp, cv::ROTATE_180);\n        m = tmp;\n        break;\n\n    case WL_OUTPUT_TRANSFORM_FLIPPED:\n        cv::flip(m, tmp, 1);\n        m = tmp;\n        break;\n\n    case WL_OUTPUT_TRANSFORM_FLIPPED_90:\n        cv::rotate(m, tmp, cv::ROTATE_90_CLOCKWISE);\n        cv::flip(tmp, m, 1);\n        switch_width_height = true;\n        break;\n\n    case WL_OUTPUT_TRANSFORM_FLIPPED_180:\n        cv::rotate(m, tmp, cv::ROTATE_180);\n        cv::flip(tmp, m, 1);\n        break;\n\n    case WL_OUTPUT_TRANSFORM_FLIPPED_270:\n        cv::rotate(m, tmp, cv::ROTATE_90_COUNTERCLOCKWISE);\n        cv::flip(tmp, m, 1);\n        switch_width_height = true;\n        break;\n    }\n\n    if (switch_width_height) {\n        uint32_t tmp = height;\n        height       = width;\n        width        = tmp;\n    }\n}\n\nstatic void compute_rects(\n    const std::vector<std::vector<cv::Point>> &contours,\n    std::vector<cv::Rect2d> &rects, double scale, double x_off, double y_off\n) {\n    rects.clear();\n    rects.reserve(contours.size());\n\n    for (const std::vector<cv::Point> &contour : contours) {\n        cv::Rect rect = cv::boundingRect(contour);\n\n        rects.push_back(\n            cv::Rect2d(\n                rect.x / scale + x_off, rect.y / scale + y_off,\n                rect.width / scale, rect.height / scale\n            )\n        );\n    }\n}\n\nstatic size_t filter_rects(\n    const std::vector<cv::Rect2d> &rects,\n    const std::vector<cv::Vec4i> &hierachy, std::vector<bool> &filtered\n) {\n    filtered.assign(rects.size(), false);\n\n    for (size_t i = 0; i < rects.size(); i++) {\n        const auto &rect = rects[i];\n\n        if (rect.height >= 50 || rect.width >= 500 || rect.height <= 3 ||\n            rect.width <= 7) {\n            filtered[i] = true;\n            continue;\n        }\n    }\n\n    std::vector<int> to_explore;\n    for (size_t i = 0; i < rects.size(); i++) {\n        if (hierachy[i][3] >= 0) {\n            to_explore.push_back(i);\n        }\n    }\n\n    while (!to_explore.empty()) {\n        int i = to_explore.back();\n        to_explore.pop_back();\n\n        if (!filtered[i]) {\n            int parent_i = hierachy[i][3];\n            if (filtered[parent_i]) {\n                goto filtered;\n            }\n\n            const auto &rect = rects[i];\n\n            // Inner targets that are flat are most likely lines forming an\n            // icon, e.g. a hamburger menu.\n            if (rect.height <= 6) {\n                filtered[i] = true;\n                goto filtered;\n            }\n\n            const auto &parent_rect = rects[parent_i];\n\n            const double center_x = rect.x + rect.width / 2.;\n            const double center_y = rect.y + rect.height / 2.;\n            const double parent_center_x =\n                parent_rect.x + parent_rect.width / 2.;\n            const double parent_center_y =\n                parent_rect.y + parent_rect.height / 2.;\n\n            // There's not much reasons to keep inner targets that have the same\n            // center as this is where the user is going to click most likely.\n            if (abs(center_x - parent_center_x) < 8 &&\n                abs(center_y - parent_center_y) < 8) {\n                filtered[i] = true;\n                goto filtered;\n            }\n\n            // If the parent target is a square, it's most likely a button with\n            // a single option or an icon.\n            if (abs(parent_rect.height - parent_rect.width) < 5 &&\n                parent_rect.height < 40 && parent_rect.width < 40) {\n                filtered[i] = true;\n                goto filtered;\n            }\n        }\n\n    filtered:\n        int child = hierachy[i][0];\n        while (child >= 0) {\n            to_explore.push_back(child);\n            child = hierachy[child][2];\n        }\n    }\n\n    size_t not_filtered_count = 0;\n    for (const auto &curr : filtered) {\n        if (!curr) {\n            not_filtered_count += 1;\n        }\n    }\n\n    return not_filtered_count;\n}\n\nint compute_target_from_img_buffer(\n    void *data, uint32_t height, uint32_t width, uint32_t stride,\n    enum wl_shm_format format, enum wl_output_transform transform,\n    struct rect initial_area, struct rect **areas\n) {\n    cv::Mat m1 =\n        get_gray_scale_from_buffer(data, height, width, stride, format);\n    apply_transform(m1, transform, width, height);\n\n    double scale = ((double)height) / ((double)initial_area.h);\n\n    cv::Mat m2;\n    cv::Mat kernel =\n        cv::Mat::ones(round(2.5 * scale), round(3.5 * scale), CV_8U);\n\n    cv::Canny(m1, m2, 70, 220);\n    cv::dilate(m2, m1, kernel);\n\n    std::vector<std::vector<cv::Point>> contours;\n    std::vector<cv::Vec4i>              hierachy;\n    cv::findContours(\n        m1, contours, hierachy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE\n    );\n\n    std::vector<cv::Rect2d> rects;\n    std::vector<bool>       filtered;\n\n    compute_rects(contours, rects, scale, initial_area.x, initial_area.y);\n    int final_rect_count = filter_rects(rects, hierachy, filtered);\n\n    size_t area_i = 0;\n    *areas = (struct rect *)malloc(sizeof(struct rect) * final_rect_count);\n    for (size_t i = 0; i < rects.size(); i++) {\n        if (filtered[i]) {\n            continue;\n        }\n\n        const auto   rect = rects[i];\n        struct rect *area = &(*areas)[area_i];\n        area->x           = round(rect.x);\n        area->y           = round(rect.y);\n        area->w           = round(rect.width);\n        area->h           = round(rect.height);\n\n        area_i++;\n    }\n\n    return final_rect_count;\n}\n"
  },
  {
    "path": "src/target_detection.h",
    "content": "#ifndef __TARGET_DETECTION_INCLUDED__\n#define __TARGET_DETECTION_INCLUDED__\n\n#ifdef __cplusplus\n#define EXTERNC extern \"C\"\n#else\n#define EXTERNC\n#endif\n\n#if OPENCV_ENABLED\n\n#include \"utils.h\"\n\n#include <stdint.h>\n#include <wayland-client.h>\n\nEXTERNC int compute_target_from_img_buffer(\n    void *data, uint32_t height, uint32_t width, uint32_t stride,\n    enum wl_shm_format format, enum wl_output_transform transform,\n    struct rect initial_area, struct rect **areas\n);\n\n#endif\n\n#undef EXTERNC\n\n#endif\n"
  },
  {
    "path": "src/test_label.c",
    "content": "#include \"log.h\"\n#include \"src/label.h\"\n\n#include <string.h>\n\nint main() {\n    label_symbols_t *label_symbols = label_symbols_from_str(\"abcdé\");\n    if (!label_symbols) {\n        LOG_ERR(\"`label_symbolss_from_str` should not have returned null.\");\n        return 1;\n    }\n\n    if (label_symbols->num_symbols != 5) {\n        LOG_ERR(\"Expected 5 symbols, got %d.\", label_symbols->num_symbols);\n        return 2;\n    }\n\n    char *s = label_symbols_idx_to_ptr(label_symbols, 0);\n    if (strcmp(s, \"a\")) {\n        LOG_ERR(\"No match\");\n        LOG_ERR(\"Given string: '%s'\", s);\n        return 3;\n    }\n\n    char *symbols[] = {\n        \"a\", \"b\", \"c\", \"d\", \"é\",\n    };\n\n    for (int i = 0; i < sizeof(symbols) / sizeof(symbols[0]); i++) {\n        int symbol_idx = label_symbols_find_idx(label_symbols, symbols[i]);\n        if (symbol_idx != i) {\n            LOG_ERR(\n                \"Wrong index %d (expected %d) for symbol '%s'\", symbol_idx, i,\n                symbols[i]\n            );\n            return 4;\n        }\n    }\n\n    label_selection_t *label_selection =\n        label_selection_new(label_symbols, 100);\n    int label_selection_str_buf_size =\n        label_selection_str_max_len(label_selection) + 1;\n    if (label_selection_str_buf_size != 7) {\n        LOG_ERR(\n            \"Wrong label_selection_str_buffer_size = %d\",\n            label_selection_str_buf_size\n        );\n\n        return 5;\n    }\n\n    char label_selection_str_buf[label_selection_str_buf_size];\n    int  idx;\n\n    for (int i = 0; i < 100; i++) {\n        label_selection_set_from_idx(label_selection, i);\n        idx = label_selection_to_idx(label_selection);\n        if (idx != i) {\n            LOG_ERR(\"Wrong index %d, expected %d.\", idx, i);\n            label_selection_str(label_selection, label_selection_str_buf);\n            LOG_ERR(\"Selection: '%s'\", label_selection_str_buf);\n            return 6;\n        }\n    }\n\n    label_selection_clear(label_selection);\n    label_selection_append(label_selection, 4);\n    label_selection_append(label_selection, 2);\n\n    label_selection_str(label_selection, label_selection_str_buf);\n    if (strcmp(label_selection_str_buf, \"éc\")) {\n        LOG_ERR(\"Wrong selection string '%s'\", label_selection_str_buf);\n        return 7;\n    }\n\n    label_selection_append(label_selection, 0);\n    if ((idx = label_selection_to_idx(label_selection)) != 14) {\n        LOG_ERR(\"Wrong index %d\", idx);\n        return 8;\n    }\n\n    if (!label_selection_incr(label_selection)) {\n        LOG_ERR(\"We should not be overflowing here.\");\n        return 9;\n    }\n\n    if ((idx = label_selection_to_idx(label_selection)) != 15) {\n        LOG_ERR(\"Wrong index %d\", idx);\n        return 10;\n    }\n\n    char label_selection_str_buf_1[label_selection_str_buf_size];\n\n    label_selection_str_split(\n        label_selection, label_selection_str_buf, label_selection_str_buf_1, 1\n    );\n    if (strcmp(label_selection_str_buf, \"a\")) {\n        LOG_ERR(\"Wrong prefix '%s'\", label_selection_str_buf);\n        return 11;\n    }\n    if (strcmp(label_selection_str_buf_1, \"da\")) {\n        LOG_ERR(\"Wrong suffix '%s'\", label_selection_str_buf_1);\n        return 12;\n    }\n\n    // Tests with the unicode character not at end-of-string\n\n    label_symbols_t *alt_label_symbols = label_symbols_from_str(\"abcdéfghi\");\n    label_selection_t *alt_selection =\n        label_selection_new(alt_label_symbols, 100);\n    int alt_selection_str_buf_size =\n        label_selection_str_max_len(alt_selection) + 1;\n    if (alt_selection_str_buf_size != 7) {\n        LOG_ERR(\n            \"Wrong label_selection_str_buffer_size = %d\",\n            alt_selection_str_buf_size\n        );\n\n        return 13;\n    }\n\n    char *alt_symbols[] = {\n        \"a\", \"b\", \"c\", \"d\", \"é\", \"f\", \"g\", \"h\", \"i\",\n    };\n\n    for (int i = 0; i < 9; i++) {\n        int symbol_idx =\n            label_symbols_find_idx(alt_label_symbols, alt_symbols[i]);\n        if (symbol_idx != i) {\n            LOG_ERR(\n                \"Wrong index %d (expected %d) for symbol '%s'\", symbol_idx, i,\n                symbols[i]\n            );\n            return 14;\n        }\n    }\n\n    label_selection_free(label_selection);\n    label_symbols_free(label_symbols);\n    return 0;\n}\n"
  },
  {
    "path": "src/utils.c",
    "content": "#include <stdint.h>\n#include <string.h>\n\nint min(int a, int b) {\n    return a < b ? a : b;\n}\n\nint max(int a, int b) {\n    return a > b ? a : b;\n}\n\nint str_to_rune(char *str, uint32_t *rune) {\n    unsigned char *c = ((unsigned char *)str);\n\n    // `\\0`, End of string byte.\n    if (*c == 0) {\n        *rune = 0;\n        return 0;\n    }\n\n    uint32_t value;\n    int      size;\n\n    if ((*c & 0b10000000) == 0) {\n        value = *c & 0b01111111;\n        size  = 1;\n    } else if ((*c & 0b11100000) == 0b11000000) {\n        value = *c & 0b00011111;\n        size  = 2;\n    } else if ((*c & 0b11110000) == 0b11100000) {\n        value = *c & 0b00001111;\n        size  = 3;\n    } else if ((*c & 0b11111000) == 0b11110000) {\n        value = *c & 0b00000111;\n        size  = 4;\n    } else {\n        return -1;\n    }\n\n    for (int i = 1; i < size; i++) {\n        c++;\n        if ((*c & 0b11000000) != 0b10000000) {\n            return -1;\n        }\n\n        value <<= 6;\n        value  += *c & 0b00111111;\n    }\n\n    *rune = value;\n    return size;\n}\n\nint find_str(char **strs, size_t len, char *to_find) {\n    int matched_i = -1;\n    for (int i = 0; i < len; i++) {\n        if (strcmp(to_find, strs[i]) == 0) {\n            matched_i = i;\n            break;\n        }\n    }\n\n    return matched_i;\n}\n"
  },
  {
    "path": "src/utils.h",
    "content": "#ifndef __UTILS_H_INCLUDED__\n#define __UTILS_H_INCLUDED__\n\n#include <stddef.h>\n#include <stdint.h>\n\nstruct rect {\n    int32_t x;\n    int32_t y;\n    int32_t w;\n    int32_t h;\n};\n\nenum click {\n    CLICK_NONE = 0,\n    CLICK_LEFT_BTN,\n    CLICK_RIGHT_BTN,\n    CLICK_MIDDLE_BTN,\n};\n\nint max(int a, int b);\nint min(int a, int b);\nint find_str(char **strs, size_t len, char *to_find);\n\n// Extract first rune (32 bit UTF-8 code) in string.\n// Return its encoded length in bytes or < 0 if invalid.\nint str_to_rune(char *s, uint32_t *rune);\n\n#endif\n"
  },
  {
    "path": "src/utils_cairo.c",
    "content": "#include \"utils_cairo.h\"\n\n#include <cairo.h>\n\nvoid cairo_set_source_u32(void *cairo, uint32_t color) {\n    cairo_set_source_rgba(\n        (cairo_t *)cairo, (color >> 24 & 0xff) / 255.0,\n        (color >> 16 & 0xff) / 255.0, (color >> 8 & 0xff) / 255.0,\n        (color & 0xff) / 255.0\n    );\n}\n"
  },
  {
    "path": "src/utils_cairo.h",
    "content": "#ifndef __CAIRO_UTILS_H_INCLUDED__\n#define __CAIRO_UTILS_H_INCLUDED__\n\n#include <stdint.h>\n\nvoid cairo_set_source_u32(void *cairo, uint32_t color);\n\n#endif\n"
  },
  {
    "path": "src/utils_wayland.c",
    "content": "#include \"utils_wayland.h\"\n\n#include \"state.h\"\n#include \"wlr-virtual-pointer-unstable-v1-client-protocol.h\"\n\n#include <wayland-client.h>\n\nstatic void _apply_transform(\n    uint32_t *x, uint32_t *y, uint32_t *width, uint32_t *height,\n    enum wl_output_transform transform\n) {\n    uint32_t temp;\n\n    switch (transform) {\n    case WL_OUTPUT_TRANSFORM_NORMAL:\n        break;\n\n    case WL_OUTPUT_TRANSFORM_90:\n        temp = *x;\n        *x   = *y;\n        *y   = *width - temp;\n\n        temp    = *width;\n        *width  = *height;\n        *height = temp;\n        break;\n\n    case WL_OUTPUT_TRANSFORM_180:\n        *x = *width - *x;\n        *y = *height - *y;\n        break;\n\n    case WL_OUTPUT_TRANSFORM_270:\n        temp = *x;\n        *x   = *height - *y;\n        *y   = temp;\n\n        temp    = *width;\n        *width  = *height;\n        *height = temp;\n        break;\n\n    case WL_OUTPUT_TRANSFORM_FLIPPED:\n        *x = *width - *x;\n        break;\n\n    case WL_OUTPUT_TRANSFORM_FLIPPED_90:\n        *x = *width - *x;\n        _apply_transform(x, y, width, height, WL_OUTPUT_TRANSFORM_90);\n        break;\n\n    case WL_OUTPUT_TRANSFORM_FLIPPED_180:\n        *x = *width - *x;\n        _apply_transform(x, y, width, height, WL_OUTPUT_TRANSFORM_180);\n        break;\n\n    case WL_OUTPUT_TRANSFORM_FLIPPED_270:\n        *x = *width - *x;\n        _apply_transform(x, y, width, height, WL_OUTPUT_TRANSFORM_270);\n        break;\n    }\n}\n\nvoid move_pointer(\n    struct state *state, uint32_t x, uint32_t y, enum click click\n) {\n    if (!state->wl_virtual_pointer_mgr) {\n        // We running in `--print-only` mode.\n        return;\n    }\n\n    wl_display_roundtrip(state->wl_display);\n\n    struct zwlr_virtual_pointer_v1 *virt_pointer =\n        zwlr_virtual_pointer_manager_v1_create_virtual_pointer_with_output(\n            state->wl_virtual_pointer_mgr,\n            ((struct seat *)state->seats.next)->wl_seat,\n            state->current_output->wl_output\n        );\n\n    uint32_t output_width  = state->current_output->width;\n    uint32_t output_height = state->current_output->height;\n\n    _apply_transform(\n        &x, &y, &output_width, &output_height, state->current_output->transform\n    );\n\n    zwlr_virtual_pointer_v1_motion_absolute(\n        virt_pointer, 0, x, y, output_width, output_height\n    );\n    zwlr_virtual_pointer_v1_frame(virt_pointer);\n    wl_display_roundtrip(state->wl_display);\n\n    if (state->click != CLICK_NONE) {\n        int btn = 271 + click;\n\n        zwlr_virtual_pointer_v1_button(\n            virt_pointer, 0, btn, WL_POINTER_BUTTON_STATE_PRESSED\n        );\n        zwlr_virtual_pointer_v1_frame(virt_pointer);\n        wl_display_roundtrip(state->wl_display);\n\n        zwlr_virtual_pointer_v1_button(\n            virt_pointer, 0, btn, WL_POINTER_BUTTON_STATE_RELEASED\n        );\n        zwlr_virtual_pointer_v1_frame(virt_pointer);\n        wl_display_roundtrip(state->wl_display);\n    }\n\n    zwlr_virtual_pointer_v1_destroy(virt_pointer);\n}\n"
  },
  {
    "path": "src/utils_wayland.h",
    "content": "#ifndef __UTILS_WAYLAND_H_INCLUDED__\n#define __UTILS_WAYLAND_H_INCLUDED__\n\n#include \"state.h\"\n\nvoid move_pointer(\n    struct state *state, uint32_t x, uint32_t y, enum click click\n);\n\n#endif\n"
  }
]