[
  {
    "path": ".github/workflows/rust.yml",
    "content": "on: [push, pull_request]\n\nname: Rust\n\njobs:\n  check:\n    name: Check\n    runs-on: ubuntu-latest\n    steps:\n      - name: Get required packages\n        run: sudo apt-get update && sudo apt-get install libpango1.0-dev libxkbcommon-dev\n      - uses: actions/checkout@v4\n      - uses: dtolnay/rust-toolchain@stable\n      - name: Check\n        run: cargo check --all --all-features\n\n  test:\n    name: Test Suite\n    runs-on: ubuntu-latest\n    steps:\n      - name: Get required packages\n        run: sudo apt-get update && sudo apt-get install libpango1.0-dev libxkbcommon-dev\n      - uses: actions/checkout@v4\n      - uses: dtolnay/rust-toolchain@stable\n      - name: Tests\n        run: cargo test --all --all-features\n\n  fmt:\n    name: Rustfmt\n    runs-on: ubuntu-latest\n    steps:\n      - name: Get required packages\n        run: sudo apt-get update && sudo apt-get install libpango1.0-dev libxkbcommon-dev\n      - uses: actions/checkout@v4\n      - uses: dtolnay/rust-toolchain@stable\n        with:\n          components: rustfmt\n      - name: Fmt check\n        run: rustfmt --check --edition 2021 $(fdfind -e rs)\n\n  clippy:\n    name: Clippy\n    runs-on: ubuntu-latest\n    steps:\n      - name: Get required packages\n        run: sudo apt-get update && sudo apt-get install libpango1.0-dev libxkbcommon-dev\n      - uses: actions/checkout@v4\n      - uses: dtolnay/rust-toolchain@stable\n        with:\n          components: clippy\n      - name: Clippy check\n        run: cargo clippy --all --all-features -- -D warnings -A unknown-lints\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"wlr-which-key\"\nversion = \"1.3.0\"\nedition = \"2024\"\ndescription = \"Keymap manager for wlroots-based compositors\"\nrepository = \"https://github.com/MaxVerevkin/wlr-which-key/\"\nreadme = \"README.md\"\nlicense = \"GPL-3.0-only\"\nauthors = [\"MaxVerevkin <maxxverr@gmail.com>\"]\n\n[dependencies]\npangocairo = \"0.20\"\nanyhow = \"1\"\nlibc = \"0.2\"\nindexmap = { version = \"2.0\", features = [\"serde\"] }\nserde = { version = \"1\", features = [\"derive\"] }\nserde_yaml = \"0.9\"\nwayrs-client = \"1.0\"\nwayrs-protocols = { version = \"0.14\", features = [\n    \"wlr-layer-shell-unstable-v1\",\n    \"keyboard-shortcuts-inhibit-unstable-v1\",\n] }\nwayrs-utils = { version = \"0.17\", features = [\n    \"shm_alloc\",\n    \"seats\",\n    \"keyboard\",\n] }\nsmart-default = \"0.7.0\"\nclap = { version = \"4.3.0\", default-features = false, features = [\n    \"std\",\n    \"derive\",\n    \"help\",\n    \"usage\",\n] }\n\n[profile.release]\nlto = \"fat\"\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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    {project}  Copyright (C) {year}  {fullname}\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<http://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<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n\n"
  },
  {
    "path": "README.md",
    "content": "# wlr-which-key\n\nKeymap manager for wlroots-based compositors. Inspired by [which-key.nvim](https://github.com/folke/which-key.nvim).\n\n## Installation\n\n[![Packaging status](https://repology.org/badge/vertical-allrepos/wlr-which-key.svg)](https://repology.org/project/wlr-which-key/versions)\n\n### From Source\n\n```sh\ncargo install wlr-which-key --locked\n```\n\n## Usage\n\n```sh\nwlr-which-key [config_name]                    # Start with default menu\nwlr-which-key --initial-keys \"p s\"             # Navigate to submenu or execute command\n```\n\n## Configuration\n\nDefault config file: `$XDG_CONFIG_HOME/wlr-which-key/config.yaml` or `~/.config/wlr-which-key/config.yaml`. Run `wlr-which-key --help` for more info.\n\nKeybindings may be single characters (e.g. `a`, `B`) or [xkb key labels](https://github.com/xkbcommon/libxkbcommon/blob/master/include/xkbcommon/xkbcommon-keysyms.h) (without the `XKB_KEY_` prefix, e.g. `Return`, `Insert`). Ctrl, Alt, and Mod4/Logo modifiers are supported (like `Ctrl+Return` or `Ctrl+Alt+a` or `Mod4+Return` or `Logo+Return`). A `key` may also be a list of strings, in which case a keybinding will match if any of the keys match (e.g. `key: [Left, h]`) will match both left arrow and 'h'.\n\nWhen executed a command will normally end the `wlr_which_key` process. If you want certain commands to keep the UI open after they execute then\nconfigure those specific commands with (`keep_open: true`).\n\nExample config:\n\n```yaml\n# Theming\nfont: JetBrainsMono Nerd Font 12\nbackground: \"#282828d0\"\ncolor: \"#fbf1c7\"\nborder: \"#8ec07c\"\nseparator: \" ➜ \"\nborder_width: 2\ncorner_r: 10\npadding: 15 # Defaults to corner_r\nrows_per_column: 5 # No limit by default\ncolumn_padding: 25 # Defaults to padding\n\n# Anchor and margin\nanchor: center # One of center, left, right, top, bottom, bottom-left, top-left, etc.\n# Only relevant when anchor is not center\nmargin_right: 0\nmargin_bottom: 0\nmargin_left: 0\nmargin_top: 0\n\n# namespace to use for the layer shell surface\nnamespace: \"wlr_which_key\"\n\n# Permits key bindings that conflict with compositor key bindings.\n# Default is `false`.\ninhibit_compositor_keyboard_shortcuts: true\n\n# Try to guess the correct keyboard layout to use. Default is `false`.\nauto_kbd_layout: true\n\nmenu:\n  - key: \"p\"\n    desc: Power\n    submenu:\n      - key: \"s\"\n        desc: Sleep\n        cmd: systemctl suspend\n      - key: \"r\"\n        desc: Reboot\n        cmd: reboot\n      - key: \"o\"\n        desc: Off\n        cmd: poweroff\n  - key: \"l\"\n    desc: Laptop Screen\n    submenu:\n      - key: \"t\"\n        desc: Toggle On/Off\n        cmd: toggle-laptop-display.sh\n      - key: \"s\"\n        desc: Scale\n        submenu:\n          - key: \"1\"\n            desc: Set Scale to 1.0\n            cmd: wlr-randr --output eDP-1 --scale 1\n          - key: \"2\"\n            desc: Set Scale to 1.1\n            cmd: wlr-randr --output eDP-1 --scale 1.1\n          - key: \"3\"\n            desc: Set Scale to 1.2\n            cmd: wlr-randr --output eDP-1 --scale 1.2\n          - key: \"4\"\n            desc: Set Scale to 1.3\n            cmd: wlr-randr --output eDP-1 --scale 1.3\n```\n\n<details>\n  <summary> Old config format (v1.1.0 and earlier) </summary>\n\n  ```yaml\n  # Theming\n  font: JetBrainsMono Nerd Font 12\n  background: \"#282828d0\"\n  color: \"#fbf1c7\"\n  border: \"#8ec07c\"\n  separator: \" ➜ \"\n  border_width: 2\n  corner_r: 10\n  padding: 15 # Defaults to corner_r\n\n  # Anchor and margin\n  anchor: center # One of center, left, right, top, bottom, bottom-left, top-left, etc.\n  # Only relevant when anchor is not center\n  margin_right: 0\n  margin_bottom: 0\n  margin_left: 0\n  margin_top: 0\n\n  menu:\n    \"w\":\n      desc: WiFi\n      submenu:\n        \"t\": { desc: Toggle, cmd: wifi_toggle.sh }\n        \"c\": { desc: Connections, cmd: kitty --class nmtui-connect nmtui-connect }\n    \"p\":\n      desc: Power\n      submenu:\n        \"s\": { desc: Sleep, cmd: systemctl suspend }\n        \"r\": { desc: Reboot, cmd: reboot }\n        \"o\": { desc: Off, cmd: poweroff }\n    \"t\":\n      desc: Theme\n      submenu:\n        \"d\": { desc: Dark, cmd: dark-theme on }\n        \"l\": { desc: Light, cmd: dark-theme off }\n        \"t\": { desc: Toggle, cmd: dark-theme toggle, keep_open: true }\n    \"l\":\n      desc: Laptop Screen\n      submenu:\n        \"t\": { desc: Toggle On/Off, cmd: toggle-laptop-display.sh }\n        \"s\":\n          desc: Scale\n          submenu:\n            \"1\": { desc: Set Scale to 1.0, cmd: wlr-randr --output eDP-1 --scale 1 }\n            \"2\": { desc: Set Scale to 1.1, cmd: wlr-randr --output eDP-1 --scale 1.1 }\n            \"3\": { desc: Set Scale to 1.2, cmd: wlr-randr --output eDP-1 --scale 1.2 }\n            \"4\": { desc: Set Scale to 1.3, cmd: wlr-randr --output eDP-1 --scale 1.3 }\n  ```\n</details>\n\n![image](https://user-images.githubusercontent.com/34583604/233025292-af0d5798-1854-4809-b08f-2e8f1a65b3ce.png)\n\n![image](https://user-images.githubusercontent.com/34583604/233025368-e59a386a-6a52-4168-a6e3-5102ea6329cf.png)\n"
  },
  {
    "path": "src/color.rs",
    "content": "use pangocairo::cairo::Context;\nuse serde::de;\nuse std::fmt;\nuse std::str::FromStr;\n\n#[derive(Debug, Clone, Copy, PartialEq)]\npub struct Color {\n    red: f64,\n    green: f64,\n    blue: f64,\n    alpha: f64,\n}\n\nimpl Color {\n    pub const TRANSPARENT: Self = Self {\n        red: 0.0,\n        green: 0.0,\n        blue: 0.0,\n        alpha: 0.0,\n    };\n\n    pub fn apply(self, cr: &Context) {\n        if self.alpha.is_nan() {\n            cr.set_source_rgb(self.red, self.green, self.blue);\n        } else {\n            cr.set_source_rgba(self.red, self.green, self.blue, self.alpha);\n        }\n    }\n\n    pub fn from_rgba(r: u8, g: u8, b: u8, a: u8) -> Self {\n        Self {\n            red: r as f64 / 255.0,\n            green: g as f64 / 255.0,\n            blue: b as f64 / 255.0,\n            alpha: if a == 255 { f64::NAN } else { a as f64 / 255.0 },\n        }\n    }\n\n    pub fn from_rgba_hex(hex: u32) -> Self {\n        let r = (hex >> 24) as u8;\n        let g = (hex >> 16) as u8;\n        let b = (hex >> 8) as u8;\n        let a = hex as u8;\n        Self::from_rgba(r, g, b, a)\n    }\n}\n\nimpl FromStr for Color {\n    type Err = ();\n\n    fn from_str(color: &str) -> Result<Self, Self::Err> {\n        let rgb = color.get(1..7).ok_or(())?;\n        let rgb = u32::from_str_radix(rgb, 16).map_err(|_| ())?;\n        let r = (rgb >> 16) as u8;\n        let g = (rgb >> 8) as u8;\n        let b = rgb as u8;\n\n        let a = match color.get(7..9) {\n            Some(a) => u8::from_str_radix(a, 16).map_err(|_| ())?,\n            None => 255,\n        };\n\n        Ok(Self::from_rgba(r, g, b, a))\n    }\n}\n\nimpl<'de> de::Deserialize<'de> for Color {\n    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n    where\n        D: de::Deserializer<'de>,\n    {\n        struct ColorVisitor;\n\n        impl de::Visitor<'_> for ColorVisitor {\n            type Value = Color;\n\n            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n                formatter.write_str(\"RBG or RGBA color (in hex)\")\n            }\n\n            fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>\n            where\n                E: de::Error,\n            {\n                s.parse()\n                    .map_err(|_| E::custom(format!(\"'{s}' is not a valid RGB/RGBA color\")))\n            }\n        }\n\n        deserializer.deserialize_str(ColorVisitor)\n    }\n}\n"
  },
  {
    "path": "src/config/anchor.rs",
    "content": "use serde::Deserialize;\nuse wayrs_protocols::wlr_layer_shell_unstable_v1::zwlr_layer_surface_v1::Anchor;\n\n/// Light wrapper around `Anchor` which also supports the \"no anchor\" value.\n///\n/// This type is also requires to derive `Deserialize` for the foreign type.\n#[derive(Deserialize, Default, Clone, Copy)]\n#[serde(rename_all(deserialize = \"kebab-case\"))]\npub enum ConfigAnchor {\n    #[default]\n    Center,\n    Top,\n    Bottom,\n    Left,\n    Right,\n    TopLeft,\n    TopRight,\n    BottomLeft,\n    BottomRight,\n}\n\n/// Convert this anchor into the type expected by `wayrs`.\nimpl From<ConfigAnchor> for Anchor {\n    fn from(value: ConfigAnchor) -> Self {\n        match value {\n            ConfigAnchor::Center => Anchor::empty(),\n            ConfigAnchor::Top => Anchor::Top,\n            ConfigAnchor::Bottom => Anchor::Bottom,\n            ConfigAnchor::Left => Anchor::Left,\n            ConfigAnchor::Right => Anchor::Right,\n            ConfigAnchor::TopLeft => Anchor::Top | Anchor::Left,\n            ConfigAnchor::TopRight => Anchor::Top | Anchor::Right,\n            ConfigAnchor::BottomLeft => Anchor::Bottom | Anchor::Left,\n            ConfigAnchor::BottomRight => Anchor::Bottom | Anchor::Right,\n        }\n    }\n}\n"
  },
  {
    "path": "src/config/compat.rs",
    "content": "use indexmap::IndexMap;\nuse serde::Deserialize;\nuse smart_default::SmartDefault;\n\nuse crate::color::Color;\nuse crate::key::SingleKey;\n\nuse super::{ConfigAnchor, Font, Namespace};\n\n#[derive(Deserialize, Default)]\n#[serde(transparent)]\npub struct Entries(pub IndexMap<SingleKey, Entry>);\n\n#[derive(Deserialize, SmartDefault)]\n#[serde(deny_unknown_fields, default)]\npub struct Config {\n    #[default(Color::from_rgba_hex(0x282828ff))]\n    pub background: Color,\n    #[default(Color::from_rgba_hex(0xfbf1c7ff))]\n    pub color: Color,\n    #[default(Color::from_rgba_hex(0x8ec07cff))]\n    pub border: Color,\n\n    pub anchor: ConfigAnchor,\n    pub margin_top: i32,\n    pub margin_right: i32,\n    pub margin_bottom: i32,\n    pub margin_left: i32,\n\n    #[default(Font::new(\"monospace 10\"))]\n    pub font: Font,\n    #[default(\" ➜ \".into())]\n    pub separator: String,\n    #[default(4.0)]\n    pub border_width: f64,\n    #[default(20.0)]\n    pub corner_r: f64,\n    // defaults to `corner_r`\n    pub padding: Option<f64>,\n\n    pub menu: Entries,\n}\n\n#[derive(Deserialize)]\n#[serde(untagged, deny_unknown_fields)]\npub enum Entry {\n    Cmd {\n        cmd: String,\n        desc: String,\n        #[serde(default)]\n        keep_open: bool,\n    },\n    Recursive {\n        submenu: Entries,\n        desc: String,\n    },\n}\n\nimpl From<Config> for super::Config {\n    fn from(value: Config) -> Self {\n        fn map_entries(value: Entries) -> Vec<super::Entry> {\n            value\n                .0\n                .into_iter()\n                .map(|(key, entry)| match entry {\n                    Entry::Cmd {\n                        cmd,\n                        desc,\n                        keep_open,\n                    } => super::Entry::Cmd {\n                        key: key.into(),\n                        cmd,\n                        desc,\n                        keep_open,\n                    },\n                    Entry::Recursive { submenu, desc } => super::Entry::Recursive {\n                        key: key.into(),\n                        submenu: map_entries(submenu),\n                        desc,\n                    },\n                })\n                .collect()\n        }\n\n        Self {\n            background: value.background,\n            color: value.color,\n            border: value.border,\n            anchor: value.anchor,\n            margin_top: value.margin_top,\n            margin_right: value.margin_right,\n            margin_bottom: value.margin_bottom,\n            margin_left: value.margin_left,\n            font: value.font,\n            separator: value.separator,\n            border_width: value.border_width,\n            corner_r: value.corner_r,\n            padding: value.padding,\n            rows_per_column: None,\n            column_padding: None,\n            menu: map_entries(value.menu),\n            inhibit_compositor_keyboard_shortcuts: false,\n            auto_kbd_layout: false,\n            namespace: Namespace::new(c\"wlr_which_key\".to_owned()),\n        }\n    }\n}\n"
  },
  {
    "path": "src/config/entry.rs",
    "content": "use anyhow::{Context, bail};\nuse serde::Deserialize;\n\nuse crate::key::Key;\n\n#[derive(Deserialize)]\n#[serde(try_from = \"RawEntry\")]\npub enum Entry {\n    Cmd {\n        key: Key,\n        cmd: String,\n        desc: String,\n        keep_open: bool,\n    },\n    Recursive {\n        key: Key,\n        submenu: Vec<Self>,\n        desc: String,\n    },\n}\n\n#[derive(Deserialize)]\n#[serde(deny_unknown_fields)]\nstruct RawEntry {\n    key: Key,\n    desc: String,\n    cmd: Option<String>,\n    keep_open: Option<bool>,\n    submenu: Option<Vec<Entry>>,\n}\n\nimpl TryFrom<RawEntry> for Entry {\n    type Error = anyhow::Error;\n\n    fn try_from(value: RawEntry) -> Result<Self, Self::Error> {\n        if let Some(submenu) = value.submenu {\n            if value.cmd.is_some() {\n                bail!(\"cannot have both 'submenu' and 'cmd'\");\n            }\n            if value.keep_open.is_some() {\n                bail!(\"cannot have both 'submenu' and 'keep_open'\");\n            }\n            Ok(Self::Recursive {\n                key: value.key,\n                submenu,\n                desc: value.desc,\n            })\n        } else {\n            Ok(Self::Cmd {\n                key: value.key,\n                cmd: value\n                    .cmd\n                    .context(\"either or 'submenu' or 'cmd' is required\")?,\n                desc: value.desc,\n                keep_open: value.keep_open.unwrap_or(false),\n            })\n        }\n    }\n}\n"
  },
  {
    "path": "src/config/font.rs",
    "content": "use std::fmt;\n\nuse pangocairo::pango::FontDescription;\nuse serde::de;\n\npub struct Font(pub FontDescription);\n\nimpl Font {\n    pub fn new(desc: &str) -> Self {\n        Self(FontDescription::from_string(desc))\n    }\n}\n\nimpl<'de> de::Deserialize<'de> for Font {\n    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n    where\n        D: de::Deserializer<'de>,\n    {\n        struct FontVisitor;\n\n        impl de::Visitor<'_> for FontVisitor {\n            type Value = Font;\n\n            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n                formatter.write_str(\"font description\")\n            }\n\n            fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>\n            where\n                E: de::Error,\n            {\n                Ok(Font::new(s))\n            }\n        }\n\n        deserializer.deserialize_str(FontVisitor)\n    }\n}\n"
  },
  {
    "path": "src/config/namespace.rs",
    "content": "use std::{\n    ffi::{CString, NulError},\n    str::FromStr,\n};\n\nuse serde::de;\n\n#[derive(Default)]\npub struct Namespace(pub CString);\n\nimpl Namespace {\n    pub fn new(namespace: CString) -> Self {\n        Self(namespace)\n    }\n}\n\nimpl FromStr for Namespace {\n    type Err = NulError;\n\n    fn from_str(s: &str) -> Result<Self, Self::Err> {\n        Ok(Self::new(CString::new(s)?))\n    }\n}\n\nimpl<'de> de::Deserialize<'de> for Namespace {\n    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n    where\n        D: de::Deserializer<'de>,\n    {\n        struct NamespaceVisitor;\n\n        impl de::Visitor<'_> for NamespaceVisitor {\n            type Value = Namespace;\n\n            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {\n                formatter.write_str(\"namespace name\")\n            }\n\n            fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>\n            where\n                E: de::Error,\n            {\n                s.parse().map_err(|_| {\n                    E::custom(format!(\"'{}' contains a null character\", s.escape_debug()))\n                })\n            }\n        }\n\n        deserializer.deserialize_str(NamespaceVisitor)\n    }\n}\n"
  },
  {
    "path": "src/config.rs",
    "content": "mod anchor;\nmod compat;\nmod entry;\nmod font;\nmod namespace;\n\nuse std::env;\nuse std::fs::read_to_string;\nuse std::path::PathBuf;\n\nuse anyhow::{Context, Result, bail};\nuse serde::Deserialize;\nuse smart_default::SmartDefault;\n\npub use self::anchor::ConfigAnchor;\npub use self::entry::Entry;\npub use self::font::Font;\npub use self::namespace::Namespace;\nuse crate::color::Color;\n\n#[derive(Deserialize, SmartDefault)]\n#[serde(deny_unknown_fields, default)]\npub struct Config {\n    #[default(Color::from_rgba_hex(0x282828ff))]\n    pub background: Color,\n    #[default(Color::from_rgba_hex(0xfbf1c7ff))]\n    pub color: Color,\n    #[default(Color::from_rgba_hex(0x8ec07cff))]\n    pub border: Color,\n\n    pub anchor: ConfigAnchor,\n    pub margin_top: i32,\n    pub margin_right: i32,\n    pub margin_bottom: i32,\n    pub margin_left: i32,\n\n    #[default(Font::new(\"monospace 10\"))]\n    pub font: Font,\n    #[default(\" ➜ \".into())]\n    pub separator: String,\n    #[default(4.0)]\n    pub border_width: f64,\n    #[default(20.0)]\n    pub corner_r: f64,\n    pub padding: Option<f64>,\n    pub rows_per_column: Option<usize>,\n    pub column_padding: Option<f64>,\n\n    pub inhibit_compositor_keyboard_shortcuts: bool,\n    pub auto_kbd_layout: bool,\n\n    pub menu: Vec<Entry>,\n\n    #[default(Namespace::new(c\"wlr_which_key\".to_owned()))]\n    pub namespace: Namespace,\n}\n\nimpl Config {\n    pub fn new(name: &str) -> Result<Self> {\n        let mut config_path = config_dir().context(\"Cound not find config directory\")?;\n        config_path.push(\"wlr-which-key\");\n        config_path.push(name);\n        config_path.set_extension(\"yaml\");\n\n        if !config_path.exists() {\n            bail!(\"config file not found: {}\", config_path.display());\n        }\n\n        let config_str = read_to_string(config_path).context(\"Failed to read configuration\")?;\n\n        match serde_yaml::from_str::<Self>(&config_str)\n            .context(\"Failed to deserialize configuration\")\n        {\n            Ok(config) => Ok(config),\n            Err(err) => match serde_yaml::from_str::<compat::Config>(&config_str) {\n                Ok(compat) => {\n                    eprintln!(\n                        \"Warning: using the old config format, which will be removed in a future version.\"\n                    );\n                    Ok(compat.into())\n                }\n                Err(_compat_err) => Err(err),\n            },\n        }\n    }\n\n    pub fn padding(&self) -> f64 {\n        self.padding.unwrap_or(self.corner_r)\n    }\n\n    pub fn column_padding(&self) -> f64 {\n        self.column_padding.unwrap_or_else(|| self.padding())\n    }\n}\n\nfn config_dir() -> Option<PathBuf> {\n    env::var_os(\"XDG_CONFIG_HOME\")\n        .map(PathBuf::from)\n        .or_else(|| Some(PathBuf::from(env::var_os(\"HOME\")?).join(\".config\")))\n}\n"
  },
  {
    "path": "src/key.rs",
    "content": "use std::fmt;\nuse std::str::FromStr;\n\nuse serde::de;\nuse wayrs_utils::keyboard::xkb;\n\n#[derive(Clone)]\npub struct Key {\n    any_of: Vec<SingleKey>,\n}\n\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]\npub struct ModifierState {\n    pub mod_ctrl: bool,\n    pub mod_alt: bool,\n    pub mod_mod4: bool,\n}\n\nimpl ModifierState {\n    pub fn from_xkb_state(xkb: &xkb::State) -> Self {\n        Self {\n            mod_ctrl: xkb.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE),\n            mod_alt: xkb.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE),\n            mod_mod4: xkb.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE),\n        }\n    }\n}\n\n#[derive(Clone, PartialEq, Eq, Hash)]\npub struct SingleKey {\n    pub keysym: xkb::Keysym,\n    pub repr: String,\n    pub modifiers: ModifierState,\n}\n\nimpl Key {\n    pub fn matches(&self, sym: xkb::Keysym, modifiers: ModifierState) -> bool {\n        self.any_of\n            .iter()\n            .any(|key| key.modifiers == modifiers && key.keysym == sym)\n    }\n}\n\nimpl fmt::Display for Key {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        for (i, key) in self.any_of.iter().enumerate() {\n            f.write_str(&key.repr)?;\n            if i + 1 != self.any_of.len() {\n                f.write_str(\" | \")?\n            }\n        }\n        Ok(())\n    }\n}\n\nimpl From<SingleKey> for Key {\n    fn from(value: SingleKey) -> Self {\n        Self {\n            any_of: vec![value],\n        }\n    }\n}\n\nimpl FromStr for SingleKey {\n    type Err = String;\n\n    fn from_str(s: &str) -> Result<Self, Self::Err> {\n        if s == \"+\" {\n            return Ok(Self {\n                keysym: xkb::Keysym::plus,\n                repr: String::from(\"+\"),\n                modifiers: Default::default(),\n            });\n        }\n\n        let mut components = s.split('+');\n        let key = components.next_back().unwrap_or(s);\n        let keysym = to_keysym(key).ok_or_else(|| format!(\"invalid key '{key}'\"))?;\n\n        let mut modifiers = ModifierState::default();\n        for modifier in components {\n            if modifier.eq_ignore_ascii_case(\"ctrl\") {\n                modifiers.mod_ctrl = true;\n            } else if modifier.eq_ignore_ascii_case(\"alt\") {\n                modifiers.mod_alt = true;\n            } else if modifier.eq_ignore_ascii_case(\"mod4\") || modifier.eq_ignore_ascii_case(\"logo\")\n            {\n                modifiers.mod_mod4 = true;\n            } else {\n                return Err(format!(\"unknown modifier '{modifier}\"));\n            }\n        }\n\n        Ok(Self {\n            keysym,\n            repr: s.to_owned(),\n            modifiers,\n        })\n    }\n}\n\nfn to_keysym(s: &str) -> Option<xkb::Keysym> {\n    let mut chars = s.chars();\n    let first_char = chars.next()?;\n\n    let keysym = if chars.next().is_none() {\n        xkb::utf32_to_keysym(first_char as u32)\n    } else {\n        xkb::keysym_from_name(s, xkb::KEYSYM_NO_FLAGS)\n    };\n\n    if keysym.raw() == xkb::keysyms::KEY_NoSymbol {\n        None\n    } else {\n        Some(keysym)\n    }\n}\n\nimpl<'de> de::Deserialize<'de> for Key {\n    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n    where\n        D: de::Deserializer<'de>,\n    {\n        struct KeyVisitor;\n\n        impl<'de> de::Visitor<'de> for KeyVisitor {\n            type Value = Key;\n\n            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n                formatter.write_str(\"a key or a list of keys\")\n            }\n\n            fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>\n            where\n                E: de::Error,\n            {\n                Ok(Key::from(s.parse::<SingleKey>().map_err(E::custom)?))\n            }\n\n            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>\n            where\n                A: de::SeqAccess<'de>,\n            {\n                let mut any_of = Vec::new();\n                while let Some(next) = seq.next_element()? {\n                    any_of.push(next);\n                }\n                Ok(Key { any_of })\n            }\n        }\n\n        deserializer.deserialize_any(KeyVisitor)\n    }\n}\n\nimpl<'de> de::Deserialize<'de> for SingleKey {\n    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n    where\n        D: de::Deserializer<'de>,\n    {\n        struct KeyVisitor;\n\n        impl de::Visitor<'_> for KeyVisitor {\n            type Value = SingleKey;\n\n            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n                formatter.write_str(\"a key\")\n            }\n\n            fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>\n            where\n                E: de::Error,\n            {\n                s.parse().map_err(E::custom)\n            }\n        }\n\n        deserializer.deserialize_str(KeyVisitor)\n    }\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "mod color;\nmod config;\nmod key;\nmod menu;\nmod text;\n\nuse std::collections::{HashMap, HashSet};\nuse std::f64::consts::{FRAC_PI_2, PI, TAU};\nuse std::io;\nuse std::os::fd::{AsRawFd, RawFd};\nuse std::os::unix::process::CommandExt;\nuse std::process::{Command, Stdio};\nuse std::sync::LazyLock;\nuse std::time::Duration;\n\nuse anyhow::bail;\nuse clap::Parser;\nuse pangocairo::cairo;\n\nuse wayrs_client::object::ObjectId;\nuse wayrs_client::protocol::*;\nuse wayrs_client::proxy::Proxy;\nuse wayrs_client::{Connection, IoMode};\nuse wayrs_client::{EventCtx, global::*};\nuse wayrs_protocols::keyboard_shortcuts_inhibit_unstable_v1::*;\nuse wayrs_protocols::wlr_layer_shell_unstable_v1::*;\nuse wayrs_utils::keyboard::{Keyboard, KeyboardEvent, KeyboardHandler, xkb};\nuse wayrs_utils::seats::{SeatHandler, Seats};\nuse wayrs_utils::shm_alloc::{BufferSpec, ShmAlloc};\nuse wayrs_utils::timer::Timer;\n\nuse crate::key::ModifierState;\n\n#[derive(Debug, Parser)]\n#[command(author, version, about)]\nstruct Args {\n    /// The name of the config file to use.\n    ///\n    /// By default, $XDG_CONFIG_HOME/wlr-which-key/config.yaml or\n    /// ~/.config/wlr-which-key/config.yaml is used.\n    ///\n    /// For example, to use ~/.config/wlr-which-key/print-srceen.yaml, set this to\n    /// \"print-srceen\". An absolute path can be used too, extension is optional.\n    config: Option<String>,\n\n    /// Initial key sequence to navigate to a specific submenu on startup.\n    ///\n    /// Provide a sequence of keys separated by spaces to navigate directly to a submenu.\n    /// For example, \"p s\" would navigate to the submenu at key 'p', then 's'.\n    /// The application will show an error and exit if the key sequence is invalid.\n    #[arg(long, short = 'k')]\n    initial_keys: Option<String>,\n}\n\nstatic DEBUG_LAYOUT: LazyLock<bool> =\n    LazyLock::new(|| std::env::var(\"WLR_WHICH_KEY_LAYOUT_DEBUG\").as_deref() == Ok(\"1\"));\n\nfn main() -> anyhow::Result<()> {\n    let args = Args::parse();\n    let config = config::Config::new(args.config.as_deref().unwrap_or(\"config\"))?;\n    let mut menu = menu::Menu::new(&config)?;\n\n    if let Some(initial_keys) = &args.initial_keys\n        && let Some(initial_action) = menu.navigate_to_key_sequence(initial_keys)?\n    {\n        match initial_action {\n            menu::Action::Submenu(_) => unreachable!(),\n            menu::Action::Quit => return Ok(()),\n            menu::Action::Exec { cmd, keep_open } => {\n                if keep_open {\n                    bail!(\"Initial key sequence cannot trigger an action with keep_open=true\");\n                }\n                exec(&cmd);\n                return Ok(());\n            }\n        }\n    }\n\n    let mut conn = Connection::connect()?;\n    conn.blocking_roundtrip()?;\n    conn.add_registry_cb(wl_registry_cb);\n\n    let wl_compositor: WlCompositor = conn.bind_singleton(4..=6)?;\n    let wlr_layer_shell: ZwlrLayerShellV1 = conn.bind_singleton(2)?;\n    let keyboard_shortcuts_inhibit_manager = match config.inhibit_compositor_keyboard_shortcuts {\n        true => Some(conn.bind_singleton(1)?),\n        false => None,\n    };\n\n    let seats = Seats::new(&mut conn);\n    let shm_alloc = ShmAlloc::bind(&mut conn)?;\n\n    let width = menu.width(&config) as u32;\n    let height = menu.height(&config) as u32;\n\n    let wl_surface = wl_compositor.create_surface_with_cb(&mut conn, wl_surface_cb);\n\n    let layer_surface = wlr_layer_shell.get_layer_surface_with_cb(\n        &mut conn,\n        wl_surface,\n        None,\n        zwlr_layer_shell_v1::Layer::Overlay,\n        config.namespace.0.to_owned(),\n        layer_surface_cb,\n    );\n    layer_surface.set_anchor(&mut conn, config.anchor.into());\n    layer_surface.set_size(&mut conn, width, height);\n    layer_surface.set_margin(\n        &mut conn,\n        config.margin_top,\n        config.margin_right,\n        config.margin_bottom,\n        config.margin_left,\n    );\n    layer_surface.set_keyboard_interactivity(\n        &mut conn,\n        zwlr_layer_surface_v1::KeyboardInteractivity::Exclusive,\n    );\n    wl_surface.commit(&mut conn);\n\n    let mut state = State {\n        shm_alloc,\n        seats,\n        keyboards: Vec::new(),\n        kbd_repeat: None,\n        outputs: Vec::new(),\n        keyboard_shortcuts_inhibit_manager,\n        keyboard_shortcuts_inhibitors: HashMap::new(),\n\n        wl_surface,\n        layer_surface,\n        visible_on_outputs: HashSet::new(),\n        surface_scale: 1,\n        exit: false,\n        configured: false,\n        width,\n        height,\n        throttle_cb: None,\n        throttled: false,\n\n        menu,\n        config,\n    };\n\n    while !state.exit {\n        conn.flush(IoMode::Blocking)?;\n\n        poll(\n            conn.as_raw_fd(),\n            state.kbd_repeat.as_ref().map(|x| x.0.sleep()),\n        )?;\n\n        if let Some((timer, action)) = &mut state.kbd_repeat\n            && timer.tick()\n        {\n            let action = action.clone();\n            state.handle_action(&mut conn, action);\n        }\n\n        match conn.recv_events(IoMode::NonBlocking) {\n            Ok(()) => conn.dispatch_events(&mut state),\n            Err(e) if e.kind() == io::ErrorKind::WouldBlock => (),\n            Err(e) => return Err(e.into()),\n        }\n    }\n\n    Ok(())\n}\n\nstruct State {\n    shm_alloc: ShmAlloc,\n    seats: Seats,\n    keyboards: Vec<Keyboard>,\n    kbd_repeat: Option<(Timer, menu::Action)>,\n    outputs: Vec<Output>,\n    keyboard_shortcuts_inhibit_manager: Option<ZwpKeyboardShortcutsInhibitManagerV1>,\n    keyboard_shortcuts_inhibitors: HashMap<WlSeat, ZwpKeyboardShortcutsInhibitorV1>,\n\n    wl_surface: WlSurface,\n    layer_surface: ZwlrLayerSurfaceV1,\n    visible_on_outputs: HashSet<ObjectId>,\n    surface_scale: u32,\n    exit: bool,\n    configured: bool,\n    width: u32,\n    height: u32,\n    throttle_cb: Option<WlCallback>,\n    throttled: bool,\n\n    menu: menu::Menu,\n    config: config::Config,\n}\n\nstruct Output {\n    wl: WlOutput,\n    reg_name: u32,\n    scale: u32,\n}\n\nimpl State {\n    fn draw(&mut self, conn: &mut Connection<Self>) {\n        if !self.configured {\n            return;\n        }\n\n        if self.throttle_cb.is_some() {\n            self.throttled = true;\n            return;\n        }\n\n        self.throttle_cb = Some(self.wl_surface.frame_with_cb(conn, |ctx| {\n            assert_eq!(ctx.state.throttle_cb, Some(ctx.proxy));\n            ctx.state.throttle_cb = None;\n            if ctx.state.throttled {\n                ctx.state.throttled = false;\n                ctx.state.draw(ctx.conn);\n            }\n        }));\n\n        let scale = if self.wl_surface.version() >= 6 {\n            self.surface_scale\n        } else {\n            self.outputs\n                .iter()\n                .filter(|o| self.visible_on_outputs.contains(&o.wl.id()))\n                .map(|o| o.scale)\n                .max()\n                .unwrap_or(1)\n        };\n\n        let width_f = self.width as f64;\n        let height_f = self.height as f64;\n\n        let (buffer, canvas) = self\n            .shm_alloc\n            .alloc_buffer(\n                conn,\n                BufferSpec {\n                    width: self.width * scale,\n                    height: self.height * scale,\n                    stride: self.width * 4 * scale,\n                    format: wl_shm::Format::Argb8888,\n                },\n            )\n            .expect(\"could not allocate frame shm buffer\");\n\n        let cairo_surf = unsafe {\n            cairo::ImageSurface::create_for_data_unsafe(\n                canvas.as_mut_ptr(),\n                cairo::Format::ARgb32,\n                (self.width * scale) as i32,\n                (self.height * scale) as i32,\n                (self.width * 4 * scale) as i32,\n            )\n            .expect(\"cairo surface\")\n        };\n\n        let cairo_ctx = cairo::Context::new(&cairo_surf).expect(\"cairo context\");\n        cairo_ctx.scale(scale as f64, scale as f64);\n        self.wl_surface.set_buffer_scale(conn, scale as i32);\n\n        // background with rounded corners\n        cairo_ctx.save().unwrap();\n        cairo_ctx.set_operator(cairo::Operator::Source);\n        color::Color::TRANSPARENT.apply(&cairo_ctx);\n        cairo_ctx.paint().unwrap();\n        cairo_ctx.restore().unwrap();\n\n        cairo_ctx.new_sub_path();\n        let half_border = self.config.border_width * 0.5;\n        let r = self.config.corner_r;\n        cairo_ctx.arc(r + half_border, r + half_border, r, PI, 3.0 * FRAC_PI_2);\n        cairo_ctx.arc(\n            width_f - r - half_border,\n            r + half_border,\n            r,\n            3.0 * FRAC_PI_2,\n            TAU,\n        );\n        cairo_ctx.arc(\n            width_f - r - half_border,\n            height_f - r - half_border,\n            r,\n            0.0,\n            FRAC_PI_2,\n        );\n        cairo_ctx.arc(\n            r + half_border,\n            height_f - r - half_border,\n            r,\n            FRAC_PI_2,\n            PI,\n        );\n        cairo_ctx.close_path();\n        self.config.background.apply(&cairo_ctx);\n        cairo_ctx.fill_preserve().unwrap();\n        self.config.border.apply(&cairo_ctx);\n        cairo_ctx.set_line_width(self.config.border_width);\n        cairo_ctx.stroke().unwrap();\n\n        // draw our menu\n        self.menu.render(&self.config, &cairo_ctx).unwrap();\n\n        // Damage the entire window\n        self.wl_surface.damage_buffer(\n            conn,\n            0,\n            0,\n            (self.width * scale) as i32,\n            (self.height * scale) as i32,\n        );\n\n        // Attach and commit to present.\n        self.wl_surface\n            .attach(conn, Some(buffer.into_wl_buffer()), 0, 0);\n        self.wl_surface.commit(conn);\n    }\n\n    fn handle_action(&mut self, conn: &mut Connection<Self>, action: menu::Action) {\n        match action {\n            menu::Action::Quit => {\n                self.exit = true;\n                conn.break_dispatch_loop();\n            }\n            menu::Action::Exec { cmd, keep_open } => {\n                exec(&cmd);\n                if !keep_open {\n                    self.exit = true;\n                    conn.break_dispatch_loop();\n                }\n            }\n            menu::Action::Submenu(page) => {\n                self.menu.set_page(page);\n                self.width = self.menu.width(&self.config) as u32;\n                self.height = self.menu.height(&self.config) as u32;\n                self.layer_surface.set_size(conn, self.width, self.height);\n                self.wl_surface.commit(conn);\n            }\n        }\n    }\n}\n\nimpl SeatHandler for State {\n    fn get_seats(&mut self) -> &mut Seats {\n        &mut self.seats\n    }\n\n    fn seat_added(&mut self, conn: &mut Connection<Self>, seat: WlSeat) {\n        if let Some(inhibit_manager) = self.keyboard_shortcuts_inhibit_manager {\n            self.keyboard_shortcuts_inhibitors.insert(\n                seat,\n                inhibit_manager.inhibit_shortcuts(conn, self.wl_surface, seat),\n            );\n        }\n    }\n\n    fn seat_removed(&mut self, conn: &mut Connection<Self>, seat: WlSeat) {\n        if let Some(inhibitor) = self.keyboard_shortcuts_inhibitors.remove(&seat) {\n            inhibitor.destroy(conn);\n        }\n    }\n\n    fn keyboard_added(&mut self, conn: &mut Connection<Self>, seat: WlSeat) {\n        self.keyboards.push(Keyboard::new(conn, seat));\n    }\n\n    fn keyboard_removed(&mut self, conn: &mut Connection<Self>, seat: WlSeat) {\n        let i = self\n            .keyboards\n            .iter()\n            .position(|k| k.seat() == seat)\n            .unwrap();\n        let keyboard = self.keyboards.swap_remove(i);\n        keyboard.destroy(conn);\n    }\n}\n\nimpl KeyboardHandler for State {\n    fn get_keyboard(&mut self, wl_keyboard: WlKeyboard) -> &mut Keyboard {\n        self.keyboards\n            .iter_mut()\n            .find(|k| k.wl_keyboard() == wl_keyboard)\n            .unwrap()\n    }\n\n    fn key_presed(&mut self, conn: &mut Connection<Self>, event: KeyboardEvent) {\n        self.kbd_repeat = None;\n        let modifiers = ModifierState::from_xkb_state(&event.xkb_state);\n        let action = if let Some(action) = self.menu.get_action(modifiers, event.keysym) {\n            Some(action)\n        } else if self.config.auto_kbd_layout {\n            let mask = XkbMaskState::new(&event.xkb_state);\n            let mut action = None;\n            // Try each layout\n            for layout in 0..event.xkb_state.get_keymap().num_layouts() {\n                mask.with_locked_layout(layout).apply(&event.xkb_state);\n                if let Some(a) = self\n                    .menu\n                    .get_action(modifiers, event.xkb_state.key_get_one_sym(event.keycode))\n                {\n                    action = Some(a);\n                    break;\n                }\n            }\n            mask.apply(&event.xkb_state); // Restore the state\n            action\n        } else {\n            None\n        };\n        if let Some(action) = action {\n            if let Some(repeat) = event.repeat_info {\n                self.kbd_repeat = Some((Timer::new(repeat.delay, repeat.interval), action.clone()));\n            }\n            self.handle_action(conn, action);\n        }\n    }\n\n    fn key_released(&mut self, _: &mut Connection<Self>, _: KeyboardEvent) {\n        self.kbd_repeat = None;\n    }\n}\n\nfn wl_registry_cb(conn: &mut Connection<State>, state: &mut State, event: &wl_registry::Event) {\n    match event {\n        wl_registry::Event::Global(g) if g.is::<WlOutput>() => {\n            state.outputs.push(Output {\n                wl: g.bind_with_cb(conn, 1..=4, wl_output_cb).unwrap(),\n                reg_name: g.name,\n                scale: 1,\n            });\n        }\n        wl_registry::Event::GlobalRemove(name) => {\n            if let Some(output_i) = state.outputs.iter().position(|o| o.reg_name == *name) {\n                let output = state.outputs.swap_remove(output_i);\n                state.visible_on_outputs.remove(&output.wl.id());\n                if output.wl.version() >= 3 {\n                    output.wl.release(conn);\n                }\n            }\n        }\n        _ => (),\n    }\n}\n\nfn wl_output_cb(ctx: EventCtx<State, WlOutput>) {\n    if let wl_output::Event::Scale(scale) = ctx.event {\n        let output = ctx\n            .state\n            .outputs\n            .iter_mut()\n            .find(|o| o.wl == ctx.proxy)\n            .unwrap();\n        let scale: u32 = scale.try_into().unwrap();\n        if output.scale != scale {\n            output.scale = scale;\n            ctx.state.draw(ctx.conn);\n        }\n    }\n}\n\nfn wl_surface_cb(ctx: EventCtx<State, WlSurface>) {\n    assert_eq!(ctx.proxy, ctx.state.wl_surface);\n    match ctx.event {\n        wl_surface::Event::Enter(output) => {\n            ctx.state.visible_on_outputs.insert(output);\n            ctx.state.draw(ctx.conn);\n        }\n        wl_surface::Event::Leave(output) => {\n            ctx.state.visible_on_outputs.remove(&output);\n        }\n        wl_surface::Event::PreferredBufferScale(scale) => {\n            assert!(scale >= 1);\n            let scale = scale as u32;\n            if ctx.state.surface_scale != scale {\n                ctx.state.surface_scale = scale;\n                ctx.state.draw(ctx.conn);\n            }\n        }\n        _ => (),\n    }\n}\n\nfn layer_surface_cb(ctx: EventCtx<State, ZwlrLayerSurfaceV1>) {\n    assert_eq!(ctx.proxy, ctx.state.layer_surface);\n    match ctx.event {\n        zwlr_layer_surface_v1::Event::Configure(args) => {\n            if args.width != 0 {\n                ctx.state.width = args.width;\n            }\n            if args.height != 0 {\n                ctx.state.height = args.height;\n            }\n            ctx.state.configured = true;\n            ctx.proxy.ack_configure(ctx.conn, args.serial);\n            ctx.state.draw(ctx.conn);\n        }\n        zwlr_layer_surface_v1::Event::Closed => {\n            ctx.state.exit = true;\n            ctx.conn.break_dispatch_loop();\n        }\n        _ => (),\n    }\n}\n\nfn poll(fd: RawFd, timeout: Option<Duration>) -> io::Result<()> {\n    let mut fds = [libc::pollfd {\n        fd,\n        events: libc::POLLIN,\n        revents: 0,\n    }];\n    let res = unsafe {\n        libc::poll(\n            fds.as_mut_ptr(),\n            1,\n            timeout.map_or(-1, |t| t.as_millis() as _),\n        )\n    };\n    match res {\n        -1 => Err(io::Error::last_os_error()),\n        _ => Ok(()),\n    }\n}\n\nfn exec(cmd: &str) {\n    let mut proc = Command::new(\"sh\");\n    proc.args([\"-c\", cmd]);\n    proc.stdin(Stdio::null());\n    proc.stdout(Stdio::null());\n    // Safety: libc::daemon() is async-signal-safe\n    unsafe {\n        proc.pre_exec(|| match libc::daemon(1, 0) {\n            -1 => Err(io::Error::last_os_error()),\n            _ => Ok(()),\n        });\n    }\n    proc.spawn().unwrap().wait().unwrap();\n}\n\n#[derive(Clone, Copy)]\nstruct XkbMaskState {\n    depressed_mods: u32,\n    latched_mods: u32,\n    locked_mods: u32,\n    depressed_layout: u32,\n    latched_layout: u32,\n    locked_layout: u32,\n}\n\nimpl XkbMaskState {\n    fn new(xkb_state: &xkb::State) -> Self {\n        Self {\n            depressed_mods: xkb_state.serialize_mods(xkb::STATE_MODS_DEPRESSED),\n            latched_mods: xkb_state.serialize_mods(xkb::STATE_MODS_LATCHED),\n            locked_mods: xkb_state.serialize_mods(xkb::STATE_MODS_LOCKED),\n            depressed_layout: xkb_state.serialize_layout(xkb::STATE_LAYOUT_DEPRESSED),\n            latched_layout: xkb_state.serialize_layout(xkb::STATE_LAYOUT_LATCHED),\n            locked_layout: xkb_state.serialize_layout(xkb::STATE_LAYOUT_LOCKED),\n        }\n    }\n\n    fn with_locked_layout(&self, locked_layout: u32) -> Self {\n        Self {\n            locked_layout,\n            ..*self\n        }\n    }\n\n    fn apply(&self, xkb_state: &xkb::State) {\n        // Hack: this is just ref counting, no actual cloning. `update_mask` should probably just\n        // accept `&self` instead of `&mut self`.\n        let mut xkb_state = xkb_state.clone();\n        xkb_state.update_mask(\n            self.depressed_mods,\n            self.latched_mods,\n            self.locked_mods,\n            self.depressed_layout,\n            self.latched_layout,\n            self.locked_layout,\n        );\n    }\n}\n"
  },
  {
    "path": "src/menu.rs",
    "content": "use std::str::FromStr;\n\nuse anyhow::{Error, Result, bail};\nuse pangocairo::{cairo, pango};\nuse wayrs_utils::keyboard::xkb;\n\nuse crate::DEBUG_LAYOUT;\nuse crate::color::Color;\nuse crate::config::{self, Config};\nuse crate::key::{Key, ModifierState, SingleKey};\nuse crate::text::{self, ComputedText};\n\npub struct Menu {\n    pages: Vec<MenuPage>,\n    cur_page: usize,\n    separator: ComputedText,\n}\n\nstruct MenuPage {\n    item_height: f64,\n    columns: Vec<MenuColumn>,\n    parent: Option<usize>,\n}\n\nstruct MenuColumn {\n    key_col_width: f64,\n    val_col_width: f64,\n    items: Vec<MenuItem>,\n}\n\nstruct MenuItem {\n    action: Action,\n    key_comp: ComputedText,\n    val_comp: ComputedText,\n    key: Key,\n}\n\n#[derive(Clone)]\npub enum Action {\n    Quit,\n    Exec { cmd: String, keep_open: bool },\n    Submenu(usize),\n}\n\nimpl Menu {\n    pub fn new(config: &Config) -> Result<Self> {\n        let context = pango::Context::new();\n        let fontmap = pangocairo::FontMap::new();\n        context.set_font_map(Some(&fontmap));\n\n        let mut this = Self {\n            pages: Vec::new(),\n            cur_page: 0,\n            separator: ComputedText::new(&config.separator, &context, &config.font.0),\n        };\n\n        this.push_page(&context, &config.menu, config, None)?;\n\n        Ok(this)\n    }\n\n    fn push_page(\n        &mut self,\n        context: &pango::Context,\n        entries: &[config::Entry],\n        config: &Config,\n        parent: Option<usize>,\n    ) -> Result<usize> {\n        if entries.is_empty() {\n            bail!(\"Empty menu pages are not allowed\");\n        }\n\n        let cur_page = self.pages.len();\n\n        self.pages.push(MenuPage {\n            item_height: self.separator.height,\n            columns: Vec::new(),\n            parent,\n        });\n\n        for (entry_i, entry) in entries.iter().enumerate() {\n            let item = match entry {\n                config::Entry::Cmd {\n                    key,\n                    cmd,\n                    desc,\n                    keep_open,\n                } => MenuItem {\n                    action: Action::Exec {\n                        cmd: cmd.into(),\n                        keep_open: *keep_open,\n                    },\n                    key_comp: ComputedText::new(key.to_string(), context, &config.font.0),\n                    val_comp: ComputedText::new(desc, context, &config.font.0),\n                    key: key.clone(),\n                },\n                config::Entry::Recursive {\n                    key,\n                    submenu: entries,\n                    desc,\n                } => {\n                    let new_page = self.push_page(context, entries, config, Some(cur_page))?;\n                    MenuItem {\n                        action: Action::Submenu(new_page),\n                        key_comp: ComputedText::new(key.to_string(), context, &config.font.0),\n                        val_comp: ComputedText::new(format!(\"+{desc}\"), context, &config.font.0),\n                        key: key.clone(),\n                    }\n                }\n            };\n\n            let height = f64::max(item.key_comp.height, item.val_comp.height);\n            if height > self.pages[cur_page].item_height {\n                self.pages[cur_page].item_height = height;\n            }\n\n            let col_i = config\n                .rows_per_column\n                .map_or(0, |rows_per_column| entry_i / rows_per_column);\n\n            if col_i == self.pages[cur_page].columns.len() {\n                self.pages[cur_page].columns.push(MenuColumn {\n                    key_col_width: item.key_comp.width,\n                    val_col_width: item.val_comp.width,\n                    items: vec![item],\n                });\n            } else {\n                let col = &mut self.pages[cur_page].columns[col_i];\n                col.key_col_width = col.key_col_width.max(item.key_comp.width);\n                col.val_col_width = col.val_col_width.max(item.val_comp.width);\n                col.items.push(item);\n            }\n        }\n\n        Ok(cur_page)\n    }\n\n    pub fn width(&self, config: &Config) -> f64 {\n        let page = &self.pages[self.cur_page];\n        page.columns\n            .iter()\n            .map(|col| col.key_col_width + col.val_col_width + self.separator.width)\n            .sum::<f64>()\n            + (page.columns.len() - 1) as f64 * config.column_padding()\n            + (config.padding() + config.border_width) * 2.0\n    }\n\n    pub fn height(&self, config: &Config) -> f64 {\n        let page = &self.pages[self.cur_page];\n        page.columns\n            .iter()\n            .map(|col| page.item_height * col.items.len() as f64)\n            .max_by(f64::total_cmp)\n            .unwrap()\n            + (config.padding() + config.border_width) * 2.0\n    }\n\n    pub fn render(&self, config: &config::Config, cairo_ctx: &cairo::Context) -> Result<()> {\n        let mut dx = config.padding() + config.border_width;\n        let dy = config.padding() + config.border_width;\n        let page = &self.pages[self.cur_page];\n        for col in &page.columns {\n            self.render_column(config, cairo_ctx, dx, dy, page, col)?;\n            dx += col.key_col_width\n                + col.val_col_width\n                + self.separator.width\n                + config.column_padding();\n        }\n        Ok(())\n    }\n\n    fn render_column(\n        &self,\n        config: &Config,\n        cairo_ctx: &cairo::Context,\n        dx: f64,\n        dy: f64,\n        page: &MenuPage,\n        column: &MenuColumn,\n    ) -> Result<()> {\n        for (i, comp) in column.items.iter().enumerate() {\n            comp.key_comp.render(\n                cairo_ctx,\n                text::RenderOptions {\n                    x: dx + column.key_col_width - comp.key_comp.width,\n                    y: dy + page.item_height * (i as f64),\n                    fg_color: config.color,\n                    height: page.item_height,\n                },\n            )?;\n            self.separator.render(\n                cairo_ctx,\n                text::RenderOptions {\n                    x: dx + column.key_col_width,\n                    y: dy + page.item_height * (i as f64),\n                    fg_color: config.color,\n                    height: page.item_height,\n                },\n            )?;\n            comp.val_comp.render(\n                cairo_ctx,\n                text::RenderOptions {\n                    x: dx + column.key_col_width + self.separator.width,\n                    y: dy + page.item_height * (i as f64),\n                    fg_color: config.color,\n                    height: page.item_height,\n                },\n            )?;\n        }\n\n        if *DEBUG_LAYOUT {\n            Color::from_rgba(0, 0, 255, 255).apply(cairo_ctx);\n            cairo_ctx.rectangle(\n                dx,\n                dy,\n                column.key_col_width + column.val_col_width + self.separator.width,\n                column.items.len() as f64 * page.item_height,\n            );\n            cairo_ctx.set_line_width(1.0);\n            cairo_ctx.stroke().unwrap();\n        }\n\n        Ok(())\n    }\n\n    pub fn get_action(&self, modifiers: ModifierState, sym: xkb::Keysym) -> Option<Action> {\n        let page = &self.pages[self.cur_page];\n\n        let action = page.columns.iter().find_map(|col| {\n            col.items\n                .iter()\n                .find_map(|i| i.key.matches(sym, modifiers).then(|| i.action.clone()))\n        });\n        if action.is_some() {\n            return action;\n        }\n\n        match sym {\n            xkb::Keysym::Escape => {\n                return Some(Action::Quit);\n            }\n            xkb::Keysym::bracketleft | xkb::Keysym::g if modifiers.mod_ctrl => {\n                return Some(Action::Quit);\n            }\n            xkb::Keysym::BackSpace => {\n                if let Some(parent) = page.parent {\n                    return Some(Action::Submenu(parent));\n                }\n            }\n            _ => (),\n        }\n\n        None\n    }\n\n    pub fn set_page(&mut self, page: usize) {\n        self.cur_page = page;\n    }\n\n    pub fn navigate_to_key_sequence(&mut self, key_sequence: &str) -> Result<Option<Action>> {\n        let mut last_action = None;\n        for key_str in key_sequence.split_whitespace() {\n            if let Some((last_key_str, _action)) = &last_action {\n                bail!(\"Key '{last_key_str}' leads to a command, but more keys follow in sequence\");\n            }\n            let key = SingleKey::from_str(key_str).map_err(Error::msg)?;\n            match self.get_action(key.modifiers, key.keysym) {\n                Some(Action::Submenu(submenu_page)) => self.set_page(submenu_page),\n                Some(action) => last_action = Some((key_str, action)),\n                None => bail!(\"Key '{}' not found in current menu\", key_str),\n            }\n        }\n        Ok(last_action.map(|x| x.1))\n    }\n}\n"
  },
  {
    "path": "src/text.rs",
    "content": "use crate::{DEBUG_LAYOUT, color::Color};\nuse anyhow::Result;\nuse pango::FontDescription;\nuse pangocairo::{cairo, pango};\n\n#[derive(Clone, Debug, PartialEq)]\npub struct RenderOptions {\n    pub x: f64,\n    pub y: f64,\n    pub fg_color: Color,\n    pub height: f64,\n}\n\n#[derive(Clone, Debug)]\npub struct ComputedText {\n    pub layout: pango::Layout,\n    pub width: f64,\n    pub height: f64,\n}\n\nimpl ComputedText {\n    pub fn new(text: impl AsRef<str>, context: &pango::Context, font: &FontDescription) -> Self {\n        let layout = pango::Layout::new(context);\n        layout.set_font_description(Some(font));\n        layout.set_text(text.as_ref());\n\n        let (width, height) = layout.pixel_size();\n\n        ComputedText {\n            layout,\n            width: width as f64,\n            height: height as f64,\n        }\n    }\n\n    pub fn render(&self, context: &cairo::Context, options: RenderOptions) -> Result<()> {\n        pangocairo::functions::update_layout(context, &self.layout);\n\n        context.save()?;\n        context.translate(options.x, options.y + (options.height - self.height) * 0.5);\n\n        options.fg_color.apply(context);\n        pangocairo::functions::show_layout(context, &self.layout);\n\n        if *DEBUG_LAYOUT {\n            Color::from_rgba(255, 0, 0, 255).apply(context);\n            context.rectangle(0.0, 0.0, self.width, self.height);\n            context.set_line_width(1.0);\n            context.stroke().unwrap();\n        }\n\n        context.restore()?;\n\n        Ok(())\n    }\n}\n"
  }
]