commit a3a9149184a70a82f6147c19da4bb48ff7bf30a7 Author: Evandro Fonseca Junior <345073078+edevbr@users.noreply.github.com> Date: Mon Nov 2 00:51:25 2026 -0300 WaylandKeybinds: reliable Discord global keybinds on GNOME Wayland Vencord plugin for the Discord desktop app. Toggles fire on key press, push-to-talk infers releases GNOME drops (re-registration probe), and GNOME's trigger descriptions are matched correctly. Includes basis-path tests, a patch checker against the live Discord bundle, the design spec and the README assets. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ad22d44 --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +

+ WaylandKeybinds: Discord global mute, deafen and push-to-talk that keep working when GNOME drops the key release +

+ +

+ Home: git.evandro.dev.br/evandro, my self-hosted Gitea. GitHub only carries this copy for reach. +

+ +**WaylandKeybinds** is a [Vencord](https://vencord.dev) plugin for the Discord desktop app on Linux. Discord already hands your keybinds to GNOME through the `GlobalShortcuts` portal, but GNOME loses the key release whenever a modifier is let go first, and Discord's mute and deafen only act on the release. The plugin fixes this inside Discord's own **Keybinds** screen: whatever key you choose there becomes global, like Discord on Windows. + +

+ Timeline of one Ctrl+Shift+F10 hold with Ctrl+Shift let go first: GNOME sends a press and key repeats but no release; Discord alone never toggles and ignores the next press; with WaylandKeybinds the mute toggles on the press and silence after a re-registration means the key was released +

+ +Measured on GNOME 50 with Discord 1.0.168: every press toggled the mute exactly once, 11 to 14 ms after GNOME's signal, including a 6-second hold that GNOME repeated 57 times. + +## Why Discord's keybinds break on GNOME + +- GNOME's compositor looks up a shortcut's release using the modifiers still held at that moment. Let Ctrl or Shift go before the main key and the release never matches, so the portal never sends `Deactivated` ([`process_event`](https://gitlab.gnome.org/GNOME/mutter/-/blob/main/src/core/keybindings.c)). +- Mute, deafen and most other toggles fire on the key **release** only. +- Discord's native module ignores further presses until it sees a release, so after one lost release the next gesture disappears too. +- GNOME describes the trigger as `Press F10` while Discord expects `CTRL+SHIFT+F10`, so every working shortcut is flagged as different from the system one. + +## What the plugin does + +- Toggle actions (mute, deafen, streamer mode and the rest) fire on the **press**. +- One second after a press it re-registers the shortcut, which clears Discord's stuck state, then listens for 300 ms. While the keys are held, GNOME's key repeat answers within a few milliseconds; silence means they were released. That is how push-to-talk stops even when the release is lost. A real release still stops it at once. +- It reads GNOME's trigger format, so the Keybinds screen stops warning about a mismatch. +- It changes nothing unless Discord registers the keybind through the Wayland portal. It runs in the renderer only: no native code, no new dependency, no DOM clicks. + +## Install + +You need a [Vencord source checkout](https://docs.vencord.dev/installing/), because user plugins are compiled into your build. + +```sh +cd /path/to/Vencord +git clone https://github.com/edevbr/vencord-wayland-keybinds.git src/userplugins/waylandKeybinds.discordDesktop +pnpm build +pnpm inject +``` + +Restart Discord. The plugin is on by default; you can find it as **WaylandKeybinds** in Vencord's plugin list. + +> [!IMPORTANT] +> Keep the folder name `waylandKeybinds.discordDesktop`. The suffix limits the plugin to the Discord desktop app, the only place where Discord's native keybind module exists. + +## Use + +1. Open Discord **User Settings → Keybinds → Add a Keybind**. +2. Pick an action (Toggle Mute, Toggle Deafen, Push to Talk…) and press your combination. +3. GNOME asks once to allow the shortcut. Click **Add**. + +Change the keys whenever you want on the same screen; GNOME asks again for the new combination. + +> [!TIP] +> For push-to-talk, a single key without modifiers (Pause, F13 to F24) keeps both press and release reliable. + +On Wayland, Discord records only combinations the portal can represent: one main key plus optional modifiers. Mouse buttons cannot be global shortcuts there. + +## Compatibility + +| Component | Tested with | +| --- | --- | +| Discord | 1.0.168 (Electron 44) | +| Vencord | 1.15.15 | +| GNOME | 50.5 (mutter 18, xdg-desktop-portal-gnome 50) | +| KDE Plasma, Hyprland | Not tested. The portal path is the same, the release behavior may differ. | + +## Limits + +- Release detection relies on GNOME's key repeat (500 ms, then every 30 ms by default). With key repeat turned off, push-to-talk ends about 1.3 s after the press even while you hold it. +- When the release is lost, push-to-talk stops up to about 1.3 s after you let go. +- The live checks covered toggle mute; push-to-talk is covered by the state-machine tests. +- Soundboard hold stays off the portal on Linux. That is Discord's own choice. +- The patches target Discord's minified code and can break with Discord updates. Run `check-patches.mjs` before you rebuild. + +## Development + +From the root of your Vencord checkout: + +```sh +# one test case per independent path of every function in logic.ts +pnpm exec esbuild src/userplugins/waylandKeybinds.discordDesktop/logic.test.ts \ + --bundle --platform=node --format=esm --outfile=/tmp/wk-test.mjs +node --test /tmp/wk-test.mjs + +# apply the patches to the Discord build that discord.com serves right now +node src/userplugins/waylandKeybinds.discordDesktop/check-patches.mjs +``` + +The design notes, measurements and acceptance criteria (in Portuguese) are in [`specs/2026-11-01-wayland-keybinds.md`](specs/2026-11-01-wayland-keybinds.md). + +--- + +

+ Made by Evandro · git.evandro.dev.br/evandro · evandro.dev.br +

diff --git a/assets/readme/hero.svg b/assets/readme/hero.svg new file mode 100644 index 0000000..58ad1be --- /dev/null +++ b/assets/readme/hero.svg @@ -0,0 +1,41 @@ + + WaylandKeybinds + Vencord plugin that keeps Discord's global mute, deafen and push-to-talk shortcuts working on GNOME Wayland. Keycaps Ctrl + Shift + F10; a GNOME lane shows a press, key repeats and a release that never arrives; a Discord lane shows the mute toggled in 11 ms. + + + + VENCORD PLUGIN · GNOME WAYLAND + WaylandKeybinds + Global mute, deafen and push-to-talk + that keep working when GNOME + drops the key release. + renderer-only · no new dependencies · GPL-3.0 + + + + + + Ctrl + + + Shift + + + F10 + + + + GNOME + + + + + release never arrives + + + + + + DISCORD + PLUGIN + + mute toggled · 11 ms + + diff --git a/assets/readme/proof.svg b/assets/readme/proof.svg new file mode 100644 index 0000000..64362d3 --- /dev/null +++ b/assets/readme/proof.svg @@ -0,0 +1,44 @@ + + What one key press looks like on GNOME + Timeline of one Ctrl+Shift+F10 hold where Ctrl+Shift are let go first. GNOME sends a press, then key repeats every 30 ms after 500 ms, and never a release. Discord alone acts on the release, so the toggle never fires and its next press is ignored. With WaylandKeybinds the mute toggles on the press; every 300 ms the plugin re-registers the shortcut and listens for repeats, and silence means the key was released. + + + What one key press looks like on GNOME + Ctrl+Shift+F10 held · Ctrl+Shift let go first · GNOME 50 key repeat: 500 ms, then every 30 ms + + + keys let go + + + GNOME sendspress, repeats + + + + + no release + + + + + + Discord aloneacts on release + + toggle waits for the release: never fires + and the next press is ignored + + + + + + + WaylandKeybindsacts on press + + toggled + + re-arms every 300 ms + + silence = released + + + + 00.5 s1 s1.8 s2.2 s + diff --git a/check-patches.mjs b/check-patches.mjs new file mode 100644 index 0000000..d1123d0 --- /dev/null +++ b/check-patches.mjs @@ -0,0 +1,72 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2026 Evandro + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +// Applies this plugin's patches to a downloaded Discord bundle the way Vencord does: +// unique find, one match per replacement, patched module still parses. +// Usage: node check-patches.mjs [dir with discord.com/assets/*.js, optional lazy/ subdir] +// Without a dir it downloads the entry bundles that discord.com/app serves right now. +import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { PATCHES } from "./patches.ts"; + +// espree is ESLint's acorn-based parser, already installed with the repo +const { parse: espreeParse } = createRequire(createRequire(import.meta.url).resolve("eslint/package.json"))("espree"); +const parse = (code, opts) => espreeParse(code, { ...opts, ecmaVersion: "latest" }); +const dir = process.argv[2] ?? await downloadEntryBundles(); + +async function downloadEntryBundles() { + const out = mkdtempSync(join(tmpdir(), "discord-web-")); + const html = await (await fetch("https://discord.com/app")).text(); + const scripts = [...html.matchAll(/src="(\/assets\/[^"]+\.js)"/g)].map(m => m[1]); + for (const src of scripts) + writeFileSync(join(out, src.split("/").pop()), await (await fetch("https://discord.com" + src)).text()); + console.log(`baixados ${scripts.length} bundles de discord.com/app em ${out}`); + return out; +} +const SELF = 'Vencord.Plugins.plugins["WaylandKeybinds"]'; +const canon = re => new RegExp(re.source.replaceAll(/(\\*)\\i/g, (m, esc) => esc.length % 2 === 0 ? esc + "(?:[A-Za-z_$][\\w$]*)" : m.slice(1)), re.flags); + +const lazy = join(dir, "lazy"); +const files = readdirSync(dir).filter(f => f.endsWith(".js")).map(f => join(dir, f)) + .concat(existsSync(lazy) ? readdirSync(lazy).filter(f => f.endsWith(".js")).map(f => join(lazy, f)) : []); +let failed = false; +const fail = msg => { failed = true; console.log("FALHOU " + msg); }; +const ok = msg => console.log("ok " + msg); + +for (const patch of PATCHES) { + const hits = files.filter(f => readFileSync(f, "utf8").includes(patch.find)); + if (hits.length !== 1) { fail(`find "${patch.find}" em ${hits.length} arquivos`); continue; } + const src = readFileSync(hits[0], "utf8"); + const pos = src.indexOf(patch.find); + let module = null; + // rspack modules are methods of one big object: `123(e,t,n){...}` + const walk = node => { + if (!node || typeof node.type !== "string" || node.end < pos || node.start > pos) return; + if (node.type === "Property" && node.value?.type === "FunctionExpression" && /^\d+$/.test(String(node.key.value ?? node.key.name))) module = node; + for (const v of Object.values(node)) Array.isArray(v) ? v.forEach(walk) : walk(v); + }; + walk(parse(src, { ecmaVersion: "latest", sourceType: "script" })); + if (!module) { fail(`módulo de "${patch.find}" não encontrado`); continue; } + ok(`find "${patch.find}" único → módulo ${module.key.value ?? module.key.name} (${hits[0].split("/").pop()})`); + if (src.indexOf(patch.find, pos + 1) !== -1 && src.indexOf(patch.find, pos + 1) < module.end) ok("find repete dentro do mesmo módulo (permitido)"); + + let code = "(function" + src.slice(module.value.start, module.value.end) + ")"; + for (const { match, replace } of [patch.replacement].flat()) { + const re = canon(match); + const count = [...code.matchAll(new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g"))].length; + if (count !== 1) { fail(`match ${match} casou ${count} vezes`); continue; } + const before = code; + code = code.replace(re, replace.replaceAll("$self", SELF)); + const at = [...before].findIndex((c, i) => c !== code[i]); + ok(`match ${match} casou 1 vez\n → ${code.slice(Math.max(0, at - 20), at + 150)}`); + } + try { parse(code, { ecmaVersion: "latest" }); ok("módulo corrigido continua JavaScript válido"); } + catch (e) { fail("módulo corrigido não compila: " + e.message); } +} +process.exit(failed ? 1 : 0); diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..76747da --- /dev/null +++ b/index.ts @@ -0,0 +1,83 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2026 Evandro + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { IS_LINUX } from "@utils/constants"; +import { Logger } from "@utils/Logger"; +import definePlugin from "@utils/types"; +import { findStoreLazy } from "@webpack"; + +import { adjustOptions, Callback, createDispatcher, Dispatcher, fixPortalState, KeyEventOptions, planRegistration, PortalState, Scheduler } from "./logic"; +import { PATCHES } from "./patches"; + +type Shortcut = [number, number, ...unknown[]][]; + +// Discord's own native keybind bridge (the object the KeybindsStore registers through) +interface Bridge { + inputEventRegister(id: number, shortcut: Shortcut, callback: Callback, options: KeyEventOptions): void; + inputEventUnregister(id: number): void; +} + +const dispatchers = new Map(); +const scheduler: Scheduler = { + now: () => performance.now(), + setTimeout: (fn, ms) => setTimeout(fn, ms), + clearTimeout: handle => clearTimeout(handle as ReturnType) +}; + +const logger = new Logger("WaylandKeybinds"); +const KeybindsStore = findStoreLazy("KeybindsStore"); + +function discordUtils() { + return DiscordNative.nativeModules.requireModule("discord_utils"); +} + +function portalTrigger(shortcut: Shortcut): string { + return discordUtils().getWaylandPortalTrigger?.(shortcut.map(([type, code]) => [type, code])) ?? ""; +} + +export default definePlugin({ + name: "WaylandKeybinds", + description: "Makes Discord's global keybinds reliable on GNOME Wayland: toggles (mute, deafen) fire on key press and push-to-talk recovers from key releases GNOME drops", + authors: [{ name: "Evandro", id: 281463271758888960n }], + // only changes behaviour when Discord registers keybinds through the Wayland GlobalShortcuts portal + enabledByDefault: true, + patches: PATCHES, + + wrapRegistration(bridge: Bridge, id: number, shortcut: Shortcut, callback: Callback, options: KeyEventOptions): [Callback, KeyEventOptions] { + try { + const portalActive = IS_LINUX && discordUtils().isWaylandGlobalShortcutsAvailable?.() === true; + const mode = planRegistration(options, portalActive, portalActive && portalTrigger(shortcut) !== ""); + const adjusted = adjustOptions(options, mode); + dispatchers.get(id)?.cancel(); + const dispatcher = createDispatcher(callback, mode, () => { + bridge.inputEventUnregister(id); + bridge.inputEventRegister(id, shortcut, dispatcher.dispatch, adjusted); + }, scheduler); + dispatchers.set(id, dispatcher); + return [dispatcher.dispatch, adjusted]; + } catch (e) { + logger.error("Failed to adapt keybind registration", e); + return [callback, options]; + } + }, + + unregister(bridge: Bridge, id: number) { + // stop probing first, or the next re-registration would bring a deleted keybind back + dispatchers.get(id)?.cancel(); + dispatchers.delete(id); + bridge.inputEventUnregister(id); + }, + + fixPortalState(state: S): S { + try { + const shortcut: Shortcut | undefined = KeybindsStore.getUserAgnosticState()?.[state.eventId]?.shortcut; + return fixPortalState(state, shortcut?.length ? portalTrigger(shortcut) : undefined); + } catch (e) { + logger.error("Failed to check portal shortcut state", e); + return state; + } + } +}); diff --git a/logic.test.ts b/logic.test.ts new file mode 100644 index 0000000..4770d66 --- /dev/null +++ b/logic.test.ts @@ -0,0 +1,243 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2026 Evandro + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +// Caminhos-base (McCabe): um caso por caminho independente de cada função de logic.ts. +import assert from "node:assert/strict"; +import { describe, test } from "node:test"; + +import { adjustOptions, createDispatcher, ECHO_MS, FIRST_PROBE_MS, fixPortalState, normalizeTrigger, planRegistration, PROBE_WINDOW_MS } from "./logic"; + +function recorder() { + const calls: boolean[] = []; + return { calls, callback: (isDown: boolean) => { calls.push(isDown); } }; +} + +describe("planRegistration (V(G)=7)", () => { + test("P1 portal ativo, representável, segurar → hold", () => { + assert.equal(planRegistration({ keydown: true, keyup: true }, true, true), "hold"); + }); + test("P2 portal inativo → passthrough", () => { + assert.equal(planRegistration({ keydown: true, keyup: true }, false, true), "passthrough"); + }); + test("P3 combinação não representável → passthrough", () => { + assert.equal(planRegistration({ keydown: true, keyup: true }, true, false), "passthrough"); + }); + test("P4 ação com portal:false (SOUNDBOARD_HOLD no Linux) → passthrough", () => { + assert.equal(planRegistration({ keydown: true, keyup: true, portal: false }, true, true), "passthrough"); + }); + test("P5 só soltar (TOGGLE_MUTE) → pressAsRelease", () => { + assert.equal(planRegistration({ keydown: false, keyup: true }, true, true), "pressAsRelease"); + }); + test("P6 só pressionar (SAVE_CLIP) → passthrough", () => { + assert.equal(planRegistration({ keydown: true, keyup: false }, true, true), "passthrough"); + }); + test("P7 nenhum evento → passthrough", () => { + assert.equal(planRegistration({}, true, true), "passthrough"); + }); +}); + +describe("adjustOptions (V(G)=2)", () => { + test("P1 pressAsRelease → pede pressionar e soltar ao nativo e preserva o resto", () => { + const options = { focused: true, blurred: true, keydown: false, keyup: true, shortcutId: "toggle-mute" }; + assert.deepEqual(adjustOptions(options, "pressAsRelease"), + { focused: true, blurred: true, keydown: true, keyup: true, shortcutId: "toggle-mute" }); + assert.equal(options.keydown, false, "não muta o objeto original"); + }); + test("P2 outros modos → mesmo objeto", () => { + const options = { keydown: true, keyup: true }; + assert.equal(adjustOptions(options, "hold"), options); + assert.equal(adjustOptions(options, "passthrough"), options); + }); +}); + +// Relógio falso: timers só disparam quando o teste avança o tempo. +function fakeScheduler() { + let now = 0, seq = 0; + const timers = new Map void; }>(); + return { + now: () => now, + setTimeout: (fn: () => void, ms: number) => { timers.set(++seq, { at: now + ms, fn }); return seq; }, + clearTimeout: (id: unknown) => { timers.delete(id as number); }, + pending: () => timers.size, + advance(ms: number) { + const target = now + ms; + for (;;) { + const next = [...timers.entries()].filter(([, t]) => t.at <= target).sort((a, b) => a[1].at - b[1].at)[0]; + if (!next) break; + timers.delete(next[0]); + now = next[1].at; + next[1].fn(); + } + now = target; + } + }; +} + +function rig(mode: "pressAsRelease" | "hold") { + const clock = fakeScheduler(); + const calls: boolean[] = []; + let rearms = 0; + const { dispatch, cancel } = createDispatcher(d => { calls.push(d); }, mode, () => { rearms++; }, clock); + return { clock, calls, dispatch, cancel, rearms: () => rearms }; +} + +describe("createDispatcher (V(G)=2) e o despachante (V(G)=6)", () => { + test("P1 passthrough → devolve o próprio callback e cancel inofensivo", () => { + const { callback } = recorder(); + const d = createDispatcher(callback, "passthrough", () => { throw new Error("não deve re-registrar"); }, fakeScheduler()); + assert.equal(d.dispatch, callback); + d.cancel(); + }); + + test("D1 ocioso + soltar avulso → ignorado, nada agendado", () => { + const r = rig("hold"); + r.dispatch(false); + assert.deepEqual(r.calls, []); + assert.equal(r.clock.pending(), 0); + }); + + test("D2 ocioso + pressionar → alternar dispara como soltura (false) e agenda a 1ª sondagem", () => { + const r = rig("pressAsRelease"); + r.dispatch(true); + assert.deepEqual(r.calls, [false]); + r.clock.advance(FIRST_PROBE_MS - 1); + assert.equal(r.rearms(), 0); + r.clock.advance(1); + assert.equal(r.rearms(), 1); + }); + + test("D2 ocioso + pressionar → segurar começa (true)", () => { + const r = rig("hold"); + r.dispatch(true); + assert.deepEqual(r.calls, [true]); + }); + + test("D3 segurado + repetição logo após o re-registro → continua segurado e sonda de novo", () => { + const r = rig("hold"); + r.dispatch(true); + r.clock.advance(FIRST_PROBE_MS); + r.clock.advance(20); + r.dispatch(true); + r.clock.advance(PROBE_WINDOW_MS - 20); + assert.deepEqual(r.calls, [true]); + assert.equal(r.rearms(), 2); + }); + + test("veredito sem repetição → segurar termina (false) e para de sondar", () => { + const r = rig("hold"); + r.dispatch(true); + r.clock.advance(FIRST_PROBE_MS + PROBE_WINDOW_MS); + assert.deepEqual(r.calls, [true, false]); + assert.equal(r.clock.pending(), 0); + assert.equal(r.rearms(), 1); + }); + + test("veredito sem repetição → alternar não chama nada a mais", () => { + const r = rig("pressAsRelease"); + r.dispatch(true); + r.clock.advance(FIRST_PROBE_MS + PROBE_WINDOW_MS); + assert.deepEqual(r.calls, [false]); + assert.equal(r.clock.pending(), 0); + }); + + test("D4 segurado + pressionar fora do eco (soltura perdida, novo gesto) → alternar dispara de novo", () => { + const r = rig("pressAsRelease"); + r.dispatch(true); + r.clock.advance(FIRST_PROBE_MS + ECHO_MS); + r.dispatch(true); + assert.deepEqual(r.calls, [false, false]); + }); + + test("D5 segurado + soltar dentro do eco do re-registro → ignorado (soltura sintética)", () => { + const r = rig("hold"); + r.dispatch(true); + r.clock.advance(FIRST_PROBE_MS + 1); + r.dispatch(false); + assert.deepEqual(r.calls, [true]); + }); + + test("D6 segurado + soltar real → segurar termina na hora e cancela a sondagem", () => { + const r = rig("hold"); + r.dispatch(true); + r.clock.advance(400); + r.dispatch(false); + assert.deepEqual(r.calls, [true, false]); + assert.equal(r.clock.pending(), 0); + r.clock.advance(5000); + assert.equal(r.rearms(), 0); + }); + + test("D6 alternar + soltar real → sem chamada extra, próximo toque dispara (toque duplo)", () => { + const r = rig("pressAsRelease"); + r.dispatch(true); + r.clock.advance(80); + r.dispatch(false); + r.clock.advance(200); + r.dispatch(true); + assert.deepEqual(r.calls, [false, false]); + }); + + test("cancel → para a sondagem e nada mais é re-registrado", () => { + const r = rig("hold"); + r.dispatch(true); + r.cancel(); + r.clock.advance(5000); + assert.equal(r.rearms(), 0); + assert.equal(r.clock.pending(), 0); + }); + + test("cenário medido: segurar 1,8 s soltando modificadores antes, depois novo toque", () => { + const r = rig("pressAsRelease"); + r.dispatch(true); // Activated + r.clock.advance(FIRST_PROBE_MS); r.dispatch(true); // repetição logo após o 1º re-registro + r.clock.advance(PROBE_WINDOW_MS); r.dispatch(true); // ainda segurado no 2º re-registro + r.clock.advance(PROBE_WINDOW_MS); // soltou (sem Deactivated): veredito encerra + r.clock.advance(1500); + r.dispatch(true); // gesto seguinte não é engolido + assert.deepEqual(r.calls, [false, false]); + assert.equal(r.clock.pending(), 1); + }); +}); + +describe("normalizeTrigger (V(G)=2 + apelidos)", () => { + test("P1 formato do portal (sem <>) → MODS|tecla", () => { + assert.equal(normalizeTrigger("CTRL+SHIFT+F12"), "CTRL+SHIFT|f12"); + }); + test("P2 descrição do GNOME (com <>) → mesma forma canônica", () => { + assert.equal(normalizeTrigger("Press F12"), "CTRL+SHIFT|f12"); + }); + test("tecla sem modificador, descrição localizada do GNOME", () => { + assert.equal(normalizeTrigger("Pressione F12"), "|f12"); + assert.equal(normalizeTrigger("m"), "|m"); + }); + test("apelidos de modificador e modificador desconhecido", () => { + assert.equal(normalizeTrigger("Press m"), "ALT+CTRL+LOGO|m"); + assert.equal(normalizeTrigger("NUM+a"), "NUM|a"); + }); +}); + +describe("fixPortalState (V(G)=5)", () => { + const gnome = { eventId: 7, bound: true, triggerDescription: "Press F12", matchesTrigger: false }; + test("P1 vinculado, divergente só no formato → matchesTrigger true (cópia)", () => { + const fixed = fixPortalState(gnome, "CTRL+SHIFT+F12"); + assert.deepEqual(fixed, { ...gnome, matchesTrigger: true }); + assert.equal(gnome.matchesTrigger, false, "não muta o estado original"); + }); + test("P2 não vinculado → igual", () => { + const s = { ...gnome, bound: false }; + assert.equal(fixPortalState(s, "CTRL+SHIFT+F12"), s); + }); + test("P3 já casa → igual", () => { + const s = { ...gnome, matchesTrigger: true }; + assert.equal(fixPortalState(s, "CTRL+SHIFT+F12"), s); + }); + test("P4 sem gatilho esperado → igual", () => { + assert.equal(fixPortalState(gnome, undefined), gnome); + }); + test("P5 atalho realmente diferente no sistema → igual", () => { + assert.equal(fixPortalState(gnome, "CTRL+ALT+F12"), gnome); + }); +}); diff --git a/logic.ts b/logic.ts new file mode 100644 index 0000000..1810f3d --- /dev/null +++ b/logic.ts @@ -0,0 +1,126 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2026 Evandro + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +export interface KeyEventOptions { + keydown?: boolean; + keyup?: boolean; + portal?: boolean; +} + +export interface PortalState { + bound: boolean; + matchesTrigger: boolean; + triggerDescription: string; +} + +export type DispatchMode = "passthrough" | "pressAsRelease" | "hold"; + +export type Callback = (isDown: boolean) => void; + +export interface Scheduler { + now(): number; + setTimeout(fn: () => void, ms: number): unknown; + clearTimeout(handle: unknown): void; +} + +export interface Dispatcher { + dispatch: Callback; + cancel(): void; +} + +// GNOME repeats a held shortcut after 500 ms and then every 30 ms (org.gnome.desktop.peripherals.keyboard) +export const FIRST_PROBE_MS = 1000; +export const PROBE_WINDOW_MS = 300; +export const ECHO_MS = 150; + +const MODIFIERS: Record = { + ctrl: "CTRL", control: "CTRL", primary: "CTRL", + shift: "SHIFT", + alt: "ALT", mod1: "ALT", + super: "LOGO", logo: "LOGO", meta: "LOGO", mod4: "LOGO" +}; + +export function planRegistration(options: KeyEventOptions, portalActive: boolean, representable: boolean): DispatchMode { + if (!portalActive || !representable || options.portal === false) return "passthrough"; + if (options.keyup && options.keydown) return "hold"; + // GNOME only delivers the release if the main key is let go before the modifiers, so act on the press + if (options.keyup) return "pressAsRelease"; + return "passthrough"; +} + +export function adjustOptions(options: T, mode: DispatchMode): T { + return mode === "pressAsRelease" ? { ...options, keydown: true, keyup: true } : options; +} + +export function createDispatcher(callback: Callback, mode: DispatchMode, rearm: () => void, scheduler: Scheduler): Dispatcher { + if (mode === "passthrough") return { dispatch: callback, cancel() { } }; + + let held = false; + let repeated = false; + let rearmedAt = -Infinity; + let timer: unknown; + + const end = () => { + held = false; + if (mode === "hold") callback(false); + }; + // Discord's native module ignores presses until it sees a release, and GNOME drops the release when a + // modifier is let go first. Re-registering resets that state; a held combo then repeats within a few ms. + const probe = () => { + repeated = false; + rearm(); + rearmedAt = scheduler.now(); + timer = scheduler.setTimeout(() => repeated ? probe() : end(), PROBE_WINDOW_MS); + }; + const start = () => { + held = true; + callback(mode === "hold"); + timer = scheduler.setTimeout(probe, FIRST_PROBE_MS); + }; + + const dispatch: Callback = isDown => { + const echo = scheduler.now() - rearmedAt < ECHO_MS; + if (!held) { + if (isDown) start(); + } else if (isDown) { + if (echo) repeated = true; + else { scheduler.clearTimeout(timer); start(); } + } else if (!echo) { + scheduler.clearTimeout(timer); + end(); + } + }; + + return { + dispatch, + cancel() { + scheduler.clearTimeout(timer); + held = false; + } + }; +} + +export function normalizeTrigger(trigger: string): string { + const mods = Array.from(trigger.matchAll(/<([^>]+)>/g), m => m[1]); + let rest = trigger.slice(trigger.lastIndexOf(">") + 1); + if (mods.length === 0) { + const parts = rest.split("+"); + rest = parts.pop()!; + mods.push(...parts); + } + + const key = rest.trim().split(/\s+/).pop()!; + const canonical = mods.map(m => MODIFIERS[m.trim().toLowerCase()] ?? m.trim().toUpperCase()); + return [...new Set(canonical)].sort().join("+") + "|" + key.toLowerCase(); +} + +export function fixPortalState(state: S, expected: string | undefined): S { + if (!state.bound || state.matchesTrigger || !expected) return state; + // GNOME describes the trigger as "Press F12", which never equals "CTRL+SHIFT+F12" literally + return normalizeTrigger(expected) === normalizeTrigger(state.triggerDescription) + ? { ...state, matchesTrigger: true } + : state; +} diff --git a/patches.ts b/patches.ts new file mode 100644 index 0000000..851fe7e --- /dev/null +++ b/patches.ts @@ -0,0 +1,26 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2026 Evandro + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import type { Patch } from "@utils/types"; + +export const PATCHES: Omit[] = [{ + // KeybindsStore: native keybind registration and Wayland portal state + find: "Skipping registration.", + replacement: [ + { + match: /(\i\.\i)\.inputEventRegister\((\i),(\i),(\i),(\i)\)/, + replace: "$1.inputEventRegister($2,$3,...$self.wrapRegistration($1,$2,$3,$4,$5))" + }, + { + match: /(\i\.\i)\.inputEventUnregister\(/, + replace: "$self.unregister($1," + }, + { + match: /(setWaylandPortalShortcutsCallback\(\i=>\{let \i=\{\};for\(let (\i) of \i\)\i\[String\(\2\.eventId\)\]=)\2/, + replace: "$1$self.fixPortalState($2)" + } + ] +}]; diff --git a/specs/2026-11-01-wayland-keybinds.md b/specs/2026-11-01-wayland-keybinds.md new file mode 100644 index 0000000..899e354 --- /dev/null +++ b/specs/2026-11-01-wayland-keybinds.md @@ -0,0 +1,108 @@ +# WaylandKeybinds: atalhos globais confiáveis do Discord no GNOME (Wayland) +**Autor:** Evandro · **Data:** 2026-11-01 · **Porte:** médio · **Status:** concluída + +## 1. Objetivo +Fazer os atalhos globais do Discord (alternar mudo/ensurdecer, push-to-talk) funcionarem de forma confiável no GNOME Wayland para quem usa Vencord. O Discord 1.0.168 já registra atalhos pelo portal `GlobalShortcuts`, mas no GNOME o evento de soltar falha e o estado do portal é lido errado. + +## 2. Escopo +- Dentro: plugin de renderer `src/plugins/waylandKeybinds.discordDesktop/` (sem `native.ts`, sem dependência nova, sem DOM), com lógica pura testável e dois patches no módulo do `KeybindsStore`. +- Fora: push-to-talk perfeito com modificadores (o mutter não entrega a soltura; ver §6), botões de mouse, `SOUNDBOARD_HOLD` (o Discord desliga o portal para ele no Linux), atalhos do VoiceGuard, Vesktop, PR upstream. + +## 3. Critérios de aceite +- CA1: Com portal ativo e atalho representável, uma ação só-soltar (`TOGGLE_MUTE`, `TOGGLE_DEAFEN` etc.) dispara no pressionar, também quando o GNOME perde a soltura, e o gesto seguinte não é engolido. → `wk:test` + teste ao vivo T8. +- CA2: Ação de segurar (push-to-talk): termina na soltura real ou, se ela se perder, em até ~1,3 s depois de a tecla ser solta (sem repetição após re-registro); continua enquanto a repetição chegar. → `wk:test` (relógio falso). +- CA9: Quando o Discord desregistra o atalho (apagado/alterado), a sondagem para e nada é re-registrado. → `wk:test` (`cancel`) + patch do `inputEventUnregister` no CA5. +- CA3: Sem portal (inativo, combinação não representável ou `portal:false`) o registro passa intacto: mesmo callback, mesmas opções. → `pnpm wk:test`. +- CA4: A descrição do GNOME `Press F12` é reconhecida como igual a `CTRL+SHIFT+F12`; o estado passa a `matchesTrigger: true`. Estados diferentes, não vinculados ou sem gatilho esperado ficam como estão. → `pnpm wk:test`. +- CA5: Os patches aplicam no Discord atual: cada `find` ocorre uma vez, cada `match` casa uma vez e o bundle corrigido continua válido. → `node check-patches.mjs` contra `discord.com/app` baixado. +- CA6: `pnpm build --dev`, `tsc --noEmit` e `eslint` do plugin sem erros. → comandos. +- CA7: Toda função de `logic.ts` com CC ≤ 10 e todos os caminhos-base cobertos. → `uvx lizard` + tabela na seção 8. +- CA8: No Discord real, alternar mudo por atalho global funciona soltando os modificadores antes da tecla. → teste ao vivo com o usuário (exige reiniciar o Discord). + +## 4. Contexto verificado +- `modules/discord_utils-1/discord_utils/discord_utils.node`: `WaylandGlobalShortcuts` (sd-bus), log `Wayland GlobalShortcuts initialized; appId='discord'` em toda inicialização (journal); filtra eventos por `keydown`/`keyup` (medido: atalho só-soltar não entrega o pressionar). +- Renderer `web.f86c748842ee176f.js`, módulo do `KeybindsStore`: `inputEventRegister(e,t,n,i)` com `{focused:!0,blurred:!0,keydown:!1,keyup:!1,...keyEvents,description,shortcutId}`; `setWaylandPortalShortcutsCallback(e=>{...t[String(n.eventId)]=n;...})`. +- Tabela de ações: `TOGGLE_MUTE`/`TOGGLE_DEAFEN` = `keyup:!0,keydown:!1`; `PUSH_TO_TALK` = `keyup:!0,keydown:!0`; `SOUNDBOARD_HOLD` = `portal:isWindows()`. +- Tela de atalhos (`82738a067c897563.js`, componente `lB`): `bound && matchesTrigger===false` mostra aviso com `triggerDescription`; regravar a mesma combinação chama `reofferWaylandPortalShortcut` (reabre o diálogo do GNOME). +- mutter `src/core/keybindings.c` `process_event`: o soltar procura o atalho pelo código da tecla + modificadores ainda pressionados; soltar um modificador antes faz o soltar nunca casar. +- Portal do GNOME 50 devolve `triggerDescription` = `Press F12`; o nativo compara com `CTRL+SHIFT+F12` (de `getWaylandPortalTrigger`) e marca `matchesTrigger:false` sempre. +- Padrão de plugin: `src/plugins/noDeepLinks.web/index.ts` (patch com `$self`). + +## 5. Desenho +- Corrigir no renderer, onde o Discord monta o registro: troca o modo de entrega por ação. Alternativas descartadas: D-Bus próprio (`dbus-next`/Rust: rejeitado nos PRs #326/#3505 e duplica o que o nativo já faz) e clique em DOM (regra do CONTRIBUTING). +- `logic.ts` (puro, sem imports do Vencord): + - `type DispatchMode = "passthrough" | "pressAsRelease" | "hold"` + - `planRegistration(options: KeyEventOptions, portalActive: boolean, representable: boolean): DispatchMode` + - `adjustOptions(options: T, mode: DispatchMode): T` (pede pressionar e soltar ao nativo) + - `createDispatcher(callback, mode, rearm: () => void, scheduler: Scheduler): { dispatch, cancel }`: no pressionar age e agenda sondagem em `FIRST_PROBE_MS` (1000); sondar = `rearm()` (re-registro, zera o estado preso do nativo) + janela `PROBE_WINDOW_MS` (300); repetição em até `ECHO_MS` (150) após o re-registro = ainda segurado; sem repetição = solto; soltura dentro de `ECHO_MS` é eco sintético do re-registro e é ignorada. + - `normalizeTrigger(trigger: string): string` → forma canônica `MODS|tecla` + - `fixPortalState(state: S, expected: string | undefined): S` +- `index.ts`: três patches no `find: "Skipping registration."`: `$self.wrapRegistration(bridge, id, shortcut, callback, options)` (devolve `[callback, options]`; o `rearm` usa a própria ponte do Discord), `$self.unregister(bridge, id)` (cancela a sondagem antes de desregistrar) e `$self.fixPortalState(state)`. Entradas vêm do nativo (`isWaylandGlobalShortcutsAvailable`, `getWaylandPortalTrigger`) e da store (`getUserAgnosticState()[id].shortcut`), tudo em `try/catch` com fallback para o comportamento original. +- `patches.ts`: dados dos patches, usados pelo `index.ts` e pelo `check-patches.mjs`. +- Arquivos (todos novos): `logic.ts`, `logic.test.ts`, `patches.ts`, `index.ts`, `check-patches.mjs`, esta spec. + +## 6. Restrições, riscos, suposições +- A inferência de soltura depende da repetição de tecla do GNOME (medido: atraso 500 ms, intervalo 30 ms). Com repetição desligada, o push-to-talk terminaria ~1,3 s após o pressionar mesmo segurado; com atraso > 1000 ms, a primeira sondagem erra. Reverter: desligar o plugin. +- Cada sondagem é um re-registro (D-Bus `BindShortcuts`); só ocorre enquanto a tecla está pressionada. Medido: não reabre o diálogo do GNOME. +- Patches dependem do bundle minificado; quebram em atualizações do Discord (o CA5 detecta). +- Explicado na v2: os "pressionar" extras e os gestos sumidos vinham da repetição automática do GNOME e do estado preso do nativo. + +## 7. Microtasks +### T1 · escrever testes de caminhos-base de `logic.ts` · N0 +- Serve: CA1, CA2, CA3, CA4, CA7 · Depende de: nenhuma +- Arquivos: criar `logic.test.ts` +- Pronto quando: um caso por caminho-base de cada função; roda e falha (lógica ausente) +- Verificar: `pnpm wk:test` → falha de import/asserção +- [x] feito +### T2 · implementar `logic.ts` · N0 +- Serve: CA1–CA4 · Depende de: T1 +- Pronto quando: todos os testes passam +- Verificar: `pnpm wk:test` → 0 falhas +- [x] feito +### T3 · medir CC e conferir caminhos · N0 +- Serve: CA7 · Depende de: T2 +- Verificar: `uvx lizard logic.ts` → CC ≤ 10 em todas +- [x] feito +### CP1 · após T1–T3 · N0 +- [x] feito +### T4 · `patches.ts` + `index.ts` · N0 +- Serve: CA1, CA4, CA6 · Depende de: T2 +- Padrão: `src/plugins/noDeepLinks.web/index.ts` +- Verificar: `pnpm build --dev` → sucesso +- [x] feito +### T5 · `check-patches.mjs` contra o bundle real · N0 +- Serve: CA5 · Depende de: T4 +- Verificar: `node check-patches.mjs` → find único, match único, bundle válido +- [x] feito +### T6 · tsc + eslint · N0 +- Serve: CA6 · Depende de: T4 +- [x] feito +### CP2 · após T4–T6 · N0 +- [x] feito +### T7 · teste real: nativo do Discord + GNOME + `logic.ts` · N0 +- Serve: CA1, S1 · Depende de: T2 · precisa de um toque do usuário +- [x] feito +### T8 · teste ao vivo no Discord · N0 +- Serve: CA8 · Depende de: CP2 · precisa do ok do usuário para reiniciar o Discord +- [x] feito + +## 8. Resultado por critério +| CA | Resultado | Evidência | +|---|---|---| +| CA1 | ok | 31/31 testes; ao vivo: 11 pressionamentos → 11 alternâncias de mudo (11–16 ms), inclusive segurar de 6 s soltando os modificadores antes (57 repetições do GNOME → 1 alternância) e os gestos seguintes | +| CA2 | ok (unidade) | testes com relógio falso; push-to-talk não exercitado ao vivo (sem atalho cadastrado) | +| CA3 | ok | testes | +| CA4 | ok | testes; ao vivo `Press F10/F11` → `matchesTrigger: true` | +| CA5 | ok | `check-patches.mjs`: find único (módulo 532624), 3 matches × 1, módulo válido; ao vivo `Patched by WaylandKeybinds` | +| CA6 | ok | `pnpm build --dev`, `tsc` 0 erros, eslint 0 | +| CA7 | ok | CC máx. 7 (`planRegistration`), despachante 6; 32/32 mutantes mortos | +| CA8 | ok (mudo) | confirmado pelo usuário; ensurdecer registrado e vinculado no GNOME, não pressionado no teste | +| CA9 | ok (unidade) | teste `cancel` + patch do `inputEventUnregister` aplicado; não exercitado ao vivo | + +## 9. Registro +- 2026-11-01 — aprovação prévia do usuário ("pode fazer tudo de maneira autônoma"); portão da spec dispensado. +- 2026-11-01 — `wk:test` é um alias de comando, não script no `package.json` (não mexer em arquivo versionado): `pnpm exec esbuild logic.test.ts --bundle --platform=node --format=esm --outfile=/tmp/wk-test.mjs && node --test /tmp/wk-test.mjs`. +- 2026-11-02 — v1 (agir no pressionar) insuficiente ao vivo: o nativo do Discord ignora `Activated` enquanto acha a tecla pressionada; soltura perdida o deixa preso e o gesto seguinte some. Medido com `busctl monitor` (portal) × eventos crus no renderer (CDP): repetição automática do GNOME (500 ms, depois 30 ms) e engolimento até `Deactivated`. +- 2026-11-02 — experimento ao vivo: re-registrar (`inputEventUnregister`+`inputEventRegister`) zera o estado; com a tecla segurada, a repetição chega 0–30 ms após o re-registro; solta, nada chega. Base da v2 (sondagem). Desregistro gera soltura sintética assíncrona (tratada como eco). +- 2026-11-02 — usuário pediu tecla configurável: já é, pela tela de atalhos do Discord; o plugin não fixa teclas e vale para todas as ações (mudo, ensurdecer, push-to-talk). +- 2026-11-02 — a pedido do usuário, movido de `src/userplugins` para `src/plugins` (branch `feat/wayland-keybinds`, sem commit) com `enabledByDefault: true`: só altera o comportamento quando o Discord registra pelo portal.