[
  {
    "path": ".gitignore",
    "content": "thd\nthd.1\nth-cmd\nth-cmd.1\n*.o\n/*.d\nevtable_*.inc\nlinux_input_defs_gen.inc\nversion.h\n"
  },
  {
    "path": "AUTHORS",
    "content": "Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n"
  },
  {
    "path": "COPYING",
    "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    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<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"
  },
  {
    "path": "Makefile",
    "content": "PREFIX:=/usr/\nDESTDIR:=/\nBINDIR:=$(DESTDIR)/$(PREFIX)/sbin/\nMANDIR:=$(DESTDIR)/$(PREFIX)/share/man/man1/\n\nPKGCONFIG = pkg-config\nHAVE_PKGCONFIG = $(shell $(PKGCONFIG) --version 2>/dev/null || echo no)\nifneq ($(HAVE_PKGCONFIG),no)\nHAVE_SYSTEMD = $(shell $(PKGCONFIG) --exists libsystemd && echo 1 || echo 0)\nifeq ($(HAVE_SYSTEMD),1)\nCPPFLAGS += -DHAVE_SYSTEMD=1\nCFLAGS += $(shell $(PKGCONFIG) --cflags libsystemd)\nLDLIBS += $(shell $(PKGCONFIG) --libs libsystemd)\nendif\nendif\n\nVERSION:=$(shell cat version.inc)\n\nTHD_COMPS := thd keystate trigger eventnames devices cmdsocket obey ignore uinput triggerparser\nTHCMD_COMPS := th-cmd cmdsocket\n\nMAKEDEPEND = $(CC) -M -MG $(CPPFLAGS) -o $*.d $<\n\nall: thd th-cmd man\n\nman: thd.1 th-cmd.1\n\nthd: $(THD_COMPS:%=%.o)\n\nth-cmd: $(THCMD_COMPS:%=%.o)\n\n%.1: %.pod\n\tpod2man \\\n\t\t--center=\"Triggerhappy daemon\" \\\n\t\t--section=1 \\\n\t\t--release=\"$(VERSION)\" \\\n\t\t$< > $@\n\nlinux_input_defs_gen.inc:\n\techo \"#include <linux/input.h>\" | $(CC) $(CPPFLAGS) -dM -E - > $@\n\nevtable_%.inc: linux_input_defs_gen.inc\n\tawk '/^#define $*_/ && $$2 !~ /_(MIN_INTERESTING|MAX|CNT|VERSION)$$/ {print \"EV_MAP(\"$$2\"),\"}' $< > $@\n\nversion.h: version.inc\n\tsed -r 's!(.*)!#define TH_VERSION \"\\1\"!' $< > $@\n\nclean:\n\trm -f *.d\n\trm -f *.o\n\trm -f linux_input_defs_gen.inc\n\trm -f evtable_*.inc\n\trm -f version.h\n\trm -f thd th-cmd\n\trm -f thd.1 th-cmd.1\n\ninstall: all\n\tinstall -D thd $(BINDIR)/thd\n\tinstall -D th-cmd $(BINDIR)/th-cmd\n\tinstall -D thd.1 $(MANDIR)/thd.1\n\tinstall -D th-cmd.1 $(MANDIR)/th-cmd.1\n\n%.d : %.c\n\t$(MAKEDEPEND)\n\n-include $(THD_COMPS:%=%.d) $(THCMD_COMPS:%=%.d)\n"
  },
  {
    "path": "README",
    "content": "Triggerhappy\n- a lightweight hotkey daemon -\n\nby Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\nhttp://github.com/wertarbyte/triggerhappy/\n\nTriggerhappy is a hotkey daemon developed with small and embedded systems in\nmind, e.g. linux based routers. It attaches to the input device files and\ninterprets the event data received and executes scripts configured in its\nconfiguration.\n\nExamples:\n\nDump all events received through two device files:\n\n\tthd --dump /dev/input/event0 /dev/input/event1\n\nEvent handlers can be defined in configuration files (specified by --triggers).\nIf a directory is specified, all configuration files within matching the\npattern *.conf are loaded. The files use the following format:\n\n<event name>\t<event value>\t<command line>\n\ne.g.\n\nKEY_VOLUMEUP\t1\t\t/usr/bin/amixer set Master 5%+\nKEY_VOLUMEUP\t2\t\t/usr/bin/amixer set Master 5%+\nKEY_VOLUMEDOWN\t1\t\t/usr/bin/amixer set Master 5%-\nKEY_VOLUMEDOWN\t2\t\t/usr/bin/amixer set Master 5%-\n\nA value of 1 corresponds to pressing a key, while 2 is generated by\nholding it; releasing it yields a value of 0.\n\nIt is also possible to append up to 5 modifiers to each event definition by\nappending their names to the event name:\n\nKEY_VOLUMEUP+KEY_LEFTSHIFT\t1\t/usr/bin/amixer set Master 15%+\n\nDevices can be added dynamically by specifying a command socket:\n\nthd --socket /var/run/triggerhappy.socket --triggers /etc/triggerhappy.d/\n\nThe program th-cmd is used to add new devices to the daemon:\n\nth-cmd --socket /var/run/triggerhappy.socket --add /dev/input/event0\nth-cmd --socket /var/run/triggerhappy.socket --remove /dev/input/event3\n\nAn example udev script is also included to facilitate this hotplug\nsupport - for this use, th-cmd can handle the parameter \"udev\" to\ndeduce the device name and action from the udev environment.\n\nFor more information, consult the manual pages of \"thd\" and \"th-cmd\".\n"
  },
  {
    "path": "cmdsocket.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n\n#ifdef HAVE_SYSTEMD\n#include <systemd/sd-daemon.h>\n#endif\n\n#include \"devtag.h\"\n#include \"devices.h\"\n#include \"command.h\"\n#include \"cmdsocket.h\"\n\nint bind_cmdsocket( char *name ) {\n\tint cmd_fd;\n\n#ifdef HAVE_SYSTEMD\n\tif (sd_listen_fds(0) == 1) {\n\t\tfprintf(stderr, SD_DEBUG \"Found socket passed from systemd\\n\");\n\t\treturn SD_LISTEN_FDS_START + 0;\n\t}\n#endif\n\n\tstruct sockaddr_un addr;\n\t/* remove any stale files */\n\tstruct stat sb;\n\tint serr = stat(name, &sb);\n\tif ( !serr && S_ISSOCK(sb.st_mode)) {\n\t\tunlink(name);\n\t}\n\tcmd_fd = socket(AF_UNIX, SOCK_DGRAM, 0);\n\tstrcpy(addr.sun_path, name);\n\taddr.sun_family = AF_UNIX;\n\tbind (cmd_fd, (struct sockaddr *) &addr, \n\t\tstrlen(addr.sun_path) + sizeof (addr.sun_family));\n\treturn cmd_fd;\n}\n\nint connect_cmdsocket( char *name ) {\n\tint fd;\n\tstruct sockaddr_un server;\n\tfd = socket(AF_UNIX, SOCK_DGRAM, 0);\n\tstrcpy(server.sun_path, name);\n\tserver.sun_family = AF_UNIX;\n\tconnect(fd, (struct sockaddr *) &server,\n\t\tstrlen(server.sun_path) + sizeof (server.sun_family));\n\treturn fd;\n}\n\nstruct command *read_command( int cmd_fd ) {\n\tstruct command *cmd = malloc(sizeof(struct command));\n\tif (! cmd) {\n\t\tfprintf(stderr, \"Unable to allocate memory for command!\\n\");\n\t\treturn NULL;\n\t}\n\n\tint fd[1] = {-1};\n\tchar buffer[CMSG_SPACE(sizeof fd)];\n\n\tstruct iovec v = {\n\t\t.iov_base = cmd,\n\t\t.iov_len  = sizeof(*cmd)\n\t};\n\tstruct msghdr msg = {\n\t\t.msg_iov        = &v,\n\t\t.msg_iovlen     = 1,\n\t\t.msg_control    = buffer,\n\t\t.msg_controllen = sizeof(buffer)\n\t};\n\n\tint done = recvmsg( cmd_fd, &msg, 0 );\n\n\tif (done == -1) {\n\t\tfprintf(stderr, \"Error reading command.\");\n\t\tfree(cmd);\n\t\treturn NULL;\n\t}\n\tstruct cmsghdr *cmessage = CMSG_FIRSTHDR(&msg);\n\tif (cmessage) {\n\t\tmemcpy(fd, CMSG_DATA(cmessage), sizeof fd);\n\t\t/* place FD back in the command message */\n\t\tcmd->fd = (int) fd[0];\n\t}\n\treturn cmd;\n}\n\nint send_command( int cmd_fd, enum command_type type, char *param, int passfd, int exclusive, char *tag ) {\n\tif (type == CMD_ADD && passfd == 1) {\n\t\ttype = CMD_PASSFD;\n\t}\n\tstruct command cmd = {\n\t\t.fd    = -1,\n\t\t.exclusive = exclusive,\n\t\t.type  = type,\n\t\t.param = {0},\n\t\t.tag = {0}\n\t};\n\tif (param != NULL) {\n\t\tstrncpy(cmd.param, param, TH_COMMAND_PARAM_LENGTH);\n\t\tcmd.param[TH_COMMAND_PARAM_LENGTH-1] = '\\0';\n\t}\n\tif (tag != NULL) {\n\t\tstrncpy(cmd.tag, tag, TH_DEVICE_TAG_LENGTH);\n\t\tcmd.tag[TH_DEVICE_TAG_LENGTH-1] = '\\0';\n\t}\n\n\tstruct iovec v = {\n\t\t.iov_base = &cmd,\n\t\t.iov_len = sizeof(cmd)\n\t};\n\tstruct msghdr m = {\n\t\t.msg_iov    = &v,\n\t\t.msg_iovlen = 1\n\t};\n\n\t/* add FD */\n\tint dev_fd[1] = { -1 };\n\tchar buffer[CMSG_SPACE(sizeof(dev_fd))];\n\tif (passfd) {\n\t\tint fd = open( param, O_RDONLY );\n\t\tif (fd < 0) {\n\t\t\tperror(\"open\");\n\t\t\treturn 1;\n\t\t}\n\t\tdev_fd[0] = fd ;\n\t\tm.msg_control = buffer;\n\t\tm.msg_controllen = sizeof(buffer);\n\n\t\tstruct cmsghdr *cmessage = CMSG_FIRSTHDR(&m);\n\t\tcmessage->cmsg_level = SOL_SOCKET;\n\t\tcmessage->cmsg_type = SCM_RIGHTS;\n\t\tcmessage->cmsg_len = CMSG_LEN(sizeof(dev_fd));\n\n\t\tm.msg_controllen = cmessage->cmsg_len;\n\t\tmemcpy(CMSG_DATA(cmessage), dev_fd, sizeof dev_fd);\n\t}\n\tint done = sendmsg( cmd_fd, &m, 0 );\n\treturn (done == -1);\n}\n"
  },
  {
    "path": "cmdsocket.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\nint bind_cmdsocket(char *name);\nstruct command *read_command(int cmd_fd);\nint send_command(int cmd_fd, enum command_type type, char *param, int passfd, int exclusive, char *tag);\nint connect_cmdsocket(char *name);\n"
  },
  {
    "path": "command.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include \"devtag.h\"\n#define TH_COMMAND_PARAM_LENGTH 256\n\nenum command_type {\n\tCMD_NOP,\n\tCMD_ADD,\n\tCMD_REMOVE,\n\tCMD_QUIT,\n\tCMD_DISABLE,\n\tCMD_ENABLE,\n\tCMD_PASSFD,\n\tCMD_CLEARDEVS,\n\tCMD_CHANGEMODE\n};\n\nstruct command {\n\tenum command_type type;\n\t/* udev pathnames are long, but not that long */\n\tchar param[TH_COMMAND_PARAM_LENGTH];\n\tint fd;\n\tint exclusive;\n\tchar tag[TH_DEVICE_TAG_LENGTH];\n};\n"
  },
  {
    "path": "devices.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <string.h>\n#include <errno.h>\n#include <linux/input.h>\n#include <linux/hiddev.h>\n#include <sys/ioctl.h>\n#include <inttypes.h>\n\n#include \"devices.h\"\n#include \"eventnames.h\"\n\n#define BITFIELD uint32_t\n\nstatic device *device_list = NULL;\n\nchar *get_device_description(int fd) {\n\tchar descr[256] = \"Unknown\";\n\tif(ioctl(fd, EVIOCGNAME(sizeof(descr)), descr) < 0) {\n\t\tperror(\"evdev ioctl\");\n\t}\n\treturn strdup(descr);\n}\n\nstatic __inline__ int test_bit(int nr, BITFIELD * addr) {\n\tBITFIELD mask;\n\n\taddr += nr >> 5;\n\tmask = 1 << (nr & 0x1f);\n\treturn ((mask & *addr) != 0);\n}\n\nint device_is_suitable(int fd) {\n\tBITFIELD bits[32];\n\tint rc = ioctl(fd, EVIOCGBIT(0,sizeof(bits)), bits);\n\treturn rc > 0 && (\n\t\t/* we only consider devices with keys or switches suitable */\n\t\ttest_bit(EV_KEY, bits) || test_bit(EV_SW, bits)\n\t);\n}\n\nvoid add_device(char *dev, int fd, int excl, char *tag) {\n\tdevice **p = &device_list;\n\t// find end of list\n\twhile (*p != NULL) {\n\t\tp = &( (*p)->next );\n\t}\n\tif (fd < 0) {\n\t\tfd = open( dev, O_RDONLY );\n\t}\n\tif (fd >= 0) {\n\t\tif (! device_is_suitable(fd) ) {\n\t\t\tfprintf(stderr, \"Device %s not suitable.\\n\", dev);\n\t\t\tclose(fd);\n\t\t\treturn;\n\t\t}\n\t\t/* grab device exclusively */\n\t\tif (excl) {\n\t\t\tif (ioctl(fd, EVIOCGRAB, 1) == -1) {\n\t\t\t\tfprintf(stderr, \"Device %s cannot be grabbed exclusively.\\n\", dev);\n\t\t\t\tclose(fd);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t*p = malloc(sizeof(device));\n\t\tif (*p == NULL) goto nomem_cleanup;\n\t\tmemset(*p, 0, sizeof(device));\n\t\t(*p)->devname = strdup(dev);\n\t\tif ((*p)->devname == NULL) goto nomem_cleanup;\n\t\t(*p)->fd = fd;\n\t\t(*p)->exclusive = excl;\n\t\tif (tag) {\n\t\t\tstrncpy((*p)->tag, tag, TH_DEVICE_TAG_LENGTH);\n\t\t\t(*p)->tag[TH_DEVICE_TAG_LENGTH-1] = '\\0';\n\t\t}\n\t\t(*p)->next = NULL;\n\t} else {\n\t\tfprintf( stderr, \"Error opening '%s': %s\\n\", dev, strerror(errno) );\n\t}\n\treturn;\nnomem_cleanup:\n\tfprintf(stderr, \"Unable to allocate memory for new device!\\n\");\n\tif (*p) {\n\t\tfree( (*p)->devname );\n\t}\n\tfree(*p);\n\t*p = NULL;\n}\n\nint remove_device(char *dev) {\n\tdevice **p = &device_list;\n\twhile (*p != NULL) {\n\t\tif ( strcmp( (*p)->devname, dev ) == 0 ) {\n\t\t\tdevice *copy = *p;\n\t\t\t/* bypass the list item */\n\t\t\t*p = copy->next;\n\t\t\tclose(copy->fd);\n\t\t\tfree(copy->devname);\n\t\t\tfree(copy);\n\t\t\treturn 1;\n\t\t}\n\t\t/* advance to the next node */\n\t\tp = &( (*p)->next );\n\t}\n\t/* reached the end of the list */\n\treturn 0;\n}\n\nvoid clear_devices(void) {\n\tdevice *p = device_list;\n\twhile (p != NULL) {\n\t\tdevice *next = p->next;\n\t\tclose(p->fd);\n\t\tfree(p->devname);\n\t\tfree(p);\n\t\tp = next;\n\t}\n\tdevice_list = NULL;\n}\n\nint count_devices(void) {\n\tint n = 0;\n\tdevice *p = device_list;\n\twhile (p != NULL) {\n\t\tn++;\n\t\tp = p->next;\n\t}\n\treturn n;\n}\n\nvoid for_each_device( void(*func)(device*) ) {\n\tdevice *p = device_list;\n\twhile (p != NULL) {\n\t\tfunc( p );\n\t\tp = p->next;\n\t}\n}\n"
  },
  {
    "path": "devices.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include \"devtag.h\"\n\ntypedef struct device {\n\tint fd;\n\tchar *devname;\n\tint exclusive;\n\tchar tag[TH_DEVICE_TAG_LENGTH];\n\tstruct device *next;\n} device;\n\nvoid add_device(char *dev, int fd, int excl, char *tag);\nint remove_device(char *dev);\nvoid clear_devices(void);\nint count_devices(void);\n\nvoid for_each_device( void(*func)(device*) );\n\nchar *get_device_description(int fd);\n"
  },
  {
    "path": "devtag.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#define TH_DEVICE_TAG_LENGTH 256\n"
  },
  {
    "path": "eventnames.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <stdlib.h>\n#include <linux/input.h>\n#include <string.h>\n#include \"eventnames.h\"\n#include \"eventtable.h\"\n\nconst char *lookup_event_name_i( const int evtype, const int evcode ) {\n\tswitch(evtype) {\n\t\tcase EV_KEY:\n\t\t\treturn (KEY_MAX >= evcode ? KEY_NAME[ evcode ] : NULL);\n\t\tcase EV_SW:\n\t\t\treturn (SW_MAX >= evcode ? SW_NAME[ evcode ] : NULL);\n\t\tcase EV_REL:\n\t\t\treturn (REL_MAX >= evcode ? REL_NAME[ evcode ] : NULL);\n\t\tcase EV_ABS:\n\t\t\treturn (ABS_MAX >= evcode ? ABS_NAME[ evcode ] : NULL);\n\t\tdefault:\n\t\t\treturn NULL;\n\t}\n}\n\nconst char *lookup_event_name( const struct input_event ev ) {\n\treturn lookup_event_name_i( ev.type, ev.code );\n}\n\nconst char *lookup_type_name_i( const int evtype ) {\n\treturn (EV_MAX >= evtype ? EV_NAME[ evtype ] : NULL);\n}\n\nconst char *lookup_type_name( const struct input_event ev ) {\n\treturn lookup_type_name_i( ev.type );\n}\n\nstatic int lookup_index(const char **map, const char *value, int max) {\n\tint i = 0;\n\twhile (i <= max) {\n\t\tif (map[i] != NULL &&\n\t\t    strcmp(value, map[i])  == 0) {\n\t\t\treturn i;\n\t\t}\n\t\ti++;\n\t}\n\treturn -1;\n}\n\nint lookup_event_code( const char *eventname ) {\n\tint res = -1;\n\tif (res == -1) res = lookup_index(KEY_NAME, eventname, KEY_MAX);\n\tif (res == -1) res = lookup_index(SW_NAME, eventname, SW_MAX);\n\tif (res == -1) res = lookup_index(REL_NAME, eventname, REL_MAX);\n\tif (res == -1) res = lookup_index(ABS_NAME, eventname, ABS_MAX);\n\treturn res;\n}\n\nint lookup_event_type( const char *eventname ) {\n\tif (lookup_index(KEY_NAME, eventname, KEY_MAX) != -1) {\n\t\treturn EV_KEY;\n\t}\n\tif (lookup_index(SW_NAME, eventname, SW_MAX) != -1) {\n\t\treturn EV_SW;\n\t}\n\tif (lookup_index(REL_NAME, eventname, REL_MAX) != -1) {\n\t\treturn EV_REL;\n\t}\n\tif (lookup_index(ABS_NAME, eventname, ABS_MAX) != -1) {\n\t\treturn EV_ABS;\n\t}\n\treturn -1;\n}\n"
  },
  {
    "path": "eventnames.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <linux/input.h>\n\nconst char *lookup_event_name_i(const int evtype, const int evcode);\nconst char *lookup_event_name(const struct input_event ev);\n\nconst char *lookup_type_name_i(const int evtype);\nconst char *lookup_type_name(const struct input_event ev);\n\nint lookup_event_code(const char *eventname);\nint lookup_event_type(const char *eventname);\n"
  },
  {
    "path": "eventtable.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <linux/input.h>\n\n#define EV_MAP( N ) [ N ] = #N\n\nstatic const char *EV_NAME[EV_CNT] = {\n#include \"evtable_EV.inc\"\n};\n\nstatic const char *KEY_NAME[KEY_CNT] = {\n#include \"evtable_KEY.inc\"\n#include \"evtable_BTN.inc\"\n};\n\nstatic const char *REL_NAME[REL_CNT] = {\n#include \"evtable_REL.inc\"\n};\n\nstatic const char *ABS_NAME[ABS_CNT] = {\n#include \"evtable_ABS.inc\"\n};\n\nstatic const char *SW_NAME[SW_CNT] = {\n#include \"evtable_SW.inc\"\n};\n"
  },
  {
    "path": "ignore.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include \"ignore.h\"\n\nvoid ignore_key( int code, ignore **list ) {\n\tignore **p = list;\n\twhile ( *p != NULL ) {\n\t\tp = &( (*p)->next );\n\t}\n\t*p = malloc( sizeof(ignore) );\n\tif (*p) {\n\t\t(*p)->next = NULL;\n\t\t(*p)->code = code;\n\t} else {\n\t\tfprintf(stderr, \"Unable to allocate memory for ignored key!\\n\");\n\t}\n}\n\nvoid print_ignores( ignore *list ) {\n\tignore *p = list;\n\twhile ( p != NULL ) {\n\t\tp = p->next;\n\t}\n}\n\nint is_ignored( int code, ignore *list ) {\n\tignore *p = list;\n\twhile ( p != NULL ) {\n\t\tif (p->code == code) {\n\t\t\treturn 1;\n\t\t}\n\t\tp = p->next;\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "ignore.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\ntypedef struct ignore {\n\tint code;\n\tstruct ignore *next;\n} ignore;\n\nvoid ignore_key( int code, ignore **list );\nint is_ignored( int code, ignore *list );\nvoid clear_ignore_list( ignore **list );\n"
  },
  {
    "path": "keystate.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <stdio.h>\n#include <linux/input.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"eventnames.h\"\n#include \"keystate.h\"\n\nvoid init_keystate_holder(keystate_holder **ksh) {\n\tif (*ksh == NULL) {\n\t\t*ksh = malloc(sizeof(keystate_holder));\n\t}\n\tif (*ksh == NULL) {\n\t\tfprintf(stderr, \"Unable to allocate memory for keystate table!\\n\");\n\t\treturn;\n\t}\n\tint i;\n\tfor (i=0; i<=KEY_MAX; i++) {\n\t\t(**ksh)[i] = 0;\n\t}\n}\n\n/*\n * Keep track of a pressed or released key\n */\nvoid change_keystate( keystate_holder ksh, struct input_event ev ) {\n\tif (ev.type != EV_KEY)\n\t\treturn;\n\tif (ev.code > KEY_MAX)\n\t\treturn;\n\tswitch(ev.value) {\n\t\tcase 1: // pressed\n\t\t\tksh[ev.code]++;\n\t\t\tbreak;\n\t\tcase 0: // released\n\t\t\tif (ksh[ev.code] > 0) {\n\t\t\t\tksh[ev.code]--;\n\t\t\t}\n\t\t\tbreak;\n\t}\n}\n\nchar *get_keystate(keystate_holder ksh) {\n\treturn get_keystate_ignore_key( ksh, -1 );\n}\n\nchar *get_keystate_ignore_key(keystate_holder ksh, int ignore_key) {\n\tconst int bsize = 1024;\n\tchar *KS = \"+\";\n\n\tchar buf[bsize];\n\tbuf[0] = '\\0';\n\n\tint i;\n\tint n = 0;\n\tfor (i=0; i<=KEY_MAX; i++) {\n\t\tif (i != ignore_key && ksh[i] > 0) {\n\t\t\tif (n>0) {\n\t\t\t\tstrncat( buf, KS, bsize-1-strlen(KS) );\n\t\t\t}\n\t\t\tconst char *name = lookup_event_name_i(EV_KEY, i);\n\t\t\tstrncat( &(buf[0]), name, bsize-1-strlen(buf) );\n\t\t\tn++;\n\t\t}\n\t}\n\tchar *res = malloc( sizeof(char) * (1+strlen(buf)) );\n\tif (res) {\n\t\tstrcpy( res, buf );\n\t}\n\treturn res;\n}\n"
  },
  {
    "path": "keystate.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <linux/input.h>\ntypedef unsigned short keystate_holder[KEY_MAX+1];\n\nvoid init_keystate_holder(keystate_holder**);\nvoid change_keystate(keystate_holder, struct input_event);\nchar *get_keystate(keystate_holder);\nchar *get_keystate_ignore_key(keystate_holder, int ignore_key);\n"
  },
  {
    "path": "obey.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <stdio.h>\n#include \"devices.h\"\n#include \"command.h\"\n#include \"keystate.h\"\n#include \"trigger.h\"\n#include \"thd.h\"\n\nint obey_command( struct command *cmd ) {\n\tif (cmd->type == CMD_ADD) {\n\t\tadd_device( cmd->param, -1, cmd->exclusive, cmd->tag );\n\t\treturn 0;\n\t}\n\tif (cmd->type == CMD_PASSFD) {\n\t\tadd_device( cmd->param, cmd->fd, cmd->exclusive, cmd->tag );\n\t\treturn 0;\n\t}\n\tif (cmd->type == CMD_REMOVE) {\n\t\tremove_device( cmd->param );\n\t\treturn 0;\n\t}\n\tif (cmd->type == CMD_QUIT) {\n\t\tcleanup();\n\t\treturn 0;\n\t}\n\tif (cmd->type == CMD_ENABLE) {\n\t\ttriggers_enabled(1);\n\t\treturn 0;\n\t}\n\tif (cmd->type == CMD_DISABLE) {\n\t\ttriggers_enabled(0);\n\t\treturn 0;\n\t}\n\tif (cmd->type == CMD_CLEARDEVS) {\n\t\tclear_devices();\n\t\treturn 0;\n\t}\n\tif (cmd->type == CMD_CHANGEMODE) {\n\t\tchange_trigger_mode( cmd->param );\n\t\treturn 0;\n\t}\n\treturn 1;\n}\n"
  },
  {
    "path": "obey.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\nint obey_command( struct command *cmd );\n"
  },
  {
    "path": "systemd/triggerhappy.service",
    "content": "[Unit]\nDescription=triggerhappy global hotkey daemon\nAfter=local-fs.target\n\n[Service]\nType=notify\nExecStart=/usr/sbin/thd --triggers /etc/triggerhappy/triggers.d/ --socket /run/thd.socket --user nobody --deviceglob /dev/input/event*\n\n[Install]\nWantedBy=multi-user.target\n"
  },
  {
    "path": "systemd/triggerhappy.socket",
    "content": "[Socket]\nListenStream=/run/thd.socket\n\n[Install]\nWantedBy=sockets.target\n"
  },
  {
    "path": "th-cmd.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <errno.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <strings.h>\n#include <getopt.h>\n#include <unistd.h>\n\n#include \"devices.h\"\n#include \"command.h\"\n#include \"cmdsocket.h\"\n\n#include \"version.h\"\n\nvoid show_help(void) {\n\tfprintf( stderr, \"Triggerhappy command \" TH_VERSION \"\\n\");\n\tfprintf( stderr, \"Use:\\n\");\n\tfprintf( stderr, \"  th-cmd --socket <socket> [--grab] [--passfd] --add <devices...>\\n\");\n\tfprintf( stderr, \"  th-cmd --socket <socket> --remove <devices...>\\n\");\n\tfprintf( stderr, \"  th-cmd --socket <socket> --clear\\n\");\n\tfprintf( stderr, \"  th-cmd --socket <socket> --enable\\n\");\n\tfprintf( stderr, \"  th-cmd --socket <socket> --disable\\n\");\n\tfprintf( stderr, \"  th-cmd --socket <socket> --mode <mode>\\n\");\n\tfprintf( stderr, \"  th-cmd --socket <socket> --quit\\n\");\n\tfprintf( stderr, \"  th-cmd --socket <socket> --help\\n\");\n}\n\nint main(int argc, char *argv[]) {\n\tchar *socket = NULL;\n\tstatic int passfd = 0;\n\tstatic int grab_dev = 0;\n\tstatic int op_add = 0;\n\tstatic int op_rem = 0;\n\tstatic int op_clear = 0;\n\tstatic int op_udev = 0;\n\tstatic int op_en = 0;\n\tstatic int op_dis = 0;\n\tstatic int op_mode = 0;\n\tstatic int op_quit = 0;\n\tenum command_type ctype = CMD_NOP;\n\n\tchar *tag = NULL;\n\n\tstatic struct option long_options[] = {\n\t\t{ \"socket\", 1, 0, 's' },\n\t\t{ \"add\", 0, &op_add, 1 },\n\t\t{ \"remove\", 0, &op_rem, 1 },\n\t\t{ \"clear\", 0, &op_clear, 1 },\n\t\t{ \"udev\", 0, &op_udev, 1 },\n\t\t{ \"passfd\", 0, &passfd, 1 },\n\t\t{ \"grab\", 0, &grab_dev, 1 },\n\t\t{ \"enable\", 0, &op_en, 1 },\n\t\t{ \"disable\", 0, &op_dis, 1 },\n\t\t{ \"mode\", 0, &op_mode, 1 },\n\t\t{ \"quit\", 0, &op_quit, 1 },\n\t\t{ \"help\", 0, 0, 'h' },\n\t\t{ \"tag\", required_argument, 0, 't' },\n\t\t{ 0, 0, 0, 0 }\n\t};\n\n\tint c;\n\twhile (1) {\n\t\tint option_index = 0;\n\t\tc = getopt_long(argc, argv, \"s:t:\", long_options, &option_index);\n\t\tif (c == -1) {\n\t\t\tbreak;\n\t\t}\n\t\tswitch(c) {\n\t\t\tcase 's':\n\t\t\t\tsocket = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\ttag = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\tcase '?':\n\t\t\tcase -1:\n\t\t\t\tshow_help();\n\t\t\t\treturn 1;\n\t\t}\n\t}\n\n\tif ( op_add + op_rem + op_clear + op_udev + op_en + op_dis + op_mode + op_quit != 1 ) {\n\t\tfprintf(stderr, \"A single command must be specified!\\n\");\n\t\tshow_help();\n\t\treturn 1;\n\t}\n\n\tif (! socket ) {\n\t\tfprintf(stderr, \"No socket specified!\\n\");\n\t\tshow_help();\n\t\treturn 1;\n\t}\n\tint s = connect_cmdsocket( socket );\n\tif (s < 0) {\n\t\tperror(\"connect()\");\n\t\treturn 1;\n\t}\n\n\tint err = 0;\n\tif (op_udev) {\n\t\tif (strcasecmp(\"add\", getenv(\"ACTION\")) == 0) {\n\t\t\tctype = CMD_ADD;\n\t\t} else if (strcasecmp(\"remove\", getenv(\"ACTION\")) == 0) {\n\t\t\tctype = CMD_REMOVE;\n\t\t}\n\t\tchar *dev = getenv(\"DEVNAME\");\n\t\tif ( ctype && dev ) {\n\t\t\terr = send_command( s, ctype, dev, passfd, grab_dev, tag );\n\t\t}\n\t} else {\n\t\t/* get devices from command line */\n\t\tif (op_add) ctype = CMD_ADD;\n\t\telse if (op_rem) ctype = CMD_REMOVE;\n\t\telse if (op_clear) ctype = CMD_CLEARDEVS;\n\t\telse if (op_en) ctype = CMD_ENABLE;\n\t\telse if (op_dis) ctype = CMD_DISABLE;\n\t\telse if (op_mode) ctype = CMD_CHANGEMODE;\n\t\telse if (op_quit) ctype = CMD_QUIT;\n\n\t\tif ( ctype == CMD_NOP) {\n\t\t\tshow_help();\n\t\t}\n\t\tswitch (ctype) {\n\t\t\tcase CMD_CLEARDEVS:\n\t\t\tcase CMD_ENABLE:\n\t\t\tcase CMD_DISABLE:\n\t\t\tcase CMD_QUIT:\n\t\t\t\terr = send_command( s, ctype, \"\", 0, 0, tag);\n\t\t\t\tbreak;\n\t\t\tcase CMD_CHANGEMODE:\n\t\t\t\terr = send_command( s, ctype,\n\t\t\t\t\t\t(optind < argc) ? argv[optind] : \"\",\n\t\t\t\t\t\t0, 0, tag );\n\t\t\t\tbreak;\n\t\t\tcase CMD_ADD:\n\t\t\tcase CMD_REMOVE:\n\t\t\t\twhile (optind < argc && err == 0) {\n\t\t\t\t\terr = send_command( s, ctype, argv[optind++], passfd, grab_dev, tag );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\terr = 1;\n\t\t}\n\t\tif (err != 0) {\n\t\t\tperror(\"send_command\");\n\t\t}\n\t}\n\tclose(s);\n\treturn err;\n}\n"
  },
  {
    "path": "th-cmd.pod",
    "content": "=pod\n\n=head1 NAME\n\nth-cmd -- triggerhappy commander\n\n=head1 SYNOPSIS\n\nB<th-cmd> --socket B<< <socket> >> [B<--passfd>] [B<--tag> I<< <foo> >>] [B<--clear>|B<--enable>|B<--disable>|B<--mode> I<< <mode> >>|B<--quit>|B<--udev>|B<--add> F<< <devices...> >>|B<--remove> F<< <devices...> >>]\n\n=head1 DESCRIPTION\n\nThis program is used to issue commands to a running triggerhappy daemon. It utilizes an unix domain socket bound by the daemon.\n\n=head1 OPTIONS\n\n=over\n\n=item B<--socket> F<socket>\n\nThe socket file opened by the running triggerhappy daemon instance.\n\n=item B<--add> F<< <devices...> >>\n\nInstruct the running daemon to open the input devices specified on the command line\n\n=item B<--remove> F<< <devices...> >>\n\nRemove specified devices from the running daemon.\n\n=item B<--clear>\n\nRemove all devices from the running daemon.\n\n=item B<--udev>\n\nDeduce operation and device name from udev environment (for use in udev rules).\n\n=item B<--disable>\n\nDisable the execution of triggers.\n\n=item B<--enable>\n\nRe-enable the execution of triggers.\n\n=item B<--mode> I<< <newmode> >>\n\nChange the mode of the triggerhappy daemon to I<< <newmode> >>. If no new mode is specified, the daemon switches to default mode.\n\n=item B<--quit>\n\nTerminate the triggerhappy daemon.\n\n=item B<--passfd>\n\nInstead of instructing the daemon to open the device, open the device and pass the file descriptor to the daemon. This allows the adding of new devices to a daemon having dropped its privileges, however the th-cmd process must have access to the device file.\n\n=item B<--grab>\n\nGrab the device; the triggerhappy daemon will try to get exclusive access to the device, other applications will not receive the events emitted by it.\n\n=item B<--tag> F<foo>\n\nLabel the added device with the tag I<< <foo> >>; this can be used to limit the scope of event\nhandlers to a subset of input devices.\n\n=back\n\n=head1 AUTHOR\n\nStefan Tomanek E<lt>stefan.tomanek+th@wertarbyte.deE<gt>\n\n"
  },
  {
    "path": "thd.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <stdio.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <string.h>\n#include <errno.h>\n#include <signal.h>\n#include <glob.h>\n\n#include <stdlib.h>\n#include <sys/wait.h>\n#include <sys/select.h>\n#include <sys/time.h>\n#include <getopt.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <stddef.h>\n#include <pwd.h>\n#include <grp.h>\n\n#ifdef HAVE_SYSTEMD\n#include <systemd/sd-daemon.h>\n#endif\n\n#include \"thd.h\"\n#include \"eventnames.h\"\n#include \"devices.h\"\n#include \"keystate.h\"\n#include \"trigger.h\"\n#include \"command.h\"\n#include \"cmdsocket.h\"\n#include \"obey.h\"\n#include \"ignore.h\"\n#include \"uinput.h\"\n\n/* version information */\n#include \"version.h\"\n\n/* command channel & FD */\nstatic char *cmd_file = NULL;\nstatic int cmd_fd = -1;\n\nstatic char *uinput_dev = NULL;\n\nstatic int dump_events = 0;\nstatic int run_as_daemon = 0;\n\nstatic char *triggerfile = NULL;\nstatic char *pidfile = NULL;\n\nstatic keystate_holder *keystate = NULL;\n\nstatic ignore *ignored_keys = NULL;\n\nstatic int normalize_events = 0;\n\nstatic char *user = NULL;\n\nstatic int exiting = 0;\nstatic int reload_conf = 0;\n\n/* forward declarations */\nstatic int reload_triggerfile();\n\n/* FDs to watch */\nstatic fd_set rfds;\nstatic int max_fd = -1;\n\n/*\n * Look up event and key names and print them to STDOUT\n */\nstatic void print_event(char* dev, struct input_event ev) {\n\tconst char *typename = lookup_type_name( ev );\n\tconst char *evname = lookup_event_name( ev );\n\tif ( evname != NULL ) {\n\t\tprintf( \"%s\\t%s\\t%d\\t%s\\n\", typename, evname, ev.value, dev );\n\t} else {\n\t\tfprintf( stderr, \"Unknown %s event id on %s : %d (value %d)\\n\", typename, dev, ev.code, ev.value );\n\t}\n\tfflush(stdout);\n}\n\nstatic void print_triggerline(struct input_event ev, keystate_holder ksh) {\n\tconst char *evname = lookup_event_name( ev );\n\tchar *state = ( ev.type == EV_KEY ? get_keystate_ignore_key( ksh, ev.code ) : NULL);\n\tconst int d = (state && strlen(state)>0);\n\tif ( evname != NULL ) {\n\t\tprintf( \"# %s%s%s\\t%d\\tcommand\\n\", state?state:\"\", d?\"+\":\"\", evname, ev.value );\n\t\tfflush(stdout);\n\t}\n\tfree(state);\n}\n\n/*\n * Read event from fd, decode it and pass it to handlers\n */\nstatic int read_event( device *dev ) {\n\tint fd = dev->fd;\n\tchar *devname = dev->devname;\n\tstruct input_event ev;\n\tint n = read( fd, &ev, sizeof(ev) );\n\tif ( n != sizeof(ev) ) {\n\t\tfprintf(stderr, \"Error reading device '%s'\\n\", dev->devname);\n\t\treturn 1;\n\t}\n\t/* ignore all events except KEY, SW and REL*/\n\tif (ev.type == EV_KEY || ev.type == EV_SW || ev.type == EV_REL || ev.type == EV_ABS) {\n\t\tif (ev.type == EV_KEY && is_ignored( ev.code, ignored_keys)) {\n\t\t\treturn 0;\n\t\t}\n\t\tif ((ev.type == EV_REL || ev.type == EV_ABS) && normalize_events) {\n\t\t\tif (ev.value > 0) {\n\t\t\t\tev.value = 1;\n\t\t\t} else if (ev.value < 0) {\n\t\t\t\tev.value = -1;\n\t\t\t}\n\t\t}\n\t\tif (dump_events) {\n\t\t\tprint_event( devname, ev );\n\t\t\tprint_triggerline( ev, *keystate );\n\t\t}\n\t\trun_triggers( ev.type, ev.code, ev.value, *keystate, dev );\n\t\tchange_keystate( *keystate, ev );\n\t}\n\treturn 0;\n}\n\nstatic void check_device( device *d ) {\n\tint fd = d->fd;\n\tif (FD_ISSET( fd, &rfds )) {\n\t\tif (read_event( d )) {\n\t\t\t/* read error? Remove the device! */\n\t\t\tremove_device( d->devname );\n\t\t}\n\t}\n}\n\nstatic void process_devices(void) {\n\tfor_each_device( &check_device );\n}\n\nstatic void add_device_to_fdset( device *d ) {\n\tint fd = d->fd;\n\tif (fd > max_fd) {\n\t\tmax_fd = fd;\n\t}\n\tFD_SET( fd, &rfds );\n}\n\n\nstatic void process_events(void) {\n\tstruct timeval tv;\n\tint retval;\n\t/* loop as long as we have at least one device or\n\t * the command channel\n\t */\n\twhile ( count_devices() > 0 || cmd_fd != -1 ) {\n\t\tFD_ZERO( &rfds );\n\t\tmax_fd = -1;\n\t\t/* add device fds */\n\t\tfor_each_device( &add_device_to_fdset );\n\t\t/* add command channel */\n\t\tif (cmd_fd != -1) {\n\t\t\tFD_SET( cmd_fd, &rfds );\n\t\t\tmax_fd = cmd_fd > max_fd ? cmd_fd : max_fd;\n\t\t}\n\t\ttv.tv_sec = 5;\n\t\ttv.tv_usec = 0;\n\t\tretval = select(max_fd+1, &rfds, NULL, NULL, &tv);\n\t\tif (retval == -1 && errno != EINTR) {\n\t\t\tperror(\"select()\");\n\t\t\tcontinue;\n\t\t} else if (exiting) {\n\t\t\tbreak;\n\t\t} else if (reload_conf) {\n\t\t\treload_conf = 0;\n\t\t\treload_triggerfile();\n\t\t\tcontinue;\n\t\t} else if (retval) {\n\t\t\tprocess_devices();\n\t\t\tif ( cmd_fd != -1 && FD_ISSET( cmd_fd, &rfds ) ) {\n\t\t\t\tstruct command *cmd = read_command( cmd_fd );\n\t\t\t\tobey_command( cmd );\n\t\t\t\tfree(cmd);\n\t\t\t}\n\t\t}\n\t}\n}\n\nstatic int write_pidfile( char *pidfile ) {\n\tFILE *pid = fopen( pidfile, \"w+\" );\n\tif (pid == NULL) {\n\t\treturn 1;\n\t}\n\tfprintf(pid, \"%u\\n\", (unsigned int) getpid());\n\treturn fclose(pid);\n}\n\nstatic struct option long_options[] = {\n\t{\"dump\",\tno_argument, &dump_events, 1},\n\t{\"daemon\",\tno_argument, &run_as_daemon, 1},\n\t{\"user\",\trequired_argument, 0, 'u'},\n\t{\"pidfile\",\trequired_argument, 0, 'p'},\n\t{\"triggers\",\trequired_argument, 0, 't'},\n\t{\"socket\",\trequired_argument, 0, 's'},\n\t{\"ignore\",\trequired_argument, 0, 'i'},\n\t{\"normalize\",\tno_argument, &normalize_events, 1},\n\t{\"help\",\tno_argument, 0, 'h'},\n\t{\"uinput\",\trequired_argument, 0, '<'},\n\t{\"listevents\",\tno_argument, 0, 'l'},\n\t{\"deviceglob\",\trequired_argument, 0, 'g'},\n\t{0,0,0,0} /* end of list */\n};\n\nvoid show_help(void) {\n\tprintf( \"Triggerhappy event daemon \" TH_VERSION \"\\n\\n\" );\n\tprintf( \"Usage:\\n\" );\n\tprintf( \"  thd [switches] [devices]\\n\\n\" );\n\tprintf( \"Command line switches:\\n\" );\n\tprintf( \"  --help             Display this help message\\n\" );\n\tprintf( \"  --daemon           Run as daemon process\\n\" );\n\tprintf( \"  --dump             Dump events to console\\n\" );\n\tprintf( \"  --listevents       Print a list of all known events\\n\" );\n\tprintf( \"  --triggers <file>  Load trigger definitions from <file>\\n\" );\n\tprintf( \"  --socket <socket>  Read commands from socket\\n\" );\n\tprintf( \"  --ignore <event>   Ignore key events with name <event>\\n\" );\n\tprintf( \"  --normalize        Normalize relative movement events\\n\" );\n\tprintf( \"  --user <name>      Drop privileges to <name> after opening devices\\n\" );\n\tprintf( \"  --deviceglob <p>   Open device files matching pattern <p>\\n\" );\n}\n\nstatic void list_event_table(int type, int max) {\n\tint n = 0;\n\tfor (n = 0; n <= max; n++) {\n\t\tconst char *name = lookup_event_name_i(type, n);\n\t\tif (name) {\n\t\t\tprintf(\"%s\\n\", name);\n\t\t}\n\t}\n}\n\nstatic void list_events(void) {\n\tlist_event_table(EV_KEY, KEY_MAX);\n\tlist_event_table(EV_SW, SW_MAX);\n\tlist_event_table(EV_REL, REL_MAX);\n\tlist_event_table(EV_ABS, REL_MAX);\n}\n\nvoid cleanup(void) {\n\tclose_uinput();\n\tif (cmd_file) {\n\t\tif (cmd_fd != -1) {\n\t\t\tclose( cmd_fd );\n\t\t}\n\t\tunlink(cmd_file);\n\t\tcmd_fd = -1;\n\t}\n\tclear_devices();\n\tif (pidfile) {\n\t\tunlink(pidfile);\n\t}\n}\n\nstatic int reload_triggerfile(void) {\n\tclear_triggers();\n\tif (triggerfile) {\n\t\tint err = read_triggers(triggerfile);\n\t\tif (err) {\n\t\t\tfprintf(stderr, \"Error loading triggerfile '%s'\\n\", triggerfile);\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}\n\nstatic void handle_signal(int sig) {\n\tswitch (sig) {\n\t\tcase SIGINT:\n\t\tcase SIGTERM:\n\t\t\texiting = 1;\n\t\t\tbreak;\n\t\tcase SIGHUP:\n\t\t\treload_conf = 1;\n\t\t\tbreak;\n\t}\n}\n\nint start_readers(int argc, char *argv[], int start, char *dev_glob) {\n\tif (argc-start < 1 && cmd_file == NULL && dev_glob == NULL) {\n\t\tfprintf(stderr, \"No input device files or command pipe specified.\\n\");\n\t\treturn 1;\n\t}\n\t/* open command pipe */\n\tif (cmd_file) {\n\t\tcmd_fd = bind_cmdsocket(cmd_file);\n\t\tif (cmd_fd < 0) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t/* add every device file supplied on command line */\n\tint i;\n\tfor (i=start; i<argc; i++) {\n\t\tchar *dev = argv[i];\n\t\t/* TODO\n\t\t * we should provide a method to\n\t\t * optionally grab the device or\n\t\t * assign a tag\n\t\t */\n\t\tint grab_dev = 0;\n\t\tchar *tag_dev = NULL;\n\t\tadd_device( dev, -1, grab_dev, tag_dev );\n\t}\n\t/* check device glob */\n\tif (dev_glob) {\n\t\tglob_t globbuf;\n\t\tglob(dev_glob, GLOB_NOSORT, NULL, &globbuf);\n\t\tfor (i=0; i<globbuf.gl_pathc; i++) {\n\t\t\tint grab_dev = 0;\n\t\t\tchar *tag_dev = NULL;\n\t\t\tadd_device(globbuf.gl_pathv[i], -1, grab_dev, tag_dev);\n\t\t}\n\t}\n\tif (run_as_daemon) {\n\t\tint err = daemon(0,0);\n\t\tif (err) {\n\t\t\tperror(\"daemon()\");\n\t\t}\n\t}\n\tif (pidfile) {\n\t\twrite_pidfile( pidfile );\n\t}\n\t/* drop privileges */\n\tif (user) {\n\t\tstruct passwd *pw = getpwnam(user);\n\t\tif (pw) {\n\t\t\tint uid = pw->pw_uid;\n\t\t\tint gid = pw->pw_gid;\n\t\t\tif ( initgroups(user, gid) ) {\n\t\t\t\tperror(\"initgroups\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif ( setregid( gid, gid ) ) {\n\t\t\t\tperror(\"setregid\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif ( setreuid( uid, uid ) ) {\n\t\t\t\tperror(\"setreuid\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unable to lookup user '%s'.\\n\", user);\n\t\t\treturn 1;\n\t\t}\n\t}\n\n#ifdef HAVE_SYSTEMD\n\tsd_notify(0, \"READY=1\");\n#endif\n\n\tprocess_events();\n\n\treturn 0;\n}\n\nint main(int argc, char *argv[]) {\n\tsignal(SIGCHLD, SIG_IGN);\n\tchar *dev_glob = NULL;\n\tint option_index = 0;\n\tint c;\n\twhile (1) {\n\t\tc = getopt_long (argc, argv, \"t:s:dhpni:u:g:\", long_options, &option_index);\n\t\tif (c == -1) {\n\t\t\tbreak;\n\t\t}\n\t\tswitch (c) {\n\t\t\tcase 0:\n\t\t\t\tif (long_options[option_index].flag != 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprintf (\"option %s\", long_options[option_index].name);\n\t\t\t\tif (optarg)\n\t\t\t\t\tprintf (\" with arg %s\", optarg);\n\t\t\t\tprintf (\"\\n\");\n\t\t\t\tbreak;\n\t\t\tcase 'd': /* short for --dump */\n\t\t\t\tdump_events = 1;\n\t\t\t\tbreak;\n\t\t\tcase 'p': /* short for --pidfile */\n\t\t\t\tpidfile = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\ttriggerfile = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tcmd_file = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\tif ( lookup_event_type(optarg) == EV_KEY ) {\n\t\t\t\t\tignore_key( lookup_event_code(optarg), &ignored_keys );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\t\tshow_help();\n\t\t\t\treturn 0;\n\t\t\tcase 'l':\n\t\t\t\tlist_events();\n\t\t\t\treturn 0;\n\t\t\tcase 'u':\n\t\t\t\tuser = optarg;\n\t\t\t\tbreak;\n\t\t\tcase '<':\n\t\t\t\tuinput_dev = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'g':\n\t\t\t\tdev_glob = optarg;\n\t\t\t\tbreak;\n\t\t\tcase '?':\n\t\t\tdefault:\n\t\t\t\treturn 1;\n\t\t}\n\t}\n\t/* load config file */\n\tif (reload_triggerfile() != 0) {\n\t\treturn 1;\n\t}\n\t/* init keystate holder */\n\tinit_keystate_holder(&keystate);\n\t/* set initial trigger mode */\n\tchange_trigger_mode(\"\");\n\t/* open uinput if requested */\n\tif (uinput_dev != NULL && open_uinput(uinput_dev) == -1) {\n\t\tfprintf(stderr, \"Error setting up uinput support\\n\");\n\t\treturn 1;\n\t}\n\t/* install signal handler */\n\tstruct sigaction handler;\n\thandler.sa_handler = handle_signal;\n\tsigfillset(&handler.sa_mask);\n\thandler.sa_flags=0;\n\tsigaction(SIGINT,&handler,0);\n\tsigaction(SIGTERM,&handler,0);\n\tsigaction(SIGHUP,&handler,0);\n\n\tint status = start_readers(argc, argv, optind, dev_glob);\n\tcleanup();\n\treturn status;\n}\n\n"
  },
  {
    "path": "thd.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\nvoid cleanup(void);\n"
  },
  {
    "path": "thd.pod",
    "content": "=pod\n\n=head1 NAME\n\nthd -- triggerhappy global hotkey daemon\n\n=head1 SYNOPSIS\n\nB<thd> [B<--help>] [B<--user> I<name>] [B<--listevents>] [B<--dump>] [B<--socket> I<socket>] [B<--triggers> I<config>] [B<--daemon>] [B<--pidfile> I<file>] [B<--uinput> I<device>][B<--ignore> I<event>] [B<--deviceglob> I<pattern>] [I<devices...>]\n\n=head1 DESCRIPTION\n\nTriggerhappy is a hotkey daemon that operates on a system wide scale. It watches all configured input devices\nfor key, switch or button events and can launch arbitrary commands specified by the administrator. In contrast\nto hotkey services provided by desktop environments, Triggerhappy is especially suited to hardware related switches\nlike volume or wifi control; it works independently from a specific user being logged in and is also suitable for embedded systems that do not a graphical user interface.\n\n=head1 OPTIONS\n\n=over\n\n=item B<--help>\n\nShows usage instructions\n\n=item B<--listevents>\n\nPrints a list of all known event names.\n\n=item B<--triggers> F<conf>\n\nRead trigger definitions from F<conf>, which can either be a file or a directory. If a directory is specified, all its files matching the pattern *.conf are loaded.\n\n=item B<--dump>\n\nDump all recognized events to STDOUT. This can also be utilized to create a skeleton trigger configuration by redirecting the printed configuration lines to a configuration file, adding the desired command and activating the generated line by removing the comment mark \"#\" at its beginning:\n\n  thd --dump /dev/input/event* | grep ^# > /etc/triggerhappy/triggers.d/skeleton.conf\n\n=item B<--socket> F<file>\n\nOpen a unix domain socket at F<file>; this socket can be used to send commands to the running daemon (by using the program L<th-cmd>), e.g. for adding or removing devices.\n\n=item B<--daemon>\n\nRun as a background daemon and detach from the terminal.\n\n=item B<--pidfile> F<file>\n\nWrite PID to F<file>.\n\n=item B<--uinput> F<device>\n\nOpen uinput file (probably F</dev/input/uinput>) to generate synthetic events.\n\n=item B<--ignore> I<eventname>\n\nIgnore key and switch event labeled I<eventname>. This can be used to suppress the FN key on some notebooks which only generates events sometimes and might screw up key combinations.\n\n=item B<--normalize>\n\nNormalize REL and ABS events. If this option is enabled, the values of axis movement events are mapped to the three values -1, 0 and 1, depending on the sign of the value reported by the kernel.\n\n=item B<--user> I<name>\n\nChange to user id I<name> after opening files. This usually prevents thd from opening additional input devices, unless they are opened by the th-cmd program and their file descriptor are passed to the daemon.\n\n=item B<--deviceglob> I<pattern>\n\nOpen device files matching the glob I<pattern>.\n\n=back\n\nAdditional command line arguments are considered filenames of input devices.\n\n=head1 CONFIGURATION\n\n\n=head2 Configuring event handlers\n\nThe hotkey bindings used by Triggerhappy are set in the configuration file specified by B<--triggers>. Each line consists of three segments:\nThe symbolic name of the key or event name to react on, the value carried by the expected event, and of course the command to be launched.\n\nThe event names can be identified by operating the desired key or switch while running the triggerhappy daemon with the option B<--dump>.\n\nKey events carry the value I<1> for a key being pressed and transmit the payload I<0> when it is released; holding the key down constantly yields events with a value of I<2>.\n\nThe command can include any number of arguments. Please include the full path to avoid trouble through different $PATH settings for the daemon and your interactive session.\n\nThe three fields are separated by an arbitrary number of whitespaces, while anything behind a # character is ignored and considered a comment.\n\n=head1 EXAMPLE\n\n=head2 Starting the daemon\n\nB<thd --dump /dev/input/event*>\n\nDump all events processable by thd to the console; this is useful to find out the correct event name for a specific key.\n\nB<thd --triggers /etc/triggerhappy/triggers.d/ /dev/input/event*>\n\nRead from all currently connected input devices and process events according to the files in F</etc/triggerhappy/triggers.d/>.\n\nB<thd --triggers /etc/triggerhappy/triggers.conf --socket /var/run/thd.socket>\n\nDo not open any input devices yet, but bind the socket F</var/run/thd.socket> for L<th-cmd> to connect to.\n\n=head2 Configuration files\n\nAny number of event handlers can be placed in the configuration file:\n\n    # /etc/triggerhappy/triggers.d/suspend.conf\n    #\n    # Suspend the system\n    KEY_SLEEP                   1       /usr/sbin/hibernate-ram\n    KEY_SLEEP+KEY_LEFTSHIFT     1       /usr/sbin/hibernate-disk\n\n    # /etc/triggerhappy/triggers.d/audio.conf\n    # Change mixer volume when pressing the appropriate keys (or holding them)\n    KEY_VOLUMEUP    1      /usr/bin/amixer set Master 5%+\n    KEY_VOLUMEUP    2      /usr/bin/amixer set Master 5%+\n    KEY_VOLUMEDOWN  1      /usr/bin/amixer set Master 5%-\n    KEY_VOLUMEDOWN  2      /usr/bin/amixer set Master 5%-\n\nIn more complex situations, triggerhappy can provide multiple modes that map a\nsingle event to different keys; triggers are bound to a specific mode by appending\nits name to the event name:\n\n    KEY_KPPLUS@media\t1\t/usr/bin/mpc next\n    KEY_KPMINUS@media\t1\t/usr/bin/mpc prev\n\nThese two lines will only cause mpc to be called if the triggerhappy daemon is in\n\"media\" mode. Changing the mode can be achieved by placing a special trigger inside\nthe configuration:\n\n    KEY_F12@\t\t1\t@media\n    KEY_F12@media\t1\t@\n\nThese two lines make the F12 key toggle between the (nameless) default mode and the\nnewly defined media mode.\n\nTriggers with \"@\" appended are only executed if the specified mode is active; all other\ntriggers are enabled in every mode.\n\nWhen launched with the option B<--uinput>, triggerhappy can be used to generate\nsynthetic events. A virtual input device is created which emits specified key\npresses once a special trigger is reached:\n\n    KEY_KPASTERISK\t1\t<KEY_VOLUMEDOWN\n\nBy prepending a keycode with the special character '<', other applications will\nreceive a press and release of the corresponding key. This is especially useful\nto remap or mirror events generated by devices exclusively serviced by the\ntriggerhappy daemon.\n\nIt is possible to create handlers that only react to specific devices: to achieve\nsuch behaviour, add the input device using B<th-cmd> and supply it with a tag; this\ntag can then be used to limit the scope of a trigger to this device:\n\n    <remote>KEY_ENTER\t1\t/usr/bin/mpc stop\n\nDefining the hotkey in this way will only trigger the handler if the event is received\nfrom a device tagged \"remote\".\n\n=head1 AUTHOR\n\nStefan Tomanek E<lt>stefan.tomanek+th@wertarbyte.deE<gt>\n\n"
  },
  {
    "path": "trigger.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <string.h>\n#include <ctype.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include \"eventnames.h\"\n#include \"keystate.h\"\n#include \"devices.h\"\n#include \"trigger.h\"\n#include \"uinput.h\"\n\n#include \"triggerparser.h\"\n\nstatic trigger *trigger_list = NULL;\n\nstatic int triggers_are_enabled = 1;\n\nstatic char *trigger_mode = NULL;\n\nchar *get_trigger_mode() {\n\treturn trigger_mode;\n}\n\nvoid change_trigger_mode(const char *mode) {\n\tif (trigger_mode != NULL) {\n\t\tfree(trigger_mode);\n\t\t/* suppress the message on the first change to default mode */\n\t\tfprintf(stderr, \"Changing trigger mode to <%s>\\n\", mode);\n\t}\n\ttrigger_mode = strdup(mode);\n}\n\nvoid triggers_enabled( int status ) {\n\ttriggers_are_enabled = status;\n}\n\nvoid append_trigger(trigger *t) {\n\ttrigger **p = &trigger_list;\n\twhile (*p != NULL) {\n\t\tp = &( (*p)->next );\n\t}\n\t*p = t;\n}\n\nstatic int read_triggerfile(const char *filename) {\n\tFILE *conf;\n\tsize_t len = 0;\n\tchar *line = NULL;\n\tssize_t read;\n\n\tif(!filename)\n\t\treturn 2;\n\n\tconf = fopen(filename, \"r\");\n\tif (conf == NULL) {\n\t\treturn 1;\n\t}\n\twhile ((read = getline(&line, &len, conf)) != -1) {\n\t\tchar *copy = strdup(line);\n\t\tif (!copy) {\n\t\t\tfprintf(stderr, \"Error allocating memory for trigger parsing!\\n\");\n\t\t\tbreak;\n\t\t}\n\t\ttrigger *t = parse_trigger(copy);\n\t\tif (t) {\n\t\t\tappend_trigger(t);\n\t\t} else if (strlen(copy) > 0) {\n\t\t\t/* perhaps it was just an empty line */\n\t\t\tfprintf(stderr, \"Unable to parse trigger line: %s\\n\", line);\n\t\t}\n\t\tfree(copy);\n\t}\n\tfclose(conf);\n\tconf=NULL;\n\tfree(line);\n\tline=NULL;\n\treturn 0;\n}\n\nstatic int accept_triggerfile(const struct dirent *entry) {\n\tconst char *suffix = \".conf\";\n\tconst char *name = entry->d_name;\n\tchar *end = strstr( name, suffix );\n\tif ( end && end[ strlen(suffix) ] == '\\0' ) {\n\t\treturn 1;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nint read_triggers(const char *path) {\n\t/* check whether filename is a directory */\n\tstruct stat sb;\n\tif (stat(path, &sb) == -1) {\n\t\tperror(\"stat\");\n\t\treturn 1;\n\t}\n\tif (S_ISDIR(sb.st_mode)) {\n\t\t/* dive into it */\n\t\tstruct dirent **namelist;\n\t\tint n;\n\t\tn = scandir(path, &namelist, accept_triggerfile, alphasort);\n\t\tif ( n < 0) {\n\t\t\tperror(\"scandir\");\n\t\t\treturn 1;\n\t\t} else {\n\t\t\twhile (n--) {\n\t\t\t\tstruct stat sf;\n\t\t\t\tchar *file = namelist[n]->d_name;\n\t\t\t\tchar *sep = \"/\";\n\t\t\t\tchar fpath[strlen(path)+strlen(sep)+strlen(file) + 1];\n\t\t\t\tstrcpy(fpath, path);\n\t\t\t\tstrcat(fpath, sep);\n\t\t\t\tstrcat(fpath, file);\n\t\t\t\tif (stat(fpath, &sf) == -1) {\n\t\t\t\t\tperror(\"stat\");\n\t\t\t\t}\n\t\t\t\tif (S_ISREG(sf.st_mode)) {\n\t\t\t\t\tread_triggerfile(fpath);\n\t\t\t\t}\n\t\t\t\tfree(namelist[n]);\n\t\t\t}\n\t\t\tfree(namelist);\n\t\t\treturn 0;\n\t\t}\n\t} else {\n\t\treturn read_triggerfile( path );\n\t}\n}\n\nstatic int devtag_equal(const char *d_tag, const char *t_tag) {\n\tif (strlen(t_tag) == 0) {\n\t\treturn 1;\n\t}\n\tif (strcmp(t_tag, d_tag) == 0) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic int mods_equal(keystate_holder ksh, trigger_modifier tm, int ignore_key) {\n\tint n = 0;\n\twhile ( n < TRIGGER_MODIFIERS_MAX ) {\n\t\tint code = tm[n]; /* this key must be pressed */\n\t\tif (code < 0) {\n\t\t\tbreak;\n\t\t} else if (ksh[code] <= 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tn++;\n\t}\n\t/* Now n is equal to the number of modifiers needed\n\t * we can check whether any additional keys are pressed\n\t * by counting the number of pressed keys instead of having\n\t * to cross-examine every key against the modifier list\n\t */\n\tint x;\n\tfor (x=0; x<=KEY_MAX; x++) {\n\t\tif (x != ignore_key && ksh[x] > 0) {\n\t\t\tn--;\n\t\t}\n\t}\n\t/* if n is zero, we have the exact number of needed modifiers pressed */\n\treturn (n == 0);\n}\n\nstatic int correct_mode( const char *tmode ) {\n\t/* not mode specified, valid in every mode */\n\treturn (tmode == NULL) || (strcmp( get_trigger_mode(), tmode ) == 0);\n}\n\nvoid run_triggers(int type, int code, int value, keystate_holder ksh, device *dev) {\n\tif (triggers_are_enabled == 0) {\n\t\treturn;\n\t}\n\tif (dev && dev->tag) {\n\t}\n\ttrigger *et = trigger_list;\n\twhile (et != NULL) {\n\t\tif ( type  == et->type &&\n\t\t     code  == et->code &&\n\t\t     value == et->value &&\n\t\t     et->action &&\n\t\t     correct_mode( et->mode ) &&\n\t\t     devtag_equal(&(dev->tag[0]), &(et->devtag[0])) &&\n\t\t     mods_equal(ksh, et->modifiers, (type==EV_KEY?code:-1) )) {\n\t\t\tfprintf(stderr, \"Executing trigger action: %s\\n\", et->action);\n\t\t\t/* switch trigger mode or execute program? */\n\t\t\tif (et->action[0] == '@') {\n\t\t\t\tchange_trigger_mode( &(et->action)[1] );\n\t\t\t\t/* we now stop checking for additional triggers\n\t\t\t\t * to avoid changing back to the original mode\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t} else if (et->action[0] == '<' ) {\n\t\t\t\tchar *keyname = &(et->action[1]);\n\t\t\t\tfprintf(stderr, \"Sending event: %s\\n\", keyname);\n\t\t\t\tint type = lookup_event_type( keyname );\n\t\t\t\tint code = lookup_event_code( keyname );\n\t\t\t\tif (type && code) {\n\t\t\t\t\tsend_event( type, code, 1 );\n\t\t\t\t\tsend_event( type, code, 0 );\n\t\t\t\t\tsend_event( EV_SYN, 0, 0 );\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tint pid = fork();\n\t\t\t\tif (pid == 0 ) {\n\t\t\t\t\t/* adjust environment */\n\t\t\t\t\tsetenv( \"TH_DEVICE\", dev->devname, 1 );\n\t\t\t\t\tsetenv( \"TH_KEYSTATE\", get_keystate(ksh), 1 );\n\t\t\t\t\tconst char *en = lookup_event_name_i( et->type, et->code );\n\t\t\t\t\tsetenv( \"TH_EVENT\", en, 1 );\n\t\t\t\t\tchar ev[8];\n\t\t\t\t\tsprintf( &(ev[0]), \"%d\", et->value );\n\t\t\t\t\tsetenv( \"TH_VALUE\", &(ev[0]), 1 );\n\t\t\t\t\t/* default SIGCHLD is not automatically\n\t\t\t\t\t   restored and most applications would\n\t\t\t\t\t   fail if this signal is ignored */\n\t\t\t\t\tsignal(SIGCHLD, SIG_DFL);\n\t\t\t\t\tsystem(et->action);\n\t\t\t\t\texit(0);\n\t\t\t\t} else if (pid < 0) {\n\t\t\t\t\tfprintf(stderr, \"Unable to fork!\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tet = et->next;\n\t}\n}\n\nint count_triggers( trigger **list ) {\n\tint n = 0;\n\tif(!list)\n\t\treturn 0;\n\ttrigger *p = *list;\n\twhile ( p != NULL ) {\n\t\tn++;\n\t\tp = p->next;\n\t}\n\treturn n;\n}\n\nvoid clear_triggers() {\n\ttrigger *p = trigger_list;\n\twhile (p != NULL) {\n\t\ttrigger *next = p->next;\n\t\tfree(p->action);\n\t\tfree(p->mode);\n\t\tfree(p);\n\t\tp = next;\n\t}\n\ttrigger_list = NULL;\n}\n"
  },
  {
    "path": "trigger.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include \"devtag.h\"\n#define TRIGGER_MODIFIERS_MAX 5\n\ntypedef int trigger_modifier[TRIGGER_MODIFIERS_MAX];\n\ntypedef struct trigger {\n\tint type;\n\tint code;\n\tint value;\n\ttrigger_modifier modifiers;\n\tchar *mode;\n\tchar devtag[TH_DEVICE_TAG_LENGTH];\n\tchar *action;\n\tstruct trigger *next;\n} trigger;\n\ntrigger* parse_trigger(char* line);\nvoid append_trigger(trigger *t);\nint read_triggers(const char *filename);\nvoid run_triggers(int type, int code, int value, keystate_holder ksh, device *dev);\nvoid clear_triggers();\n\nvoid triggers_enabled( int status );\n\nvoid change_trigger_mode( const char *tmode );\n"
  },
  {
    "path": "triggerhappy.conf.examples",
    "content": "# adjust volume\nKEY_VOLUMEUP\t\t\t1\t/usr/bin/amixer set Master 5%+\nKEY_VOLUMEUP+KEY_LEFTSHIFT\t1\t/usr/bin/amixer set Master 15%+ # with modifier\nKEY_VOLUMEUP\t\t\t2\t/usr/bin/amixer set Master 5%+ # even while holding\nKEY_VOLUMEDOWN\t\t\t1\t/usr/bin/amixer set Master 5%-\nKEY_VOLUMEDOWN+KEY_LEFTSHIFT\t1\t/usr/bin/amixer set Master 15%-\nKEY_VOLUMEDOWN\t\t\t2\t/usr/bin/amixer set Master 5%-\n# only trigger commands when in \"media\" mode\nKEY_KPPLUS@media\t\t1\t/usr/bin/mpc next # next song\nKEY_KPMINUS@media\t\t1\t/usr/bin/mpc prev # next song\n# only used if in the nameless default mode\nKEY_F12@\t\t\t1\t@media # switch to media mode\nKEY_F12@media\t\t\t1\t@ # switch back to nameless default mode\nKEY_KPASTERISK\t\t\t1\t<KEY_VOLUMEDOWN # emit a synthetic key event through uinput\n# enable trigger only on devices tagged \"sys\"\n<sys>KEY_F11\t\t\t1\tid\n"
  },
  {
    "path": "triggerparser.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include \"eventnames.h\"\n#include \"keystate.h\"\n#include \"devices.h\"\n#include \"trigger.h\"\n#include \"triggerparser.h\"\n\nstatic int parse_evdef(char *evdef, trigger *t) {\n\t/* first we split the mode (if present) */\n\tchar *mode = strchr(evdef, '@');\n\tif (mode) {\n\t\t*mode = '\\0';\n\t\tmode++;\n\t}\n\t/* place a copy of the mode string or NULL in the struct */\n\tt->mode = (mode ? strdup(mode) : NULL);\n\n\t/* The evdef event now might still contain a device tag enclosed in < > */\n\tt->devtag[0] = '\\0';\n\tchar *tmp = strchr(evdef, '>');\n\tif (tmp && evdef[0] == '<') {\n\t\t*tmp = '\\0';\n\t\tstrncpy(t->devtag, &evdef[1], TH_DEVICE_TAG_LENGTH);\n\t\tt->devtag[TH_DEVICE_TAG_LENGTH-1] = '\\0';\n\t\tevdef = tmp+1; /* point evdef to the beginning of the event */\n\t}\n\n\t/* now we can start to separate the triggering event from the modifiers */\n\tchar *sptr = NULL;\n\tchar *s_trigger  = strtok_r(evdef, \"+\", &sptr);\n\n\tint n = 0;\n\twhile (n < TRIGGER_MODIFIERS_MAX) {\n\t\tchar *s_mod = strtok_r(NULL, \"+\", &sptr);\n\t\tif (s_mod == NULL) {\n\t\t\tt->modifiers[n] = -1;\n\t\t} else {\n\t\t\tint type = lookup_event_type(s_mod);\n\t\t\tint c = lookup_event_code(s_mod);\n\t\t\tif (type == EV_KEY && c >= 0) {\n\t\t\t\tt->modifiers[n] = c;\n\t\t\t} else {\n\t\t\t\t/* we cannot process this key code */\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\tn++;\n\t}\n\n\tint type = lookup_event_type( s_trigger );\n\tint code = lookup_event_code( s_trigger );\n\n\tif (type < 0 || code < 0) {\n\t\treturn 1;\n\t}\n\tt->type = type;\n\tt->code = code;\n\n\treturn 0;\n}\n\ntrigger* parse_trigger(char* line) {\n\t/* ignore everything behind # */\n\tchar *comment = strchr(line, '#');\n\tif ( comment != NULL ) {\n\t\t*comment = '\\0';\n\t}\n\n\t/* no we must have at least 3 tokens left */\n\tchar *delim = \" \\t\\n\";\n\tchar *sptr = NULL;\n\t/* event definition including modifiers and daemon mode */\n\tchar *s_evdef  = strtok_r(line, delim, &sptr);\n\t/* value of the event (0, 1, 2) */\n\tchar *s_value  = strtok_r(NULL, delim, &sptr);\n\t/* the action that should take place filling the rest of the line */\n\tchar *s_action = strtok_r(NULL, \"\", &sptr);\n\n\t/* if we do not have 3 tokens, we can abort */\n\tif (! (s_evdef && s_value && s_action)) {\n\t\treturn NULL;\n\t}\n\ttrigger *t = malloc( sizeof(trigger) );\n\tif (! t) {\n\t\tfprintf(stderr, \"Unable to allocate memory for trigger definition!\\n\");\n\t\treturn NULL;\n\t}\n\tmemset( t, 0, sizeof(*t) );\n\tt->next = NULL;\n\n\tt->value = atoi(s_value);\n\n\tint err = parse_evdef( s_evdef, t );\n\tif (!err) {\n\t\t/* remove trailing whitespaces from the end of the command line */\n\t\tchar *end = s_action + strlen(s_action) - 1;\n\t\twhile (end >= s_action && (isspace(*end) || *end == '\\n')) {\n\t\t\tend --;\n\t\t}\n\t\t*(end+1) = '\\0';\n\t\t/* remove leading whitespaces as well */\n\t\twhile (isspace(*s_action)) {\n\t\t\ts_action++;\n\t\t}\n\t\t/* now copy the strings (mode is already copied in parse_evdef) */\n\t\tt->action = strdup(s_action);\n\t} else {\n\t\t/* free the allocated memory */\n\t\tfree(t->mode);\n\t\tfree(t->action);\n\t\tfree(t);\n\t\tt = NULL;\n\t}\n\treturn t;\n}\n\n"
  },
  {
    "path": "triggerparser.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\ntrigger* parse_trigger(char* line);\n"
  },
  {
    "path": "udev/triggerhappy-udev.rules",
    "content": "## open new input devices and pass the file descriptor to the triggerhappy daemon\nACTION==\"add\", SUBSYSTEM==\"input\", \\\n\tATTRS{name}!=\"triggerhappy\", \\\n\tRUN+=\"/usr/sbin/th-cmd --socket /var/run/thd.socket --passfd --udev\"\n## add device exclusively\n#ACTION==\"add\", SUBSYSTEM==\"input\", \\\n#\tATTRS{name}==\"Nintendo Wiimote\", \\\n#\tRUN+=\"/usr/sbin/th-cmd --socket /var/run/thd.socket --passfd --udev --grab\"\n"
  },
  {
    "path": "uinput.c",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\n#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <linux/input.h>\n#include <linux/uinput.h>\n\n#include \"uinput.h\"\n\nstatic int uinput_fd = -1;\n\nint open_uinput(const char *path) {\n\tclose_uinput();\n\tstruct uinput_user_dev device;\n\tuinput_fd = open(path, O_WRONLY);\n\tif (!uinput_fd) {\n\t\treturn -1;\n\t}\n\tmemset(&device, 0, sizeof device);\n\tstrcpy(device.name,\"triggerhappy\");\n\tdevice.id.bustype = BUS_USB;\n\tdevice.id.vendor = 1;\n\tdevice.id.product = 1;\n\tdevice.id.version = 1;\n\tif (write(uinput_fd,&device,sizeof(device)) != sizeof(device)) {\n\t\tclose_uinput();\n\t\treturn -1;\n\t}\n\n\tif (ioctl(uinput_fd,UI_SET_EVBIT,EV_KEY) < 0) {\n\t\tclose_uinput();\n\t\treturn -1;\n\t}\n\n\t/* we can generate _any_ key event */\n\tint i;\n\tfor (i=0; i<KEY_MAX && uinput_fd; i++) {\n\t\tif (ioctl(uinput_fd, UI_SET_KEYBIT, i) < 0) {\n\t\t\tclose_uinput();\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (ioctl(uinput_fd, UI_DEV_CREATE) < 0) {\n\t\tclose_uinput();\n\t\treturn -1;\n\t}\n\n\treturn uinput_fd;\n}\n\nvoid close_uinput() {\n\tif (uinput_fd >= 0) {\n\t\tclose(uinput_fd);\n\t\tuinput_fd = -1;\n\t}\n}\n\nint send_event(const int type, const int code, const int value) {\n\tif (!uinput_fd) {\n\t\treturn -1;\n\t}\n\tstruct input_event event;\n\tmemset(&event, 0, sizeof event);\n\tevent.type = type;\n\tevent.code = code;\n\tevent.value = value;\n\tif (write(uinput_fd, &event, sizeof(event)) != sizeof(event)) {\n\t\tfprintf(stderr, \"Error on send_event\\n\");\n\t\treturn -1;\n\t}\n\treturn 0;\n}\n\n"
  },
  {
    "path": "uinput.h",
    "content": "/* Copyright 2010 Stefan Tomanek <stefan.tomanek+th@wertarbyte.de>\n * You have permission to copy, modify, and redistribute under the\n * terms of the GPLv3 or any later version.\n * For full license terms, see COPYING.\n */\n\nint open_uinput(const char *path);\nvoid close_uinput();\nint send_event(const int type, const int code, const int value);\n"
  },
  {
    "path": "version.inc",
    "content": "0.5.0\n"
  }
]