├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── bin
└── xswitcher
├── embeddedConfig
└── config.go
├── exec
└── exec.go
├── gnome3
├── switch.gnome
└── xswitcher.conf
├── go.mod
├── go.sum
├── scancodes
├── LICENSE
├── README.md
├── scancodes.go
├── scancodes_test.go
├── table.go
└── table_test.go
├── src
├── C
│ └── x11.c
├── keybd_event
│ ├── LICENSE
│ ├── README.md
│ ├── go.mod
│ ├── keybd_darwin.go
│ ├── keybd_event.go
│ ├── keybd_event_test.go
│ ├── keybd_linux.go
│ ├── keybd_linux_export.go
│ ├── keybd_windows.go
│ └── keyboard.png
├── keys.go
├── test.pl
└── xswitcher.go
└── xswitcher.conf
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Code of Conduct
2 |
3 | This project adheres to No Code of Conduct. We are all adults. We accept anyone's contributions. Nothing else matters.
4 |
5 | For more information please visit the [No Code of Conduct](https://github.com/domgetter/NCoC) homepage.
6 |
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # X language switcher v1.0 ("xswitcher")
2 | Xswitcher is the fully customizable low-level keyboard helper for X.Org-based Linux desktops.
3 | It consists of two main parts: low-level keylogger and the virtual keyboard.
4 | On each key up/down event, xswitcher checks the last events chain against configured regex-based patterns.
5 | If one matches, xswitcher triggers the associated action. Action chains can be joined from simple actions.
6 | Look at TOML-based explained config file "xswitcher.conf" for further details.
7 |
8 | ## Retype
9 | One of the most powerful actions of xswitcher is to retype the collected event buffer
10 | after switching the language. Because of it's low-level nature, it may know nothing about layout details.
11 | So, xswitcher does nothing strange, in comparison with punto switcher on windows.
12 | It just sends a number of BackSpaces to wipe the last input, then calls language switcher
13 | (internal, via X API, or external, via call of the configured program), an then retypes the same
14 | keyboard events by means of virtual keyboard.
15 |
16 | ## Gnome is the pain
17 | Note that the users of actual gnome-based shells can't use the XOrg embedded language switcher.
18 | Due to the gnome built-in bug, X language API is broken by gnome since 2011.
19 | However, there's the workaround. Look under the "gnome3" subfolder for customized config file and the simple helper "switch.gnome".
20 | The helper header contains the brief instruction on how to deal with the https://github.com/lyokha/g3kb-switch.git
21 |
22 | ## Precompiled xswitcher for the beginners
23 | The statically compiled binary lays under "bin" folder.
24 | The unexperienced users *(except of those who used gnome-based interfaces, e.g. ubuntu)* can just download this binary.
25 | Then put it under e.g. "/usr/local/bin" path and make it executable:
26 |
27 | sudo chown root:root /usr/local/bin/xswitcher
28 | sudo chmod +xs /usr/local/bin/xswitcher
29 |
30 | Note the sticky bit "+s" in this example. Being the low-level keylogger, xswitcher needs the access to "/dev/input/" devices.
31 | Someone can make xswitcher slightly less dangerous by adding the privilege-separated code.
32 | Or You yourself can try add your GUI user to "input" group (but I'm not sure it's enough to attach the virtual keyboard).
33 | All improvements are welcome.
34 |
35 | Also note that, being an honest keylogger by nature, xswitcher can be of course configured to do something strange.
36 | E.g. you can configure it to email all the input to e.g. "fbi@usa.gov". Nobody bans.
37 |
38 | ## CLI
39 | There are a number of helpful CLI flags:
40 |
41 | xswitcher -h
42 | Usage of :
43 | -c, --conf string Non-default config location (default "/etc/xswitcher/xswitcher.conf")
44 | -d, --debug Debug log level
45 | -t, --test Only output all key events to STDERR. No actions.
46 | -v, --verbose Increase log level to NOTICE
47 |
48 | Use "-v" or even "-d" to debug when You implements any config changes.
49 | Use "-t" to collect the keyboard events string to construct Your custom actions.
50 |
51 | ## Respawn
52 | This version of xswitcher do the scan of input devices only once (on it's launch).
53 | But there is the internal "respawn" action in case You connects new keyboard/mouse.
54 | By default, the long press of "Scroll lock" triggers "respawn". (Respawn does the complete self-restart).
55 |
56 | ## How to build.
57 | You must install (libX11-devel | libx11-dev) + (libXmu-devel | libxmu-dev) packages for X bindings.
58 | * The package name may, of course, be different in Your distro.
59 | And, of course, you must have the working go environment.
60 | Obtain dependencies:
61 |
62 | go get "github.com/spf13/pflag" # CLI keys
63 | go get "github.com/pelletier/go-toml" # Actual TOML parser
64 | go get "github.com/gvalkov/golang-evdev" # Keyboard and mouse events
65 | go get "github.com/micmonay/keybd_event" # Virtual keyboard !!(must be improved to deal with complex input)
66 | go get "github.com/kballard/go-shellquote" # joining/splitting strings using sh's word-splitting rules
67 |
68 | Unfortunately my pull request https://github.com/micmonay/keybd_event/pull/32 still stays unaccepted.
69 | You must put "src/keybd_event/keybd_linux_export.go" inside "keybd_event" sources for successful assembly.
70 | You must also move "embeddedConfig" and "exec" internal libraries under Your "src/xswitcher" to satisfy
71 |
72 | import (
73 | "xswitcher/embeddedConfig"
74 | "xswitcher/exec"
75 | )
76 | declaration.
77 |
78 | Now You are ready to build. I do the portable static build using the string below:
79 |
80 | go build -o xswitcher -ldflags "-s -w" --tags static_all src/*.go && chmod +xs xswitcher
81 |
82 | Put the config to "/etc/xswitcher/xswitcher.conf" (or just use embedded one)
83 | and install xswitcher executable under "/usr/local/bin/" or where You prefer.
84 |
85 | Make it executable, e.g. "chmod +xs /usr/local/bin/xswitcher", configure the autostart inside Your X GUI and enjoy.
86 |
87 | ## Wayland
88 | To deal with wayland-based GUI, (at least) there must be some driver to provide "/dev/input" character devices.
89 | I don't plan to write something for wayland, and also don't know any ready-made solution.
90 | So, feel free to do this job. In case of such a driver appears, I of course will adapt (or help to adapt) xswitcher.
91 |
92 | ## Packaging
93 | I don't have enough time to maintain any distro package (rpm, dpkg, etc.).
94 | But it seems to be a good deed. So, everybody who is ready to do this job is welcome.
95 |
96 | ## Conclusion
97 | Please, don't be shy to report the bug if something in this README looks unclear.
98 |
--------------------------------------------------------------------------------
/bin/xswitcher:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ds-voix/xswitcher/e7cba290dc86ab18287a60de136b50519111742e/bin/xswitcher
--------------------------------------------------------------------------------
/embeddedConfig/config.go:
--------------------------------------------------------------------------------
1 | package embeddedConfig
2 |
3 | const Toml string = `
4 | # xswitcher config file. Uses TOML markup language.
5 | [ScanDevices]
6 | # Must exist on start. Self-respawn in case it is younger then 30s
7 | Test = "/dev/input/event0"
8 | Respawn = 30
9 | # Search mask
10 | Search = "/dev/input/event*"
11 | # In my thinkPads there are such a pseudo-keyboards whith tons of unnecessary events.
12 | Bypass = "(?i)Video|Camera" # "(?i)" obviously differs from "classic" pcre's.
13 |
14 | [Keyboard]
15 | Delay = 5 # Delay in the virtual keyboard before sending the next event
16 |
17 | [Templates] # "@name@" to simplify expressions
18 | # Words can consist of these chars (regex) !!! There must be only "canonic" key names, or regex will fail to match !!!
19 | "WORD" = "([0-9A-Z=-]|GRAVE|APOSTROPHE|SEMICOLON|[LR]_BRACE|COMMA|DOT|(BACK)?SLASH|KP[0-9])"
20 | "SEPARATOR" = "(((BACK)?SPACE)|([=-]|(KP)?MINUS|(KP)?ENTER|ESC|TAB))"
21 | "COMPOSE" = "([0-9=-]|[LR]_BRACE)"
22 |
23 | # actions = (Add, Drop, Test), key codes are defined in "keys.go".
24 | # !!! To be converted into jump matrix inside. Avoid stupid cyclic tests!!!
25 | [ActionKeys]
26 | Layouts = [0, 1] # Don't impact extra languages (e.g., Chinese)
27 |
28 | # Collect key and do the test for command sequence
29 | # !!! Repeat codes (code=2) must be collected once per key!
30 | Add = ["1..0", "-", "=", "BACKSPACE", "Q..]", "L_CTRL..CAPS", "N_LOCK", "S_LOCK",
31 | "KP7..KPDOT", "R_CTRL", "KPSLASH", "R_ALT", "KPEQUAL..PAUSE",
32 | "KPCOMMA", "L_META..COMPOSE", "KPLEFTPAREN", "KPRIGHTPAREN"]
33 |
34 | # Drop all collected keys, including this. This is default action.
35 | Drop = ["ESC", "TAB", "ENTER", "KPENTER", "LINEFEED..POWER"]
36 |
37 | # Store extra map for these keys, when any is in "down" state.
38 | # State is checked via "OFF:"|"ON:" conditions in action.
39 | # (Also, state of these keys must persist between buffer drops.)
40 | # ToDo: StateKeys are hardcoded now.
41 | StateKeys = ["L_CTRL", "L_SHIFT", "L_ALT", "L_META", "CAPS", "N_LOCK", "S_LOCK",
42 | "R_CTRL", "R_SHIFT", "R_ALT", "R_META"]
43 |
44 | # Test only, but don't collect.
45 | # E.g., I use F12 instead of BREAK on dumb laptops whith shitty keyboards (new ThinkPads)
46 | Test = ["F1..F10", "ZENKAKUHANKAKU", "102ND", "F11", "F12",
47 | "RO..KPJPCOMMA", "SYSRQ", "SCALE", "HANGEUL..YEN",
48 | "STOP..SCROLLDOWN", "NEW..MAX"]
49 |
50 |
51 | # Some behaviour can depend on application currently doing the input.
52 | # During runtime, [WindowClasses] are checked in the order in wich they are declared in this config.
53 | [[WindowClasses]]
54 | # VNC, VirtualBox, qemu etc. emulates there input independently, so never intercept.
55 | # With the exception of some stupid VNC clients, which does high-level (layout-based) keyboard input.
56 | Regex = "^(VirtualBox|Focus-Proxy-Window)"
57 | Actions = "" # Do nothing while focus stays in VirtualBox | ATEN-based java VNC-console
58 |
59 | [[WindowClasses]]
60 | Regex = "^konsole"
61 | # In general, mouse clicks leads to unpredictable (at the low-level where xswitcher resides) cursor jumps.
62 | # So, it's good choise to drop all buffers after click.
63 | # But some windows, e.g. terminals, can stay out of this problem.
64 | MouseClickDrops = false
65 | Actions = "Actions"
66 |
67 | [[WindowClasses]] # Default behaviour: no Regex (or wildcard like ".")
68 | MouseClickDrops = true
69 | Actions = "Actions"
70 |
71 |
72 | # action = [ test1, test2, ... ]
73 | # test = (ON|OFF|SEQ):(regex)
74 | # "ON:(regex)" - True if at least one of pressed state keys matches regex.
75 | # "OFF:(regex)" - True if no one of state keys matches regex.
76 | # Note the virtual state key "WORD". It's "pressed" just after the RetypeWord and stays down until NewWord.
77 | # "SEQ:(regex)" — True if last key events (the comma-separated chain of up to SeqLength events) matches regex.
78 | # Use "xswitcher -t" in command line to view typed chain in STDERR.
79 | [Actions]
80 | # Inverse regex is hard to understand, so extract negation to external condition.
81 | # Expresions will be checked in direct order, one-by-one. Condition succceds when ALL results are True.
82 | # Maximum key sequence length, extra keys will be dropped. More length - more CPU.
83 | SeqLength = 12
84 | # Count only those chars in word which must be removed (by sending the same count of BS keys) while "RetypeWord".
85 | WordChars = "(^@WORD@:0$)"
86 | # Drop word buffer and start collecting new one
87 | # !!! Note that (@WORD@:1) /key-press/ at the end of regex allows to collect the last char,
88 | # while (@WORD@:0) cuts the WORD strictly at the end of sequence. !!!
89 | # --- In my layout, R_META selects 5'th layout and R_ALT does "compose". ---
90 | NewWord = [ "SEQ:(@SEPARATOR@:[12]),(((CAPS:[012])|([LR]_SHIFT:[12])|(R_META:0)|((@WORD@|@SEPARATOR@):0)),)*(@WORD@:1)", # "@WORD@:0" then collects the char
91 | "SEQ:(@WORD@:2,@WORD@:0)", # Drop repeated char at all: unlikely it needs correction
92 | "SEQ:(BACKSPACE:0)", # Drop buffer just afrer BACKSPACE
93 | # Control sequences. !!! Must be dropped ASAP.
94 | "SEQ:((([LR]_CTRL|L_ALT|[LR]_META):[12])(,((@WORD@|@SEPARATOR@):[012]))+(,(([LR]_CTRL|L_ALT|[LR]_META):0))+(,@WORD@:1)?)", # "@WORD@:0" then collects the char
95 | "ON:(WORD) SEQ:(,@WORD@:1)" ] # New input after previous correction. "@WORD@:0" then collects the char
96 | # Drop all buffers
97 | NewSentence = [ "SEQ:(ENTER:0)" ]
98 |
99 | # In some windows the single char must be deleted by single BS, so there is need in compose sequence detector.
100 | Compose = [ "OFF:(CTRL|L_ALT|META|SHIFT) SEQ:(R_ALT:1(,R_ALT:2)?(,[LR]_SHIFT:[12])*(,@COMPOSE@:1,@COMPOSE@:0)(,[LR]_SHIFT:0)?(,@COMPOSE@:1,@COMPOSE@:0),R_ALT:0)",
101 | "OFF:(CTRL|L_ALT|META|SHIFT) SEQ:(R_ALT:1(,R_ALT:2)?(,[LR]_SHIFT:[12])*,@COMPOSE@:1,@COMPOSE@:0(,[LR]_SHIFT:0)?,R_ALT:0(,[LR]_SHIFT:0)?,@COMPOSE@:1,@COMPOSE@:0)" ]
102 |
103 | # Try to type the text from clipboard to virtual keyboard.
104 | # Shift+Shift+L_Ctrl
105 | # TypeClipboard = [ "OFF:(CTRL|L_ALT|META) SEQ:(L_CTRL:1,L_CTRL:0,[LR]_SHIFT:0,[LR]_SHIFT:0)"]
106 |
107 | # !!! Note that xswitcher counts extra keys as the length of matched SEQ:() !!!
108 | # So, any regex for "RetypeWord" SEQ must be EXACT ONE. Otherwise, xswitcher will generate the troubles for You.
109 | "Action.RetypeWord" = [ "OFF:(CTRL|ALT|META|SHIFT) SEQ:(PAUSE:1,PAUSE:0)",
110 | "OFF:(CTRL|ALT|META|SHIFT) SEQ:(F12:1,F12:0)" ]
111 |
112 | "Action.CyclicSwitch" = [ "OFF:(R_CTRL|ALT|META|SHIFT) SEQ:(L_CTRL:1,L_CTRL:0)" ] # Single short LEFT CONTROL
113 | "Action.Respawn" = [ "OFF:(CTRL|ALT|META|SHIFT) SEQ:(S_LOCK:2,S_LOCK:0)" ] # Long-pressed SCROLL LOCK
114 |
115 | "Action.Layout0" = [ "OFF:(CTRL|ALT|META|R_SHIFT) SEQ:(L_SHIFT:1,L_SHIFT:0)" ] # Single short LEFT SHIFT
116 | "Action.Layout1" = [ "OFF:(CTRL|ALT|META|L_SHIFT) SEQ:(R_SHIFT:1,R_SHIFT:0)" ] # Single short RIGHT SHIFT
117 |
118 | "Action.Hook1" = [ "OFF:(CTRL|R_ALT|META|SHIFT) SEQ:(L_ALT:1,L_ALT:0)" ]
119 |
120 |
121 | # Action is the array, so actions could be chained (m.b., infinitely... Have I to check this?).
122 | # For each action type, extra named parameters could be collected. Invalid parameters will be ignored(?).
123 | [Action.RetypeWord] # Switch layout, drop last word and type it again
124 | Action = [ "Action.CyclicSwitch", "RetypeWord" ] # Call Switch() between layouts tuned below, then RetypeWord()
125 |
126 | [Action.CyclicSwitch] # Cyclic layout switching
127 | Action = [ "Switch" ] # Internal layout switcher func
128 | Layouts = [0, 1]
129 |
130 | [Action.Layout0] # Direct layout selection
131 | Action = [ "Layout" ] # Internal layout selection func
132 | Layout = 0
133 |
134 | [Action.Layout1] # Direct layout selection
135 | Action = [ "Layout" ] # Internal layout selection func
136 | Layout = 1
137 |
138 | [Action.Respawn] # Completely respawn xswitcher. Reload config as well
139 | Action = [ "Respawn" ]
140 |
141 | [Action.Hook1] # Run external commands
142 | Action = [ "Exec" ]
143 | Exec = "cat > /tmp/xxx" # All the input after the 1'st space will be reassembled into the CLI args.
144 | # Timeout = 1000 # Wait up to 1 second, then kill the executing process.
145 | # Wait = true # Wait for termination, then output the result to STDOUT|STDERR.
146 | # External hook can process collected buffer by it's own means.
147 | # The last typed word, or sentence, or just the custom string could be passed to stdIn.
148 | SendBuffer = "WORD" # "WORD"|"SENTENCE"|"any custom input\n"
149 |
150 | UseShell = true # Execute inside /bin/bash
151 | # Directory = "/path/to/" # Change the working directory to this one.
152 | CleanEnv = true # Run command inside the clean environment.
153 | Environment = [ "var=value" ] # A set of environment variables.
154 |
155 | # Use the specific user/group.
156 | UID = "root"
157 | GID = "root"
158 | `
159 |
--------------------------------------------------------------------------------
/exec/exec.go:
--------------------------------------------------------------------------------
1 | package exec
2 |
3 | /*
4 | Fold external command execution.
5 | */
6 |
7 | import (
8 | "bytes"
9 | "io"
10 | "io/ioutil"
11 | "os/exec"
12 | "sync"
13 | "syscall"
14 | "time"
15 | )
16 |
17 | type Command struct {
18 | id string // Sequence ID may be set. Othewise, it is auto-generated.
19 | no_exec bool
20 | UID, GID uint32 // "run_as" linux representation
21 | UseShell bool
22 | No_wait bool // https://golang.org/pkg/os/exec/#Cmd.Start vs "Run()" or m.b. "Wait()"
23 | Timeout float64
24 | max_reply int64
25 | // https://golang.org/pkg/os/exec/#Cmd
26 | Set_env []string
27 | Set_dir string
28 | Command string
29 | Args []string
30 | StdIn []byte
31 | }
32 |
33 | type Result struct {
34 | ID string `json:"id"`
35 | Processed bool `json:"processed"` // Was this command ever been processed?
36 | Command string `json:"command"`
37 | Args []string `json:"args,omitempty"`
38 | Status int `json:"status"`
39 | StdOut []byte `json:"stdout,omitempty"`
40 | StdErr []byte `json:"stderr,omitempty"`
41 | }
42 |
43 | // https://golang.org/pkg/os/exec/#Cmd
44 | func ExecCommand(c *Command) (*Result) {
45 | // var waitWorkers *sync.WaitGroup
46 |
47 | r := &Result{ID: c.id,
48 | Command: c.Command,
49 | Args: c.Args}
50 |
51 | cmd := exec.Command(c.Command)
52 | if c.UseShell { // Pack into bash environment (In fact, bash is *sh's mainstream. And I unwill to deep into specifics)
53 | cmd = exec.Command("/bin/bash")
54 | // -c If the -c option is present, then commands are read from the first non-option argument command_string. If there are arguments after the command_string, the first argu-
55 | // ment is assigned to $0 and any remaining arguments are assigned to the positional parameters. The assignment to $0 sets the name of the shell, which is used in warning
56 | // and error messages.
57 | cmd.Args = append(cmd.Args, "-c")
58 | cmd.Args = append(cmd.Args, c.Command)
59 | }
60 | // https://medium.com/@felixge/killing-a-child-process-and-all-of-its-children-in-go-54079af94773
61 | cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
62 |
63 | cmd.Args = append(cmd.Args, c.Args...)
64 | cmd.Stdin = bytes.NewReader(c.StdIn)
65 |
66 | // https://stackoverflow.com/questions/21705950/running-external-commands-through-os-exec-under-another-user
67 | if c.UID > 0 {
68 | cmd.SysProcAttr = &syscall.SysProcAttr{}
69 | cmd.SysProcAttr.Credential = &syscall.Credential{Uid: c.UID, Gid: c.GID}
70 | }
71 | if len(c.Set_dir) > 0 {
72 | cmd.Dir = c.Set_dir
73 | }
74 | if len(c.Set_env) > 0 {
75 | cmd.Env = append(cmd.Env, c.Set_env...)
76 | }
77 |
78 | // http://www.agardner.me/golang/garbage/collection/gc/escape/analysis/2015/10/18/go-escape-analysis.html
79 | // https://habr.com/ru/company/intel/blog/422447/
80 | var _stdout, _stderr bytes.Buffer
81 | var stdoutIn, stderrIn io.ReadCloser
82 | var errStdout, errStderr error
83 |
84 | stdout := io.Writer(&_stdout)
85 | stderr := io.Writer(&_stderr)
86 | if ! c.No_wait { // Otherwise, just fork process with /dev/null at stdout&stderr.
87 | stdoutIn, _ = cmd.StdoutPipe()
88 | stderrIn, _ = cmd.StderrPipe()
89 | }
90 |
91 | r.Status = 0
92 | if c.no_exec {
93 | r.StdErr = []byte("no_exec")
94 | return r
95 | }
96 |
97 | err := cmd.Start()
98 | r.Processed = true
99 | if err != nil {
100 | r.StdErr= []byte(err.Error())
101 | if exitErr, ok := err.(*exec.ExitError); ok {
102 | if _status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
103 | r.Status = _status.ExitStatus()
104 | }
105 | } else {
106 | r.Status = -1 // No such command at all?
107 | }
108 |
109 | return r
110 | }
111 | // fmt.Printf("pid = %d\n", cmd.Process.Pid)
112 |
113 | if c.No_wait {
114 | cmd.Process.Release() // Drop PPID to avoid zombies
115 | return r
116 | }
117 |
118 | // Wait for the process to finish or kill it after a timeout (whichever happens first):
119 | if c.Timeout > 0 {
120 | go func(cmd *exec.Cmd, pid int) { // !!! panic: runtime error: invalid memory address or nil pointer dereference
121 | for i := 0; i < int(c.Timeout * 10); i++ {
122 | time.Sleep(time.Second / 10)
123 | if cmd == nil { return }
124 | if cmd.ProcessState != nil {
125 | break
126 | }
127 | }
128 |
129 | if cmd.ProcessState == nil {
130 | // cmd.Process.Signal(syscall.SIGTERM) // No, such a method terminates only this PID, leaving orphans!
131 | if cmd == nil { return }
132 | syscall.Kill(-pid, syscall.SIGTERM) // !!! [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x7c1ef0]
133 | time.Sleep(time.Second / 2)
134 | if cmd == nil { return }
135 | syscall.Kill(-pid, syscall.SIGKILL)
136 | }
137 | } (cmd, cmd.Process.Pid)
138 | } else if c.Timeout == 0 { // Wait for interrupt
139 | go func(cmd *exec.Cmd, pid int) {
140 | // defer waitWorkers.Done()
141 | for {
142 | time.Sleep(time.Second / 50)
143 | if cmd == nil { return }
144 | if cmd.ProcessState != nil {
145 | break
146 | }
147 | /*
148 | if interrupt {
149 | break
150 | }
151 | */
152 | }
153 |
154 | if cmd.ProcessState == nil {
155 | // cmd.Process.Signal(syscall.SIGTERM) // No, such a method terminates only this PID, leaving orphans!
156 | if cmd == nil { return }
157 | syscall.Kill(-pid, syscall.SIGTERM) // !!! [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x7c1ef0]
158 | time.Sleep(time.Second / 2)
159 | if cmd == nil { return }
160 | syscall.Kill(-pid, syscall.SIGKILL)
161 | }
162 | } (cmd, cmd.Process.Pid)
163 | }
164 |
165 | // https://blog.kowalczyk.info/article/wOYk/advanced-command-execution-in-go-with-osexec.html
166 | var wg sync.WaitGroup
167 | wg.Add(1)
168 | go func() {
169 | _, errStdout = io.CopyN(stdout, stdoutIn, c.max_reply)
170 | if errStdout == io.EOF {
171 | errStdout = nil
172 | } else {
173 | io.Copy(ioutil.Discard, stdoutIn) // Discard all the rest of stdout
174 | }
175 | wg.Done()
176 | } ()
177 | _, errStderr = io.CopyN(stderr, stderrIn, c.max_reply)
178 | if errStderr == io.EOF {
179 | errStderr = nil
180 | } else {
181 | io.Copy(ioutil.Discard, stderrIn) // Discard all the rest of stderr
182 | }
183 | wg.Wait()
184 |
185 | err = cmd.Wait()
186 | if err != nil {
187 | r.StdErr = []byte(err.Error())
188 | if exitErr, ok := err.(*exec.ExitError); ok {
189 | if _status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
190 | r.Status = _status.ExitStatus()
191 | }
192 | } else {
193 | r.Status = -1 // No such command at all?
194 | }
195 |
196 | }
197 |
198 | if errStdout != nil {
199 | r.StdOut = []byte(errStdout.Error())
200 | r.Status = -254
201 | }
202 | if errStderr != nil {
203 | r.StdErr = []byte(errStderr.Error())
204 | r.Status = -255
205 | }
206 |
207 | r.StdOut = _stdout.Bytes()
208 | r.StdErr = _stderr.Bytes()
209 | return r
210 | }
211 |
--------------------------------------------------------------------------------
/gnome3/switch.gnome:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Uses "g3kb-switch" to switch between two languages under gnome3.
4 |
5 | # apt install build-essential
6 | # git clone https://github.com/lyokha/g3kb-switch.git
7 |
8 | # Then build and install "g3kb-switch",
9 | # according to instruction at https://github.com/lyokha/g3kb-switch
10 |
11 | locale0="us"
12 | locale1="ru"
13 |
14 | export DISPLAY=":0"
15 | export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/1000/bus"
16 |
17 | if [ -z "$1" ]; then
18 | locale=$(/usr/local/bin/g3kb-switch -p)
19 | if [ "${locale}" = "${locale0}" ]; then
20 | /usr/local/bin/g3kb-switch -s ${locale1}
21 | else
22 | /usr/local/bin/g3kb-switch -s ${locale0}
23 | fi
24 | exit $?
25 | fi
26 |
27 | if [ "$1" = "0" ]; then
28 | /usr/local/bin/g3kb-switch -s ${locale0}
29 | else
30 | /usr/local/bin/g3kb-switch -s ${locale1}
31 | fi
32 | exit $?
33 |
--------------------------------------------------------------------------------
/gnome3/xswitcher.conf:
--------------------------------------------------------------------------------
1 | # xswitcher config file. Uses TOML markup language.
2 | # Tuned for gnome3. Switches between languages by means of
3 | # https://github.com/lyokha/g3kb-switch external executable.
4 | # Uses helper script "switch.gnome" instead of X API,
5 | # as X API doesn't work under gnome due to https://bugs.launchpad.net/ubuntu/+source/xorg-server/+bug/711842
6 | # The root cause was ignored in gnome. M.b., to say "X sucks, use wayland"?
7 | #
8 | # !!! Replace "user_name" in all "UID =" assignments with your GUI user name !!!
9 | #
10 | [ScanDevices]
11 | # Must exist on start. Self-respawn in case it is younger then 30s
12 | Test = "/dev/input/event0"
13 | Respawn = 30
14 | # Search mask
15 | Search = "/dev/input/event*"
16 | # In my thinkPads there are such a pseudo-keyboards whith tons of unnecessary events.
17 | Bypass = "(?i)Video|Camera" # "(?i)" obviously differs from "classic" pcre's.
18 |
19 | [Keyboard]
20 | Delay = 5 # Delay in the virtual keyboard before sending the next event
21 |
22 | [Templates] # "@name@" to simplify expressions
23 | # Words can consist of these chars (regex) !!! There must be only "canonic" key names, or regex will fail to match !!!
24 | "WORD" = "([0-9A-Z=-]|GRAVE|APOSTROPHE|SEMICOLON|[LR]_BRACE|COMMA|DOT|(BACK)?SLASH|KP[0-9])"
25 | "SEPARATOR" = "(((BACK)?SPACE)|([=-]|(KP)?MINUS|(KP)?ENTER|ESC|TAB))"
26 | "COMPOSE" = "([0-9=-]|[LR]_BRACE)"
27 |
28 | # actions = (Add, Drop, Test), key codes are defined in "keys.go".
29 | # !!! To be converted into jump matrix inside. Avoid stupid cyclic tests!!!
30 | [ActionKeys]
31 | Layouts = [0, 1] # Don't impact extra languages (e.g., Chinese)
32 |
33 | # Collect key and do the test for command sequence
34 | # !!! Repeat codes (code=2) must be collected once per key!
35 | Add = ["1..0", "-", "=", "BACKSPACE", "Q..]", "L_CTRL..CAPS", "N_LOCK", "S_LOCK",
36 | "KP7..KPDOT", "R_CTRL", "KPSLASH", "R_ALT", "KPEQUAL..PAUSE",
37 | "KPCOMMA", "L_META..COMPOSE", "KPLEFTPAREN", "KPRIGHTPAREN"]
38 |
39 | # Drop all collected keys, including this. This is default action.
40 | Drop = ["ESC", "TAB", "ENTER", "KPENTER", "LINEFEED..POWER"]
41 |
42 | # Store extra map for these keys, when any is in "down" state.
43 | # State is checked via "OFF:"|"ON:" conditions in action.
44 | # (Also, state of these keys must persist between buffer drops.)
45 | # ToDo: StateKeys are hardcoded now.
46 | StateKeys = ["L_CTRL", "L_SHIFT", "L_ALT", "L_META", "CAPS", "N_LOCK", "S_LOCK",
47 | "R_CTRL", "R_SHIFT", "R_ALT", "R_META"]
48 |
49 | # Test only, but don't collect.
50 | # E.g., I use F12 instead of BREAK on dumb laptops whith shitty keyboards (new ThinkPads)
51 | Test = ["F1..F10", "ZENKAKUHANKAKU", "102ND", "F11", "F12",
52 | "RO..KPJPCOMMA", "SYSRQ", "SCALE", "HANGEUL..YEN",
53 | "STOP..SCROLLDOWN", "NEW..MAX"]
54 |
55 |
56 | # Some behaviour can depend on application currently doing the input.
57 | # During runtime, [WindowClasses] are checked in the order in wich they are declared in this config.
58 | [[WindowClasses]]
59 | # VNC, VirtualBox, qemu etc. emulates there input independently, so never intercept.
60 | # With the exception of some stupid VNC clients, which does high-level (layout-based) keyboard input.
61 | Regex = "^(VirtualBox|Focus-Proxy-Window)"
62 | Actions = "" # Do nothing while focus stays in VirtualBox | ATEN-based java VNC-console
63 |
64 | [[WindowClasses]]
65 | Regex = "^konsole"
66 | # In general, mouse clicks leads to unpredictable (at the low-level where xswitcher resides) cursor jumps.
67 | # So, it's good choise to drop all buffers after click.
68 | # But some windows, e.g. terminals, can stay out of this problem.
69 | MouseClickDrops = false
70 | Actions = "Actions"
71 |
72 | [[WindowClasses]] # Default behaviour: no Regex (or wildcard like ".")
73 | MouseClickDrops = true
74 | Actions = "Actions"
75 |
76 |
77 | # action = [ test1, test2, ... ]
78 | # test = (ON|OFF|SEQ):(regex)
79 | # "ON:(regex)" - True if at least one of pressed state keys matches regex.
80 | # "OFF:(regex)" - True if no one of state keys matches regex.
81 | # Note the virtual state key "WORD". It's "pressed" just after the RetypeWord and stays down until NewWord.
82 | # "SEQ:(regex)" — True if last key events (the comma-separated chain of up to SeqLength events) matches regex.
83 | # Use "xswitcher -t" in command line to view typed chain in STDERR.
84 | [Actions]
85 | # Inverse regex is hard to understand, so extract negation to external condition.
86 | # Expresions will be checked in direct order, one-by-one. Condition succceds when ALL results are True.
87 | # Maximum key sequence length, extra keys will be dropped. More length - more CPU.
88 | SeqLength = 12
89 | # Count only those chars in word which must be removed (by sending the same count of BS keys) while "RetypeWord".
90 | WordChars = "(^@WORD@:0$)"
91 | # Drop word buffer and start collecting new one
92 | # !!! Note that (@WORD@:1) /key-press/ at the end of regex allows to collect the last char,
93 | # while (@WORD@:0) cuts the WORD strictly at the end of sequence. !!!
94 | # --- In my layout, R_META selects 5'th layout and R_ALT does "compose". ---
95 | NewWord = [ "SEQ:(@SEPARATOR@:[12]),(((CAPS:[012])|([LR]_SHIFT:[12])|(R_META:0)|((@WORD@|@SEPARATOR@):0)),)*(@WORD@:1)", # "@WORD@:0" then collects the char
96 | "SEQ:(@WORD@:2,@WORD@:0)", # Drop repeated char at all: unlikely it needs correction
97 | "SEQ:(BACKSPACE:0)", # Drop buffer just afrer BACKSPACE
98 | # Control sequences. !!! Must be dropped ASAP.
99 | "SEQ:((([LR]_CTRL|L_ALT|[LR]_META):[12])(,((@WORD@|@SEPARATOR@):[012]))+(,(([LR]_CTRL|L_ALT|[LR]_META):0))+(,@WORD@:1)?)", # "@WORD@:0" then collects the char
100 | "ON:(WORD) SEQ:(,@WORD@:1)" ] # New input after previous correction. "@WORD@:0" then collects the char
101 | # Drop all buffers
102 | NewSentence = [ "SEQ:(ENTER:0)" ]
103 |
104 | # In some windows the single char must be deleted by single BS, so there is need in compose sequence detector.
105 | Compose = [ "OFF:(CTRL|L_ALT|META|SHIFT) SEQ:(R_ALT:1(,R_ALT:2)?(,[LR]_SHIFT:[12])*(,@COMPOSE@:1,@COMPOSE@:0)(,[LR]_SHIFT:0)?(,@COMPOSE@:1,@COMPOSE@:0),R_ALT:0)",
106 | "OFF:(CTRL|L_ALT|META|SHIFT) SEQ:(R_ALT:1(,R_ALT:2)?(,[LR]_SHIFT:[12])*,@COMPOSE@:1,@COMPOSE@:0(,[LR]_SHIFT:0)?,R_ALT:0(,[LR]_SHIFT:0)?,@COMPOSE@:1,@COMPOSE@:0)" ]
107 |
108 | # !!! Note that xswitcher counts extra keys as the length of matched SEQ:() !!!
109 | # So, any regex for "RetypeWord" SEQ must be EXACT ONE. Otherwise, xswitcher will generate the troubles for You.
110 | "Action.RetypeWord" = [ "OFF:(CTRL|ALT|META|SHIFT) SEQ:(PAUSE:1,PAUSE:0)",
111 | "OFF:(CTRL|ALT|META|SHIFT) SEQ:(F12:1,F12:0)" ]
112 |
113 | "Action.CyclicSwitch" = [ "OFF:(R_CTRL|ALT|META|SHIFT) SEQ:(L_CTRL:1,L_CTRL:0)" ] # Single short LEFT CONTROL
114 | "Action.Respawn" = [ "OFF:(CTRL|ALT|META|SHIFT) SEQ:(S_LOCK:2,S_LOCK:0)" ] # Long-pressed SCROLL LOCK
115 |
116 | "Action.Layout0" = [ "OFF:(CTRL|ALT|META|R_SHIFT) SEQ:(L_SHIFT:1,L_SHIFT:0)" ] # Single short LEFT SHIFT
117 | "Action.Layout1" = [ "OFF:(CTRL|ALT|META|L_SHIFT) SEQ:(R_SHIFT:1,R_SHIFT:0)" ] # Single short RIGHT SHIFT
118 |
119 | # "Action.Hook1" = [ "OFF:(CTRL|R_ALT|META|SHIFT) SEQ:(L_ALT:1,L_ALT:0)" ]
120 |
121 |
122 | # Action is the array, so actions could be chained (m.b., infinitely... Have I to check this?).
123 | # For each action type, extra named parameters could be collected. Invalid parameters will be ignored(?).
124 | [Action.RetypeWord] # Switch layout, drop last word and type it again
125 | Action = [ "Action.CyclicSwitch", "RetypeWord" ] # Call Switch() between layouts tuned below, then RetypeWord()
126 |
127 | [Action.CyclicSwitch] # Cyclic layout switching
128 | # Action = [ "Switch" ] # Internal layout switcher func
129 | # Layouts = [0, 1]
130 | Action = [ "Action.EN_RU" ]
131 |
132 | [Action.Layout0] # Direct layout selection
133 | # Action = [ "Layout" ] # Internal layout selection func
134 | # Layout = 0
135 | Action = [ "Action.EN" ]
136 |
137 | [Action.Layout1] # Direct layout selection
138 | # Action = [ "Layout" ] # Internal layout selection func
139 | # Layout = 1
140 | Action = [ "Action.RU" ]
141 |
142 | [Action.Respawn] # Completely respawn xswitcher. Reload config as well
143 | Action = [ "Respawn" ]
144 |
145 | [Action.EN_RU] # CyclicSwitch for gnome3
146 | Action = [ "Exec" ]
147 | Exec = "/usr/local/bin/switch.gnome"
148 | Wait = true # Wait for termination, then output the result to STDOUT|STDERR.
149 | UseShell = true # Execute inside /bin/bash
150 | CleanEnv = true # Run command inside the clean environment.
151 | # Use the specific user/group.
152 | UID = "user_name"
153 |
154 | [Action.EN] # Run external commands
155 | Action = [ "Exec" ]
156 | Exec = "/usr/local/bin/switch.gnome 0"
157 | Wait = true # Wait for termination, then output the result to STDOUT|STDERR.
158 | UseShell = true # Execute inside /bin/bash
159 | CleanEnv = true # Run command inside the clean environment.
160 | # Use the specific user/group.
161 | UID = "user_name"
162 |
163 | [Action.RU] # Run external commands
164 | Action = [ "Exec" ]
165 | Exec = "/usr/local/bin/switch.gnome 1"
166 | Wait = true # Wait for termination, then output the result to STDOUT|STDERR.
167 | UseShell = true # Execute inside /bin/bash
168 | CleanEnv = true # Run command inside the clean environment.
169 | # Use the specific user/group.
170 | UID = "user_name"
171 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module xswitcher
2 |
3 | go 1.22.4
4 |
5 | replace github.com/micmonay/keybd_event => ./src/keybd_event/
6 |
7 | require (
8 | github.com/fsnotify/fsnotify v1.7.0
9 | github.com/gvalkov/golang-evdev v0.0.0-20220815104727-7e27d6ce89b6
10 | github.com/holoplot/go-evdev v0.0.0-20240306072622-217e18f17db1
11 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
12 | github.com/micmonay/keybd_event v1.1.2
13 | github.com/pelletier/go-toml v1.9.5
14 | github.com/spf13/pflag v1.0.5
15 | golang.design/x/clipboard v0.7.0
16 | )
17 |
18 | require (
19 | golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 // indirect
20 | golang.org/x/image v0.6.0 // indirect
21 | golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c // indirect
22 | golang.org/x/sys v0.5.0 // indirect
23 | )
24 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
2 | github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
3 | github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
4 | github.com/gvalkov/golang-evdev v0.0.0-20220815104727-7e27d6ce89b6 h1:K9b8efT9f1NkITNgNAm2A1LuoamhG4pAhXVjz5Sfa5Q=
5 | github.com/gvalkov/golang-evdev v0.0.0-20220815104727-7e27d6ce89b6/go.mod h1:SAzVFKCRezozJTGavF3GX8MBUruETCqzivVLYiywouA=
6 | github.com/holoplot/go-evdev v0.0.0-20240306072622-217e18f17db1 h1:92OsBIf5KB1Tatx+uUGOhah73jyNUrt7DmfDRXXJ5Xo=
7 | github.com/holoplot/go-evdev v0.0.0-20240306072622-217e18f17db1/go.mod h1:iHAf8OIncO2gcQ8XOjS7CMJ2aPbX2Bs0wl5pZyanEqk=
8 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
9 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
10 | github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
11 | github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
12 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
13 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
14 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
15 | golang.design/x/clipboard v0.7.0 h1:4Je8M/ys9AJumVnl8m+rZnIvstSnYj1fvzqYrU3TXvo=
16 | golang.design/x/clipboard v0.7.0/go.mod h1:PQIvqYO9GP29yINEfsEn5zSQKAz3UgXmZKzDA6dnq2E=
17 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
18 | golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
19 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
20 | golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 h1:estk1glOnSVeJ9tdEZZc5mAMDZk5lNJNyJ6DvrBkTEU=
21 | golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4=
22 | golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
23 | golang.org/x/image v0.6.0 h1:bR8b5okrPI3g/gyZakLZHeWxAR8Dn5CyxXv1hLH5g/4=
24 | golang.org/x/image v0.6.0/go.mod h1:MXLdDR43H7cDJq5GEGXEVeeNhPgi+YYEQ2pC1byI1x0=
25 | golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
26 | golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c h1:Gk61ECugwEHL6IiyyNLXNzmu8XslmRP2dS0xjIYhbb4=
27 | golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c/go.mod h1:aAjjkJNdrh3PMckS4B10TGS2nag27cbKR1y2BpUxsiY=
28 | golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
29 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
30 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
31 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
32 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
33 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
34 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
35 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
36 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
37 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
38 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
39 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
40 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
41 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
42 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
43 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
44 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
45 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
46 | golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
47 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
48 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
49 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
50 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
51 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
52 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
53 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
54 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
55 | golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
56 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
57 | golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
58 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
59 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
60 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
61 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
62 |
--------------------------------------------------------------------------------
/scancodes/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2015 Victor Costan. All rights reserved.
2 |
3 | Redistribution and use in source and binary forms, with or without
4 | modification, are permitted provided that the following conditions are
5 | met:
6 |
7 | * Redistributions of source code must retain the above copyright
8 | notice, this list of conditions and the following disclaimer.
9 | * Redistributions in binary form must reproduce the above
10 | copyright notice, this list of conditions and the following disclaimer
11 | in the documentation and/or other materials provided with the
12 | distribution.
13 | * Neither the name of Google Inc. nor the names of its
14 | contributors may be used to endorse or promote products derived from
15 | this software without specific prior written permission.
16 |
17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 |
--------------------------------------------------------------------------------
/scancodes/README.md:
--------------------------------------------------------------------------------
1 | # scancodes
2 |
3 | [](https://godoc.org/github.com/pwnall/scancodes)
4 |
5 | scancodes is a Go package that computes the Set 1 (IBM PC XT)
6 | [keyboard scancodes](http://en.wikipedia.org/wiki/Scancode) produced by a
7 | keyboard when a string is typed in.
8 |
9 | This is the author's secod piece of Go code, so feedback is welcome.
10 |
11 |
12 | ## Copyright and Licensing
13 |
14 | This package is (C) Victor Costan 2015, and made available under the MIT
15 | license, which is contained in the `LICENSE` file.
16 |
--------------------------------------------------------------------------------
/scancodes/scancodes.go:
--------------------------------------------------------------------------------
1 | // Package scancodes computes the Set 1 (IBM PC XT) keyboard scancodes produced
2 | // by typing in a string.
3 | package scancodes
4 |
5 | import (
6 | "bytes"
7 | "errors"
8 | "strings"
9 | "unicode"
10 | )
11 |
12 | // ForString obtains the series of scancodes needed to produce a string.
13 | func ForString(input string) ([]int, error) {
14 | return ForSequence(SequenceForString(input))
15 | }
16 |
17 | // ForSequence obtains the series of scancodes for a sequence of keypresses.
18 | func ForSequence(sequence string) ([]int, error) {
19 | codes := make([]int, 0, len(sequence))
20 | depress := make([]int, 0, 2)
21 | for _, chord := range strings.Split(sequence, " ") {
22 | chordLoop: for _, key := range strings.Split(chord, "+") {
23 | for code, codeKey := range baseCodes {
24 | if key == codeKey || key == numLockCodes[code] {
25 | codes = append(codes, code)
26 | depress = append(depress, 0x80 | code)
27 | continue chordLoop
28 | }
29 | }
30 | for codeKey, codeSequence := range escapeTable {
31 | if key == codeKey {
32 | codes = append(codes, codeSequence[0], codeSequence[1])
33 | depress = append(depress, codeSequence[0], 0x80 | codeSequence[1])
34 | continue chordLoop
35 | }
36 | }
37 | return nil, errors.New("Unknown keyboard key " + key)
38 | }
39 | codes = append(codes, depress...)
40 | depress = depress[:0]
41 | }
42 | return codes, nil
43 | }
44 |
45 | // SequenceForString converts an input string into a sequence of keypresses.
46 | func SequenceForString(input string) string {
47 | sequence := bytes.Buffer{}
48 | wroteFirst := false
49 | for _, char := range input {
50 | if wroteFirst {
51 | sequence.WriteRune(' ')
52 | } else {
53 | wroteFirst = true
54 | }
55 | sequence.WriteString(SequenceForChar(char))
56 | }
57 | return sequence.String()
58 | }
59 |
60 | // SequenceForChar converts an input character into a sequence of keypresses.
61 | func SequenceForChar(char rune) string {
62 | // Letters.
63 | if unicode.IsLower(char) {
64 | return string(unicode.ToUpper(char))
65 | } else if unicode.IsUpper(char) {
66 | return "LShift+" + string(char)
67 | }
68 | switch char {
69 | case '\n':
70 | return "Enter"
71 | case '\t':
72 | return "Tab"
73 | case ' ':
74 | return "Space"
75 | }
76 | for code, keyName := range shiftCodes {
77 | if keyName == string(char) {
78 | return "LShift+" + baseCodes[code]
79 | }
80 | }
81 | return string(char)
82 | }
83 |
--------------------------------------------------------------------------------
/scancodes/scancodes_test.go:
--------------------------------------------------------------------------------
1 | package scancodes
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func ExampleSequenceForChar_letters() {
8 | fmt.Printf("%s %s\n", SequenceForChar('a'), SequenceForChar('A'))
9 | fmt.Printf("%s %s\n", SequenceForChar('v'), SequenceForChar('V'))
10 | // Output:
11 | // A LShift+A
12 | // V LShift+V
13 | }
14 | func ExampleSequenceForChar_symbols() {
15 | fmt.Printf("%s %s\n", SequenceForChar(';'), SequenceForChar(':'))
16 | // Output:
17 | // ; LShift+;
18 | }
19 | func ExampleSequenceForChar_whitespace() {
20 | fmt.Printf("%s %s\n", SequenceForChar(' '), SequenceForChar('\n'))
21 | // Output:
22 | // Space Enter
23 | }
24 |
25 | func ExampleSequenceForString() {
26 | fmt.Println(SequenceForString("Hello world!\n"))
27 | // Output: LShift+H E L L O Space W O R L D LShift+1 Enter
28 | }
29 |
30 | func ExampleForSequence_key() {
31 | codes, err := ForSequence("Esc")
32 | fmt.Printf("%x %v", codes, err)
33 | // Output:
34 | // [1 81]
35 | }
36 | func ExampleForSequence_konami() {
37 | codes, err := ForSequence("Up Up Down Down Left Right Left Right B A")
38 | fmt.Printf("%x %v", codes, err)
39 | // Output:
40 | // [48 c8 48 c8 50 d0 50 d0 4b cb 4d cd 4b cb 4d cd 30 b0 1e 9e]
41 | }
42 | func ExampleForSequence_reboot() {
43 | codes, err := ForSequence("LCtrl+LAlt+Del")
44 | fmt.Printf("%x %v", codes, err)
45 | // Output: [1d 38 53 9d b8 d3]
46 | }
47 | func ExampleForSequence_error() {
48 | codes, err := ForSequence("Food")
49 | fmt.Printf("%x %v", codes, err)
50 | // Output: [] Unknown keyboard key Food
51 | }
52 |
53 | func ExampleForString() {
54 | codes, err := ForString("Hello")
55 | fmt.Printf("%x %v", codes, err)
56 | // Output: [2a 23 aa a3 12 92 26 a6 26 a6 18 98]
57 | }
58 |
--------------------------------------------------------------------------------
/scancodes/table.go:
--------------------------------------------------------------------------------
1 | package scancodes
2 |
3 | // Tables lifted from:
4 | // http://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html#ss1.4
5 |
6 | // Unshifted codes.
7 | var baseCodes = []string{
8 | "Error",
9 | "Esc", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace",
10 | "Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]",
11 | "Enter",
12 | "LCtrl",
13 | "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'",
14 | "`",
15 | "LShift", "\\",
16 | "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "RShift",
17 | "Keypad_*",
18 | "LAlt", "Space",
19 | "CapsLock",
20 | "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10",
21 | "NumLock", "ScrollLock",
22 | "Keypad_7", "Keypad_8", "Keypad_9",
23 | "Keypad_-",
24 | "Keypad_4", "Keypad_5", "Keypad_6", "Keypad_Plus",
25 | "Keypad_1", "Keypad_2", "Keypad_3",
26 | "Keypad_0", "Keypad-.",
27 | "Alt_SysRq",
28 | }
29 |
30 | // Shifted codes.
31 | // NOTE: Uppercase letters are special-cased in code. They're only here because
32 | // they help us align the other keys.
33 | var shiftCodes = []string{
34 | "",
35 | "", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "",
36 | "", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "{", "}",
37 | "Enter",
38 | "LCtrl",
39 | "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "\"",
40 | "~",
41 | "", "|",
42 | "Z", "X", "C", "V", "B", "N", "M", "<", ">", "?", "",
43 | "PrintScreen",
44 | "", "",
45 | "",
46 | "", "", "", "", "", "", "", "", "", "",
47 | "", "",
48 | "", "", "",
49 | "",
50 | "", "", "", "",
51 | "", "", "",
52 | "", "",
53 | "",
54 | }
55 |
56 | var numLockCodes = []string{
57 | "",
58 | "", "", "", "", "", "", "", "", "", "", "", "", "", "",
59 | "", "", "", "", "", "", "", "", "", "", "", "", "",
60 | "",
61 | "",
62 | "", "", "", "", "", "", "", "", "", "", "",
63 | "",
64 | "", "",
65 | "", "", "", "", "", "", "", "", "", "", "",
66 | "",
67 | "", "",
68 | "",
69 | "", "", "", "", "", "", "", "", "", "",
70 | "", "",
71 | "Home", "Up", "PageUp",
72 | "",
73 | "Left", "", "Right", "",
74 | "End", "Down", "PageDown",
75 | "Ins", "Del",
76 | "",
77 | }
78 |
79 | var escapeTable = map[string][]int{
80 | "Keypad_Enter": []int{0xe0, 0x1c},
81 | "RCtrl": []int{0xe0, 0x1d},
82 | "Keypad_/": []int{0xe0, 0x35},
83 | "Ctrl_PrintScreen": []int{0xe0, 0x37},
84 | "RAlt": []int{0xe0, 0x38},
85 | "Ctrl_Break": []int{0xe0, 0x46},
86 | "LeftWindow": []int{0xe0, 0x5b},
87 | "RightWindow": []int{0xe0, 0x5c},
88 | "Menu": []int{0xe0, 0x5d},
89 | "Power": []int{0xe0, 0x5e},
90 | "Sleep": []int{0xe0, 0x5f},
91 | "Wake": []int{0xe0, 0x63},
92 | }
93 |
--------------------------------------------------------------------------------
/scancodes/table_test.go:
--------------------------------------------------------------------------------
1 | package scancodes
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestBaseTable(t *testing.T) {
8 | if len(baseCodes) != 0x55 {
9 | t.Errorf("Table misses %d entries", 0x55 - len(baseCodes))
10 | }
11 | if baseCodes[0x10] != "Q" {
12 | t.Error("Misalignment before Q")
13 | }
14 | if baseCodes[0x1e] != "A" {
15 | t.Error("Misalignment between Q-A")
16 | }
17 | if baseCodes[0x2c] != "Z" {
18 | t.Error("Misalignment between A-Z")
19 | }
20 | if baseCodes[0x3b] != "F1" {
21 | t.Error("Misalignment betwen Z-F1")
22 | }
23 | if baseCodes[0x47] != "Keypad_7" {
24 | t.Error("Misalignment between F1-Keypad_7")
25 | }
26 | }
27 | func TestShiftTable(t *testing.T) {
28 | if len(shiftCodes) != len(baseCodes) {
29 | t.Errorf("Table misses %d entries", len(baseCodes) - len(shiftCodes))
30 | }
31 | if shiftCodes[0x10] != "Q" {
32 | t.Error("Misalignment before Q")
33 | }
34 | if shiftCodes[0x1e] != "A" {
35 | t.Error("Misalignment between Q-A")
36 | }
37 | if shiftCodes[0x2c] != "Z" {
38 | t.Error("Misalignment between A-Z")
39 | }
40 | if shiftCodes[0x37] != "PrintScreen" {
41 | t.Error("Misalignment betwen Z-PrintScreen")
42 | }
43 | }
44 | func TestNumLockTable(t *testing.T) {
45 | if len(numLockCodes) != len(baseCodes) {
46 | t.Errorf("Table misses %d entries", len(baseCodes) - len(numLockCodes))
47 | }
48 | if numLockCodes[0x47] != "Home" {
49 | t.Error("Misalignment before Home")
50 | }
51 | if numLockCodes[0x53] != "Del" {
52 | t.Error("Misalignment between Home-Del")
53 | }
54 | }
55 |
56 |
57 |
--------------------------------------------------------------------------------
/src/C/x11.c:
--------------------------------------------------------------------------------
1 | #include // (libX11-devel | libx11-dev) + (libXmu-devel | libxmu-dev >> WinUtil.h)
2 | #include // Query windows (focus, name, etc.)
3 | #include // Switch window language ("layout")
4 |
5 | Bool xerror = False;
6 |
7 | extern int handle_error(Display* display, XErrorEvent* error) {
8 | xerror = True;
9 | return 1;
10 | }
11 |
12 | void set_handle_error() {
13 | XSetErrorHandler(handle_error);
14 | }
15 |
--------------------------------------------------------------------------------
/src/keybd_event/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 MicMonay
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 |
--------------------------------------------------------------------------------
/src/keybd_event/README.md:
--------------------------------------------------------------------------------
1 | # keybd_event
2 |
3 | [](https://pkg.go.dev/github.com/micmonay/keybd_event)
4 |
5 | This library simulates the key press on a keyboard. It runs on Linux, Windows and Mac.
6 |
7 | **Important :**
8 | - The keys change in the different keyboard layouts of the target computer(s).
9 | - I have tested this code on my system and I don't find any errors. If you have a bug, please create an issue.
10 |
11 |
12 | ### Example :
13 | ```go
14 | package main
15 |
16 | import (
17 | "runtime"
18 | "time"
19 | "github.com/micmonay/keybd_event"
20 | )
21 |
22 | func main() {
23 | kb, err := keybd_event.NewKeyBonding()
24 | if err != nil {
25 | panic(err)
26 | }
27 |
28 | // For linux, it is very important to wait 2 seconds
29 | if runtime.GOOS == "linux" {
30 | time.Sleep(2 * time.Second)
31 | }
32 |
33 | // Select keys to be pressed
34 | kb.SetKeys(keybd_event.VK_A, keybd_event.VK_B)
35 |
36 | // Set shift to be pressed
37 | kb.HasSHIFT(true)
38 |
39 | // Press the selected keys
40 | err = kb.Launching()
41 | if err != nil {
42 | panic(err)
43 | }
44 |
45 | // Or you can use Press and Release
46 | kb.Press()
47 | time.Sleep(10 * time.Millisecond)
48 | kb.Release()
49 |
50 | // Here, the program will generate "ABAB" as if they were pressed on the keyboard.
51 | }
52 | ```
53 |
54 | For easy access to all the keys on the virtual keyboard, I have added more special keycodes constants `VK_SP*`.
55 |
56 | Below is an illustration showing the "VK_" symbols for each key on the keyboard:
57 | 
58 |
59 | ## Linux
60 |
61 | On Linux this library uses **uinput**, which on the major distributions requires root permissions.
62 |
63 | The easy solution is executing through root user (by using `sudo`). A worse way is by changing the executable's permissions by using `chmod`.
64 |
65 | ### Secure Linux Example
66 | ```bash
67 | sudo groupadd uinput
68 | sudo usermod -a -G uinput my_username
69 | sudo udevadm control --reload-rules
70 | echo "SUBSYSTEM==\"misc\", KERNEL==\"uinput\", GROUP=\"uinput\", MODE=\"0660\"" | sudo tee /etc/udev/rules.d/uinput.rules
71 | echo uinput | sudo tee /etc/modules-load.d/uinput.conf
72 | ```
73 |
74 | Another subtlety on Linux: it is important after creating the `keybd_event` to **wait 2 seconds before running first keyboard actions**.
75 |
76 | ## Darwin (MacOS)
77 | This library depends on Apple's frameworks, and I did not find a solution to cross-compile from another OS to MacOS.
78 |
--------------------------------------------------------------------------------
/src/keybd_event/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/micmonay/keybd_event
2 |
3 | go 1.16
4 |
--------------------------------------------------------------------------------
/src/keybd_event/keybd_darwin.go:
--------------------------------------------------------------------------------
1 | package keybd_event
2 |
3 | /*
4 | #cgo CFLAGS: -x objective-c
5 | #cgo LDFLAGS: -framework Cocoa
6 | #import
7 | #import
8 | CGEventRef CreateDown(int k){
9 | CGEventRef event = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)k, true);
10 | return event;
11 | }
12 | CGEventRef CreateUp(int k){
13 | CGEventRef event = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)k, false);
14 | return event;
15 | }
16 | void KeyTap(CGEventRef event){
17 | CGEventPost(kCGAnnotatedSessionEventTap, event);
18 | CFRelease(event);
19 | }
20 | void AddActionKey(CGEventFlags type,CGEventRef event){
21 | CGEventSetFlags(event, type);
22 | }
23 | */
24 | import "C"
25 | import "time"
26 |
27 | const (
28 | _AShift = C.kCGEventFlagMaskAlphaShift
29 | _VK_SHIFT = C.kCGEventFlagMaskShift
30 | _VK_CTRL = C.kCGEventFlagMaskControl
31 | _VK_ALT = C.kCGEventFlagMaskAlternate
32 | _VK_CMD = C.kCGEventFlagMaskCommand
33 | _Help = C.kCGEventFlagMaskHelp
34 | _VK_FN = C.kCGEventFlagMaskSecondaryFn
35 | _NumPad = C.kCGEventFlagMaskNumericPad
36 | _Coalesced = C.kCGEventFlagMaskNonCoalesced
37 | _VK_Control = 0x3B
38 | _VK_RightShift = 0x3C
39 | _VK_RightControl = 0x3E
40 | _VK_Command = 0x37
41 | _VK_Shift = 0x38
42 | )
43 |
44 | func initKeyBD() error { return nil }
45 |
46 | // Press key(s)
47 | func (k *KeyBonding) Press() error {
48 | for _, key := range k.keys {
49 | k.keyPress(key)
50 | }
51 | return nil
52 | }
53 |
54 | // Release key(s)
55 | func (k *KeyBonding) Release() error {
56 | for _, key := range k.keys {
57 | k.keyRelease(key)
58 | }
59 | return nil
60 | }
61 |
62 | // Launch key bounding
63 | func (k *KeyBonding) Launching() error {
64 |
65 | for _, key := range k.keys {
66 | k.tapKey(key)
67 | }
68 | return nil
69 | }
70 | func altgr(event C.CGEventRef) {
71 | alt(event)
72 | }
73 | func shift(event C.CGEventRef) {
74 | C.AddActionKey(_VK_SHIFT, event)
75 | }
76 | func ctrl(event C.CGEventRef) {
77 | C.AddActionKey(_VK_CTRL, event)
78 | }
79 | func alt(event C.CGEventRef) {
80 | C.AddActionKey(_VK_ALT, event)
81 | }
82 | func cmd(event C.CGEventRef) {
83 | C.AddActionKey(_VK_CMD, event)
84 | }
85 | func (k KeyBonding) keyPress(key int) {
86 | downEvent := C.CreateDown(C.int(key))
87 | if k.hasALT {
88 | alt(downEvent)
89 | }
90 | if k.hasCTRL {
91 | ctrl(downEvent)
92 | }
93 | if k.hasSHIFT {
94 | shift(downEvent)
95 | }
96 | if k.hasRCTRL { //not support on mac
97 | ctrl(downEvent)
98 | }
99 | if k.hasRSHIFT { //not support on mac
100 | shift(downEvent)
101 | }
102 | if k.hasALTGR {
103 | altgr(downEvent)
104 | }
105 | if k.hasSuper {
106 | cmd(downEvent)
107 | }
108 | C.KeyTap(downEvent)
109 | }
110 | func (k KeyBonding) keyRelease(key int) {
111 | upEvent := C.CreateUp(C.int(key))
112 | if k.hasALT {
113 | alt(upEvent)
114 | }
115 | if k.hasCTRL {
116 | ctrl(upEvent)
117 | }
118 | if k.hasSHIFT {
119 | shift(upEvent)
120 | }
121 | if k.hasRCTRL { //not support on mac
122 | ctrl(upEvent)
123 | }
124 | if k.hasRSHIFT { //not support on mac
125 | shift(upEvent)
126 | }
127 | if k.hasALTGR {
128 | altgr(upEvent)
129 | }
130 | if k.hasSuper {
131 | cmd(upEvent)
132 | }
133 | C.KeyTap(upEvent)
134 | }
135 | func (k KeyBonding) tapKey(key int) {
136 | k.keyPress(key)
137 | time.Sleep(100 * time.Millisecond) //ignore if speed is most in my test system
138 | k.keyRelease(key)
139 | }
140 |
141 | const (
142 | VK_SP1 = 0x0A
143 | VK_SP2 = 0x1B
144 | VK_SP3 = 0x18
145 | VK_SP4 = 0x21
146 | VK_SP5 = 0x1E
147 | VK_SP6 = 0x29
148 | VK_SP7 = 0x27
149 | VK_SP8 = 0x2A
150 | VK_SP9 = 0x2B
151 | VK_SP10 = 0x2F
152 | VK_SP11 = 0x2C
153 | VK_SP12 = 0x32
154 |
155 | VK_A = 0x00
156 | VK_S = 0x01
157 | VK_D = 0x02
158 | VK_F = 0x03
159 | VK_H = 0x04
160 | VK_G = 0x05
161 | VK_Z = 0x06
162 | VK_X = 0x07
163 | VK_C = 0x08
164 | VK_V = 0x09
165 | VK_B = 0x0B
166 | VK_Q = 0x0C
167 | VK_W = 0x0D
168 | VK_E = 0x0E
169 | VK_R = 0x0F
170 | VK_Y = 0x10
171 | VK_T = 0x11
172 | VK_1 = 0x12
173 | VK_2 = 0x13
174 | VK_3 = 0x14
175 | VK_4 = 0x15
176 | VK_6 = 0x16
177 | VK_5 = 0x17
178 | VK_EQUAL = 0x18
179 | VK_9 = 0x19
180 | VK_7 = 0x1A
181 | VK_MINUS = 0x1B
182 | VK_8 = 0x1C
183 | VK_0 = 0x1D
184 | VK_RightBracket = 0x1E
185 | VK_O = 0x1F
186 | VK_U = 0x20
187 | VK_LeftBracket = 0x21
188 | VK_I = 0x22
189 | VK_P = 0x23
190 | VK_L = 0x25
191 | VK_J = 0x26
192 | VK_Quote = 0x27
193 | VK_K = 0x28
194 | VK_SEMICOLON = 0x29
195 | VK_BACKSLASH = 0x2A
196 | VK_COMMA = 0x2B
197 | VK_SLASH = 0x2C
198 | VK_N = 0x2D
199 | VK_M = 0x2E
200 | VK_Period = 0x2F
201 | VK_GRAVE = 0x32
202 | VK_KeypadDecimal = 0x41
203 | VK_KeypadMultiply = 0x43
204 | VK_KeypadPlus = 0x45
205 | VK_KeypadClear = 0x47
206 | VK_KeypadDivide = 0x4B
207 | VK_KeypadEnter = 0x4C
208 | VK_KeypadMinus = 0x4E
209 | VK_KeypadEquals = 0x51
210 | VK_Keypad0 = 0x52
211 | VK_Keypad1 = 0x53
212 | VK_Keypad2 = 0x54
213 | VK_Keypad3 = 0x55
214 | VK_Keypad4 = 0x56
215 | VK_Keypad5 = 0x57
216 | VK_Keypad6 = 0x58
217 | VK_Keypad7 = 0x59
218 | VK_Keypad8 = 0x5B
219 | VK_Keypad9 = 0x5C
220 |
221 | VK_ENTER = 0x24
222 | VK_TAB = 0x30
223 | VK_SPACE = 0x31
224 | VK_DELETE = 0x33
225 | VK_ESC = 0x35
226 | VK_CAPSLOCK = 0x39
227 | VK_Option = 0x3A
228 | VK_RightOption = 0x3D
229 | VK_Function = 0x3F
230 | VK_F17 = 0x40
231 | VK_VOLUMEUP = 0x48
232 | VK_VOLUMEDOWN = 0x49
233 | VK_MUTE = 0x4A
234 | VK_F18 = 0x4F
235 | VK_F19 = 0x50
236 | VK_F20 = 0x5A
237 | VK_F5 = 0x60
238 | VK_F6 = 0x61
239 | VK_F7 = 0x62
240 | VK_F3 = 0x63
241 | VK_F8 = 0x64
242 | VK_F9 = 0x65
243 | VK_F11 = 0x67
244 | VK_F13 = 0x69
245 | VK_F16 = 0x6A
246 | VK_F14 = 0x6B
247 | VK_F10 = 0x6D
248 | VK_F12 = 0x6F
249 | VK_F15 = 0x71
250 | VK_HELP = 0x72
251 | VK_HOME = 0x73
252 | VK_PAGEUP = 0x74
253 | VK_ForwardDelete = 0x75
254 | VK_F4 = 0x76
255 | VK_END = 0x77
256 | VK_F2 = 0x78
257 | VK_PAGEDOWN = 0x79
258 | VK_F1 = 0x7A
259 | VK_LEFT = 0x7B
260 | VK_RIGHT = 0x7C
261 | VK_DOWN = 0x7D
262 | VK_UP = 0x7E
263 | )
264 |
--------------------------------------------------------------------------------
/src/keybd_event/keybd_event.go:
--------------------------------------------------------------------------------
1 | // Package keybd_event is used for a key press simulated in Windows, Linux and Mac
2 | package keybd_event
3 |
4 | //KeyBonding type for keybd_event
5 | type KeyBonding struct {
6 | hasCTRL bool
7 | hasALT bool
8 | hasSHIFT bool
9 | hasRCTRL bool
10 | hasRSHIFT bool
11 | hasALTGR bool
12 | hasSuper bool
13 | keys []int
14 | }
15 |
16 | //NewKeyBonding Use for create struct KeyBounding
17 | func NewKeyBonding() (KeyBonding, error) {
18 | keyBounding := KeyBonding{}
19 | keyBounding.Clear()
20 | err := initKeyBD()
21 | if err != nil {
22 | return keyBounding, err
23 | }
24 | return keyBounding, nil
25 | }
26 |
27 | //Clear clean instance
28 | func (k *KeyBonding) Clear() {
29 | k.hasALT = false
30 | k.hasCTRL = false
31 | k.hasSHIFT = false
32 | k.hasRCTRL = false
33 | k.hasRSHIFT = false
34 | k.hasALTGR = false
35 | k.hasSuper = false
36 | k.keys = []int{}
37 | }
38 |
39 | //SetKeys set keys
40 | func (k *KeyBonding) SetKeys(keys ...int) {
41 | k.keys = keys
42 | }
43 |
44 | //AddKey add one key pressed
45 | func (k *KeyBonding) AddKey(key int) {
46 | k.keys = append(k.keys, key)
47 | }
48 |
49 | //HasALT If key ALT pressed
50 | func (k *KeyBonding) HasALT(b bool) {
51 | k.hasALT = b
52 | }
53 |
54 | //HasCTRL If key CTRL pressed
55 | func (k *KeyBonding) HasCTRL(b bool) {
56 | k.hasCTRL = b
57 | }
58 |
59 | //HasSHIFT If key SHIFT pressed
60 | func (k *KeyBonding) HasSHIFT(b bool) {
61 | k.hasSHIFT = b
62 | }
63 |
64 | //HasALTGR If key ALTGR pressed
65 | func (k *KeyBonding) HasALTGR(b bool) {
66 | k.hasALTGR = b
67 | }
68 |
69 | //HasSuper If key Super pressed
70 | func (k *KeyBonding) HasSuper(b bool) {
71 | k.hasSuper = b
72 | }
73 |
74 | //HasCTRLR If key CTRLR pressed
75 | //
76 | //This is currently not supported on macOS
77 | func (k *KeyBonding) HasCTRLR(b bool) {
78 | k.hasRCTRL = b
79 | }
80 |
81 | //HasSHIFTR If key SHIFTR pressed
82 | //
83 | //This is currently not supported on macOS
84 | func (k *KeyBonding) HasSHIFTR(b bool) {
85 | k.hasRSHIFT = b
86 | }
87 |
--------------------------------------------------------------------------------
/src/keybd_event/keybd_event_test.go:
--------------------------------------------------------------------------------
1 | package keybd_event_test
2 |
3 | import (
4 | "runtime"
5 | "time"
6 |
7 | "github.com/micmonay/keybd_event"
8 | )
9 |
10 | func ExampleNewKeyBonding() {
11 | kb, err := keybd_event.NewKeyBonding()
12 | if err != nil {
13 | panic(err)
14 | }
15 |
16 | // For linux, it is very important to wait 2 seconds
17 | if runtime.GOOS == "linux" {
18 | time.Sleep(2 * time.Second)
19 | }
20 |
21 | // Select keys to be pressed
22 | kb.SetKeys(keybd_event.VK_A, keybd_event.VK_B)
23 |
24 | // Set shift to be pressed
25 | kb.HasSHIFT(true)
26 |
27 | // Press the selected keys
28 | err = kb.Launching()
29 | if err != nil {
30 | panic(err)
31 | }
32 |
33 | // Or you can use Press and Release
34 | kb.Press()
35 | time.Sleep(10 * time.Millisecond)
36 | kb.Release()
37 |
38 | // Here, the program will generate "ABAB" as if they were pressed on the keyboard.
39 |
40 | // Output:
41 | }
42 |
--------------------------------------------------------------------------------
/src/keybd_event/keybd_linux.go:
--------------------------------------------------------------------------------
1 | package keybd_event
2 |
3 | /*
4 | #include
5 | */
6 | import "C"
7 | import (
8 | "encoding/binary"
9 | "errors"
10 | "os"
11 | "syscall"
12 | )
13 |
14 | type uinput_user_dev C.struct_uinput_user_dev
15 | type timeval C.struct_timeval
16 | type input_event C.struct_input_event
17 |
18 | var fd *os.File
19 | var X11 = true
20 |
21 | const (
22 | _EV_KEY = C.EV_KEY
23 | _EV_SYN = C.EV_SYN
24 | _UI_SET_EVBIT = C.UI_SET_EVBIT
25 | _UI_SET_KEYBIT = C.UI_SET_KEYBIT
26 | _UI_DEV_CREATE = C.UI_DEV_CREATE
27 | _UI_DEV_DESTROY = C.UI_DEV_DESTROY
28 | _UINPUT_MAX_NAME_SIZE = C.UINPUT_MAX_NAME_SIZE
29 | _VK_LEFTCTRL = 29
30 | _VK_RIGHTCTRL = 97
31 | _VK_CTRL = 29
32 | _VK_LEFTSHIFT = 42
33 | _VK_RIGHTSHIFT = 54
34 | _VK_SHIFT = 42
35 | _VK_LEFTALT = 56
36 | _VK_RIGHTALT = 100
37 | _VK_ALT = 56
38 | _VK_LEFTMETA = 125
39 | _VK_RIGHTMETA = 126
40 | )
41 |
42 | func initKeyBD() error {
43 | if fd != nil {
44 | return nil
45 | }
46 | path, err := getFileUInput()
47 | if err != nil {
48 | return err
49 | }
50 | fdInit, err := os.OpenFile(path, os.O_WRONLY|syscall.O_NONBLOCK, os.ModeDevice)
51 | fd = fdInit
52 | if err != nil {
53 | if os.IsPermission(err) {
54 | return errors.New("permission error for " + path + " try cmd : sudo chmod +0666 " + path)
55 | } else {
56 | return err
57 | }
58 | }
59 | _, _, errCall := syscall.Syscall(syscall.SYS_IOCTL, fd.Fd(), _UI_SET_EVBIT, uintptr(_EV_KEY))
60 | if errCall != 0 {
61 | return err
62 | }
63 | _, _, errCall = syscall.Syscall(syscall.SYS_IOCTL, fd.Fd(), _UI_SET_EVBIT, uintptr(_EV_SYN))
64 | if errCall != 0 {
65 | return err
66 | }
67 | keyEventSet()
68 | uidev := uinput_user_dev{}
69 | for i, c := range "keybd interface" {
70 | uidev.name[i] = C.char(c)
71 | }
72 | uidev.id.bustype = C.BUS_USB
73 | uidev.id.vendor = 0x1
74 | uidev.id.product = 0x1
75 | uidev.id.version = 0x1
76 | err = binary.Write(fd, binary.LittleEndian, &uidev)
77 | if err != nil {
78 | return err
79 | }
80 | //Create device
81 | _, _, errCall = syscall.Syscall(syscall.SYS_IOCTL, fd.Fd(), _UI_DEV_CREATE, 0)
82 | if errCall != 0 {
83 | return err
84 | }
85 | return nil
86 | }
87 |
88 | //actualy don't use
89 | func destroyLinuxUInput() {
90 | syscall.Syscall(syscall.SYS_IOCTL, fd.Fd(), _UI_DEV_DESTROY, 0)
91 | fd.Close()
92 | }
93 | func getFileUInput() (string, error) {
94 | if _, err := os.Stat("/dev/uinput"); err == nil {
95 | return "/dev/uinput", nil
96 | }
97 | if _, err := os.Stat("/dev/input/uinput"); err == nil {
98 | return "/dev/input/uinput", nil
99 | }
100 | err := errors.New("Not found uinput file. Try this cmd 'sudo modprobe uinput'")
101 | return "", err
102 | }
103 |
104 | // Press key(s)
105 | func (k *KeyBonding) Press() error {
106 | var err error
107 | if k.hasALT {
108 | err = downKey(_VK_ALT)
109 | if err != nil {
110 | return err
111 | }
112 | }
113 | if k.hasSHIFT {
114 | err = downKey(_VK_SHIFT)
115 | if err != nil {
116 | return err
117 | }
118 | }
119 | if k.hasCTRL {
120 | err = downKey(_VK_CTRL)
121 | if err != nil {
122 | return err
123 | }
124 | }
125 | if k.hasRSHIFT {
126 | err = downKey(_VK_RIGHTSHIFT)
127 | if err != nil {
128 | return err
129 | }
130 | }
131 | if k.hasRCTRL {
132 | err = downKey(_VK_RIGHTCTRL)
133 | if err != nil {
134 | return err
135 | }
136 | }
137 | if k.hasALTGR {
138 | err = downKey(_VK_RIGHTALT)
139 | if err != nil {
140 | return err
141 | }
142 | }
143 | if k.hasSuper {
144 | err = downKey(_VK_LEFTMETA)
145 | if err != nil {
146 | return err
147 | }
148 | }
149 | for _, key := range k.keys {
150 | err = downKey(key)
151 | if err != nil {
152 | return err
153 | }
154 | }
155 | err = sync()
156 | if err != nil {
157 | return err
158 | }
159 | return nil
160 | }
161 |
162 | // Release key(s)
163 | func (k *KeyBonding) Release() error {
164 | var err error
165 | if k.hasALT {
166 | err = upKey(_VK_ALT)
167 | if err != nil {
168 | return err
169 | }
170 | }
171 | if k.hasSHIFT {
172 | err = upKey(_VK_SHIFT)
173 | if err != nil {
174 | return err
175 | }
176 | }
177 | if k.hasCTRL {
178 | err = upKey(_VK_CTRL)
179 | if err != nil {
180 | return err
181 | }
182 | }
183 | if k.hasRSHIFT {
184 | err = upKey(_VK_RIGHTSHIFT)
185 | if err != nil {
186 | return err
187 | }
188 | }
189 | if k.hasRCTRL {
190 | err = upKey(_VK_RIGHTCTRL)
191 | if err != nil {
192 | return err
193 | }
194 | }
195 | if k.hasALTGR {
196 | err = upKey(_VK_RIGHTALT)
197 | if err != nil {
198 | return err
199 | }
200 | }
201 | if k.hasSuper {
202 | err := upKey(_VK_LEFTMETA)
203 | if err != nil {
204 | return err
205 | }
206 | }
207 | for _, key := range k.keys {
208 | err = upKey(key)
209 | if err != nil {
210 | return err
211 | }
212 | }
213 | err = sync()
214 | if err != nil {
215 | return err
216 | }
217 | //Destroy device
218 |
219 | return nil
220 | }
221 |
222 | // Launch key bounding
223 | func (k *KeyBonding) Launching() error {
224 | k.Press()
225 | //key up
226 | k.Release()
227 | return nil
228 | }
229 | func keyEventSet() error {
230 | for i := 0; i < 256; i++ {
231 | _, _, errCall := syscall.Syscall(syscall.SYS_IOCTL, fd.Fd(), _UI_SET_KEYBIT, uintptr(i))
232 | if errCall != 0 {
233 | return errCall
234 | }
235 | }
236 | return nil
237 | }
238 | func downKey(key int) error {
239 | ev := input_event{}
240 | ev._type = _EV_KEY
241 | ev.code = C.__u16(key)
242 | ev.value = 1
243 | err := binary.Write(fd, binary.LittleEndian, &ev)
244 | if err != nil {
245 | return err
246 | }
247 | return nil
248 | }
249 | func sync() error {
250 | ev := input_event{}
251 | ev._type = _EV_SYN
252 | ev.code = 0
253 | ev.value = 0
254 | err := binary.Write(fd, binary.LittleEndian, &ev)
255 | if err != nil {
256 | return err
257 | }
258 | return nil
259 | }
260 | func upKey(key int) error {
261 | ev := input_event{}
262 | ev._type = _EV_KEY
263 | ev.code = C.__u16(key)
264 | ev.value = 0
265 | err := binary.Write(fd, binary.LittleEndian, &ev)
266 | if err != nil {
267 | return err
268 | }
269 | return nil
270 | }
271 |
272 | const (
273 | VK_SP1 = 41
274 | VK_SP2 = 12
275 | VK_SP3 = 13
276 | VK_SP4 = 26
277 | VK_SP5 = 27
278 | VK_SP6 = 39
279 | VK_SP7 = 40
280 | VK_SP8 = 43
281 | VK_SP9 = 51
282 | VK_SP10 = 52
283 | VK_SP11 = 53
284 | VK_SP12 = 86
285 |
286 | VK_UP = 103
287 | VK_DOWN = 108
288 | VK_LEFT = 105
289 | VK_RIGHT = 106
290 |
291 | VK_ESC = 1
292 | VK_1 = 2
293 | VK_2 = 3
294 | VK_3 = 4
295 | VK_4 = 5
296 | VK_5 = 6
297 | VK_6 = 7
298 | VK_7 = 8
299 | VK_8 = 9
300 | VK_9 = 10
301 | VK_0 = 11
302 | VK_Q = 16
303 | VK_W = 17
304 | VK_E = 18
305 | VK_R = 19
306 | VK_T = 20
307 | VK_Y = 21
308 | VK_U = 22
309 | VK_I = 23
310 | VK_O = 24
311 | VK_P = 25
312 | VK_A = 30
313 | VK_S = 31
314 | VK_D = 32
315 | VK_F = 33
316 | VK_G = 34
317 | VK_H = 35
318 | VK_J = 36
319 | VK_K = 37
320 | VK_L = 38
321 | VK_Z = 44
322 | VK_X = 45
323 | VK_C = 46
324 | VK_V = 47
325 | VK_B = 48
326 | VK_N = 49
327 | VK_M = 50
328 | VK_F1 = 59
329 | VK_F2 = 60
330 | VK_F3 = 61
331 | VK_F4 = 62
332 | VK_F5 = 63
333 | VK_F6 = 64
334 | VK_F7 = 65
335 | VK_F8 = 66
336 | VK_F9 = 67
337 | VK_F10 = 68
338 | VK_F11 = 87
339 | VK_F12 = 88
340 |
341 | VK_NUMLOCK = 69
342 | VK_SCROLLLOCK = 70
343 | VK_RESERVED = 0
344 | VK_MINUS = 12
345 | VK_EQUAL = 13
346 | VK_BACKSPACE = 14
347 | VK_TAB = 15
348 | VK_LEFTBRACE = 26
349 | VK_RIGHTBRACE = 27
350 | VK_ENTER = 28
351 | VK_SEMICOLON = 39
352 | VK_APOSTROPHE = 40
353 | VK_GRAVE = 41
354 | VK_BACKSLASH = 43
355 | VK_COMMA = 51
356 | VK_DOT = 52
357 | VK_SLASH = 53
358 | VK_SPACE = 57
359 | VK_CAPSLOCK = 58
360 |
361 | VK_KP0 = 82
362 | VK_KP1 = 79
363 | VK_KP2 = 80
364 | VK_KP3 = 81
365 | VK_KP4 = 75
366 | VK_KP5 = 76
367 | VK_KP6 = 77
368 | VK_KP7 = 71
369 | VK_KP8 = 72
370 | VK_KP9 = 73
371 | VK_KPMINUS = 74
372 | VK_KPPLUS = 78
373 | VK_KPDOT = 83
374 | VK_KPJPCOMMA = 95
375 | VK_KPENTER = 96
376 | VK_KPSLASH = 98
377 | VK_KPASTERISK = 55
378 | VK_KPEQUAL = 117
379 | VK_KPPLUSMINUS = 118
380 | VK_KPCOMMA = 121
381 |
382 | VK_ZENKAKUHANKAKU = 85
383 | VK_102ND = 86
384 | VK_RO = 89
385 | VK_KATAKANA = 90
386 | VK_HIRAGANA = 91
387 | VK_HENKAN = 92
388 | VK_KATAKANAHIRAGANA = 93
389 | VK_MUHENKAN = 94
390 | VK_SYSRQ = 99
391 | VK_LINEFEED = 101
392 | VK_HOME = 102
393 | VK_PAGEUP = 104
394 | VK_END = 107
395 | VK_PAGEDOWN = 109
396 | VK_INSERT = 110
397 | VK_DELETE = 111
398 | VK_MACRO = 112
399 | VK_MUTE = 113
400 | VK_VOLUMEDOWN = 114
401 | VK_VOLUMEUP = 115
402 | VK_POWER = 116 /* SC System Power Down */
403 | VK_PAUSE = 119
404 | VK_SCALE = 120 /* AL Compiz Scale (Expose) */
405 |
406 | VK_HANGEUL = 122
407 | VK_HANGUEL = VK_HANGEUL
408 | VK_HANJA = 123
409 | VK_YEN = 124
410 | VK_LEFTMETA = 125
411 | VK_RIGHTMETA = 126
412 | VK_COMPOSE = 127
413 |
414 | VK_STOP = 128 /* AC Stop */
415 | VK_AGAIN = 129
416 | VK_PROPS = 130 /* AC Properties */
417 | VK_UNDO = 131 /* AC Undo */
418 | VK_FRONT = 132
419 | VK_COPY = 133 /* AC Copy */
420 | VK_OPEN = 134 /* AC Open */
421 | VK_PASTE = 135 /* AC Paste */
422 | VK_FIND = 136 /* AC Search */
423 | VK_CUT = 137 /* AC Cut */
424 | VK_HELP = 138 /* AL Integrated Help Center */
425 | VK_MENU = 139 /* Menu (show menu) */
426 | VK_CALC = 140 /* AL Calculator */
427 | VK_SETUP = 141
428 | VK_SLEEP = 142 /* SC System Sleep */
429 | VK_WAKEUP = 143 /* System Wake Up */
430 | VK_FILE = 144 /* AL Local Machine Browser */
431 | VK_SENDFILE = 145
432 | VK_DELETEFILE = 146
433 | VK_XFER = 147
434 | VK_PROG1 = 148
435 | VK_PROG2 = 149
436 | VK_WWW = 150 /* AL Internet Browser */
437 | VK_MSDOS = 151
438 | VK_COFFEE = 152 /* AL Terminal Lock/Screensaver */
439 | VK_SCREENLOCK = VK_COFFEE
440 | VK_ROTATE_DISPLAY = 153 /* Display orientation for e.g. tablets */
441 | VK_DIRECTION = VK_ROTATE_DISPLAY
442 | VK_CYCLEWINDOWS = 154
443 | VK_MAIL = 155
444 | VK_BOOKMARKS = 156 /* AC Bookmarks */
445 | VK_COMPUTER = 157
446 | VK_BACK = 158 /* AC Back */
447 | VK_FORWARD = 159 /* AC Forward */
448 | VK_CLOSECD = 160
449 | VK_EJECTCD = 161
450 | VK_EJECTCLOSECD = 162
451 | VK_NEXTSONG = 163
452 | VK_PLAYPAUSE = 164
453 | VK_PREVIOUSSONG = 165
454 | VK_STOPCD = 166
455 | VK_RECORD = 167
456 | VK_REWIND = 168
457 | VK_PHONE = 169 /* Media Select Telephone */
458 | VK_ISO = 170
459 | VK_CONFIG = 171 /* AL Consumer Control Configuration */
460 | VK_HOMEPAGE = 172 /* AC Home */
461 | VK_REFRESH = 173 /* AC Refresh */
462 | VK_EXIT = 174 /* AC Exit */
463 | VK_MOVE = 175
464 | VK_EDIT = 176
465 | VK_SCROLLUP = 177
466 | VK_SCROLLDOWN = 178
467 | VK_KPLEFTPAREN = 179
468 | VK_KPRIGHTPAREN = 180
469 | VK_NEW = 181 /* AC New */
470 | VK_REDO = 182 /* AC Redo/Repeat */
471 |
472 | VK_F13 = 183
473 | VK_F14 = 184
474 | VK_F15 = 185
475 | VK_F16 = 186
476 | VK_F17 = 187
477 | VK_F18 = 188
478 | VK_F19 = 189
479 | VK_F20 = 190
480 | VK_F21 = 191
481 | VK_F22 = 192
482 | VK_F23 = 193
483 | VK_F24 = 194
484 |
485 | VK_PLAYCD = 200
486 | VK_PAUSECD = 201
487 | VK_PROG3 = 202
488 | VK_PROG4 = 203
489 | VK_DASHBOARD = 204 /* AL Dashboard */
490 | VK_SUSPEND = 205
491 | VK_CLOSE = 206 /* AC Close */
492 | VK_PLAY = 207
493 | VK_FASTFORWARD = 208
494 | VK_BASSBOOST = 209
495 | VK_PRINT = 210 /* AC Print */
496 | VK_HP = 211
497 | VK_CAMERA = 212
498 | VK_SOUND = 213
499 | VK_QUESTION = 214
500 | VK_EMAIL = 215
501 | VK_CHAT = 216
502 | VK_SEARCH = 217
503 | VK_CONNECT = 218
504 | VK_FINANCE = 219 /* AL Checkbook/Finance */
505 | VK_SPORT = 220
506 | VK_SHOP = 221
507 | VK_ALTERASE = 222
508 | VK_CANCEL = 223 /* AC Cancel */
509 | VK_BRIGHTNESSDOWN = 224
510 | VK_BRIGHTNESSUP = 225
511 | VK_MEDIA = 226
512 |
513 | VK_SWITCHVIDEOMODE = 227 /* Cycle between available video
514 | outputs (Monitor/LCD/TV-out/etc) */
515 | VK_KBDILLUMTOGGLE = 228
516 | VK_KBDILLUMDOWN = 229
517 | VK_KBDILLUMUP = 230
518 |
519 | VK_SEND = 231 /* AC Send */
520 | VK_REPLY = 232 /* AC Reply */
521 | VK_FORWARDMAIL = 233 /* AC Forward Msg */
522 | VK_SAVE = 234 /* AC Save */
523 | VK_DOCUMENTS = 235
524 |
525 | VK_BATTERY = 236
526 |
527 | VK_BLUETOOTH = 237
528 | VK_WLAN = 238
529 | VK_UWB = 239
530 |
531 | VK_UNKNOWN = 240
532 |
533 | VK_VIDEO_NEXT = 241 /* drive next video source */
534 | VK_VIDEO_PREV = 242 /* drive previous video source */
535 | VK_BRIGHTNESS_CYCLE = 243 /* brightness up, after max is min */
536 | VK_BRIGHTNESS_AUTO = 244 /* Set Auto Brightness: manual
537 | brightness control is off,
538 | rely on ambient */
539 | VK_BRIGHTNESS_ZERO = VK_BRIGHTNESS_AUTO
540 | VK_DISPLAY_OFF = 245 /* display device to off state */
541 |
542 | VK_WWAN = 246 /* Wireless WAN (LTE, UMTS, GSM, etc.) */
543 | VK_WIMAX = VK_WWAN
544 | VK_RFKILL = 247 /* Key that controls all radios */
545 |
546 | VK_MICMUTE = 248 /* Mute / unmute the microphone */
547 | )
548 |
549 | //http://thiemonge.org/getting-started-with-uinput
550 |
--------------------------------------------------------------------------------
/src/keybd_event/keybd_linux_export.go:
--------------------------------------------------------------------------------
1 | package keybd_event
2 | // Extra API for xswitcher, by PnD!
3 | // I'll try to commit to keybd_event, a little bit later.
4 | // Right now, just put this to the folder with "keybd_event" sources. To success the build.
5 | func (k *KeyBonding) Down(key uint16) error { return downKey(int(key)) }
6 | func (k *KeyBonding) Up(key uint16) error { return upKey(int(key)) }
7 | func (k *KeyBonding) Sync() error { return sync() }
8 |
--------------------------------------------------------------------------------
/src/keybd_event/keybd_windows.go:
--------------------------------------------------------------------------------
1 | package keybd_event
2 |
3 | import (
4 | "syscall"
5 | )
6 |
7 | var dll = syscall.NewLazyDLL("user32.dll")
8 | var procKeyBd = dll.NewProc("keybd_event")
9 |
10 | // Press key(s)
11 | func (k *KeyBonding) Press() error {
12 | if k.hasALT {
13 | downKey(_VK_ALT)
14 | }
15 | if k.hasALTGR {
16 | downKey(_VK_ALT)
17 | downKey(_VK_CTRL)
18 | }
19 | if k.hasSHIFT {
20 | downKey(_VK_SHIFT)
21 | }
22 | if k.hasCTRL {
23 | downKey(_VK_CTRL)
24 | }
25 | if k.hasRSHIFT {
26 | downKey(_VK_RSHIFT)
27 | }
28 | if k.hasRCTRL {
29 | downKey(_VK_RCONTROL)
30 | }
31 | if k.hasSuper {
32 | downKey(_VK_LWIN)
33 | }
34 | for _, key := range k.keys {
35 | downKey(key)
36 | }
37 | return nil
38 | }
39 |
40 | //Release key(s)
41 | func (k *KeyBonding) Release() error {
42 | if k.hasALT {
43 | upKey(_VK_ALT)
44 | }
45 | if k.hasALTGR {
46 | upKey(_VK_ALT)
47 | upKey(_VK_CTRL)
48 | }
49 | if k.hasSHIFT {
50 | upKey(_VK_SHIFT)
51 | }
52 | if k.hasCTRL {
53 | upKey(_VK_CTRL)
54 | }
55 | if k.hasRSHIFT {
56 | upKey(_VK_RSHIFT)
57 | }
58 | if k.hasRCTRL {
59 | upKey(_VK_RCONTROL)
60 | }
61 | for _, key := range k.keys {
62 | upKey(key)
63 | }
64 | if k.hasSuper {
65 | upKey(_VK_LWIN)
66 | }
67 | return nil
68 | }
69 |
70 | // Launch key bounding
71 | func (k *KeyBonding) Launching() error {
72 | err := k.Press()
73 | if err != nil {
74 | return err
75 | }
76 | err = k.Release()
77 | return err
78 | }
79 | func downKey(key int) {
80 | flag := 0
81 | if key < 0xFFF { // Detect if the key code is virtual or no
82 | flag |= _KEYEVENTF_SCANCODE
83 | } else {
84 | key -= 0xFFF
85 | }
86 | vkey := key + 0x80
87 | procKeyBd.Call(uintptr(key), uintptr(vkey), uintptr(flag), 0)
88 | }
89 | func upKey(key int) {
90 | flag := _KEYEVENTF_KEYUP
91 | if key < 0xFFF {
92 | flag |= _KEYEVENTF_SCANCODE
93 | } else {
94 | key -= 0xFFF
95 | }
96 | vkey := key + 0x80
97 | procKeyBd.Call(uintptr(key), uintptr(vkey), uintptr(flag), 0)
98 | }
99 | func initKeyBD() error { return nil }
100 |
101 | const (
102 | // I add 0xFFF for all Virtual key
103 | _VK_SHIFT = 0x10 + 0xFFF
104 | _VK_CTRL = 0x11 + 0xFFF
105 | _VK_ALT = 0x12 + 0xFFF
106 | _VK_LSHIFT = 0xA0 + 0xFFF
107 | _VK_RSHIFT = 0xA1 + 0xFFF
108 | _VK_LCONTROL = 0xA2 + 0xFFF
109 | _VK_RCONTROL = 0xA3 + 0xFFF
110 | _VK_LWIN = 0x5B + 0xFFF
111 | _VK_RWIN = 0x5C + 0xFFF
112 | _KEYEVENTF_KEYUP = 0x0002
113 | _KEYEVENTF_SCANCODE = 0x0008
114 | )
115 | const (
116 | VK_SP1 = 41
117 | VK_SP2 = 12
118 | VK_SP3 = 13
119 | VK_SP4 = 26
120 | VK_SP5 = 27
121 | VK_SP6 = 39
122 | VK_SP7 = 40
123 | VK_SP8 = 43
124 | VK_SP9 = 51
125 | VK_SP10 = 52
126 | VK_SP11 = 53
127 | VK_SP12 = 86
128 |
129 | VK_ESC = 1
130 | VK_1 = 2
131 | VK_2 = 3
132 | VK_3 = 4
133 | VK_4 = 5
134 | VK_5 = 6
135 | VK_6 = 7
136 | VK_7 = 8
137 | VK_8 = 9
138 | VK_9 = 10
139 | VK_0 = 11
140 | VK_Q = 16
141 | VK_W = 17
142 | VK_E = 18
143 | VK_R = 19
144 | VK_T = 20
145 | VK_Y = 21
146 | VK_U = 22
147 | VK_I = 23
148 | VK_O = 24
149 | VK_P = 25
150 | VK_A = 30
151 | VK_S = 31
152 | VK_D = 32
153 | VK_F = 33
154 | VK_G = 34
155 | VK_H = 35
156 | VK_J = 36
157 | VK_K = 37
158 | VK_L = 38
159 | VK_Z = 44
160 | VK_X = 45
161 | VK_C = 46
162 | VK_V = 47
163 | VK_B = 48
164 | VK_N = 49
165 | VK_M = 50
166 | VK_F1 = 59
167 | VK_F2 = 60
168 | VK_F3 = 61
169 | VK_F4 = 62
170 | VK_F5 = 63
171 | VK_F6 = 64
172 | VK_F7 = 65
173 | VK_F8 = 66
174 | VK_F9 = 67
175 | VK_F10 = 68
176 | VK_F11 = 87
177 | VK_F12 = 88
178 |
179 | VK_F13 = 0x7C + 0xFFF
180 | VK_F14 = 0x7D + 0xFFF
181 | VK_F15 = 0x7E + 0xFFF
182 | VK_F16 = 0x7F + 0xFFF
183 | VK_F17 = 0x80 + 0xFFF
184 | VK_F18 = 0x81 + 0xFFF
185 | VK_F19 = 0x82 + 0xFFF
186 | VK_F20 = 0x83 + 0xFFF
187 | VK_F21 = 0x84 + 0xFFF
188 | VK_F22 = 0x85 + 0xFFF
189 | VK_F23 = 0x86 + 0xFFF
190 | VK_F24 = 0x87 + 0xFFF
191 |
192 | VK_NUMLOCK = 69
193 | VK_SCROLLLOCK = 70
194 | VK_RESERVED = 0
195 | VK_MINUS = 12
196 | VK_EQUAL = 13
197 | VK_BACKSPACE = 14
198 | VK_TAB = 15
199 | VK_LEFTBRACE = 26
200 | VK_RIGHTBRACE = 27
201 | VK_ENTER = 28
202 | VK_SEMICOLON = 39
203 | VK_APOSTROPHE = 40
204 | VK_GRAVE = 41
205 | VK_BACKSLASH = 43
206 | VK_COMMA = 51
207 | VK_DOT = 52
208 | VK_SLASH = 53
209 | VK_KPASTERISK = 55
210 | VK_SPACE = 57
211 | VK_CAPSLOCK = 58
212 |
213 | VK_KP0 = 82
214 | VK_KP1 = 79
215 | VK_KP2 = 80
216 | VK_KP3 = 81
217 | VK_KP4 = 75
218 | VK_KP5 = 76
219 | VK_KP6 = 77
220 | VK_KP7 = 71
221 | VK_KP8 = 72
222 | VK_KP9 = 73
223 | VK_KPMINUS = 74
224 | VK_KPPLUS = 78
225 | VK_KPDOT = 83
226 |
227 | // I add 0xFFF for all Virtual key
228 | VK_LBUTTON = 0x01 + 0xFFF
229 | VK_RBUTTON = 0x02 + 0xFFF
230 | VK_CANCEL = 0x03 + 0xFFF
231 | VK_MBUTTON = 0x04 + 0xFFF
232 | VK_XBUTTON1 = 0x05 + 0xFFF
233 | VK_XBUTTON2 = 0x06 + 0xFFF
234 | VK_BACK = 0x08 + 0xFFF
235 | VK_CLEAR = 0x0C + 0xFFF
236 | VK_PAUSE = 0x13 + 0xFFF
237 | VK_CAPITAL = 0x14 + 0xFFF
238 | VK_KANA = 0x15 + 0xFFF
239 | VK_HANGUEL = 0x15 + 0xFFF
240 | VK_HANGUL = 0x15 + 0xFFF
241 | VK_JUNJA = 0x17 + 0xFFF
242 | VK_FINAL = 0x18 + 0xFFF
243 | VK_HANJA = 0x19 + 0xFFF
244 | VK_KANJI = 0x19 + 0xFFF
245 | VK_CONVERT = 0x1C + 0xFFF
246 | VK_NONCONVERT = 0x1D + 0xFFF
247 | VK_ACCEPT = 0x1E + 0xFFF
248 | VK_MODECHANGE = 0x1F + 0xFFF
249 | VK_PAGEUP = 0x21 + 0xFFF
250 | VK_PAGEDOWN = 0x22 + 0xFFF
251 | VK_END = 0x23 + 0xFFF
252 | VK_HOME = 0x24 + 0xFFF
253 | VK_LEFT = 0x25 + 0xFFF
254 | VK_UP = 0x26 + 0xFFF
255 | VK_RIGHT = 0x27 + 0xFFF
256 | VK_DOWN = 0x28 + 0xFFF
257 | VK_SELECT = 0x29 + 0xFFF
258 | VK_PRINT = 0x2A + 0xFFF
259 | VK_EXECUTE = 0x2B + 0xFFF
260 | VK_SNAPSHOT = 0x2C + 0xFFF
261 | VK_INSERT = 0x2D + 0xFFF
262 | VK_DELETE = 0x2E + 0xFFF
263 | VK_HELP = 0x2F + 0xFFF
264 |
265 | VK_SCROLL = 0x91 + 0xFFF
266 | VK_LMENU = 0xA4 + 0xFFF
267 | VK_RMENU = 0xA5 + 0xFFF
268 | VK_BROWSER_BACK = 0xA6 + 0xFFF
269 | VK_BROWSER_FORWARD = 0xA7 + 0xFFF
270 | VK_BROWSER_REFRESH = 0xA8 + 0xFFF
271 | VK_BROWSER_STOP = 0xA9 + 0xFFF
272 | VK_BROWSER_SEARCH = 0xAA + 0xFFF
273 | VK_BROWSER_FAVORITES = 0xAB + 0xFFF
274 | VK_BROWSER_HOME = 0xAC + 0xFFF
275 | VK_VOLUME_MUTE = 0xAD + 0xFFF
276 | VK_VOLUME_DOWN = 0xAE + 0xFFF
277 | VK_VOLUME_UP = 0xAF + 0xFFF
278 | VK_MEDIA_NEXT_TRACK = 0xB0 + 0xFFF
279 | VK_MEDIA_PREV_TRACK = 0xB1 + 0xFFF
280 | VK_MEDIA_STOP = 0xB2 + 0xFFF
281 | VK_MEDIA_PLAY_PAUSE = 0xB3 + 0xFFF
282 | VK_LAUNCH_MAIL = 0xB4 + 0xFFF
283 | VK_LAUNCH_MEDIA_SELECT = 0xB5 + 0xFFF
284 | VK_LAUNCH_APP1 = 0xB6 + 0xFFF
285 | VK_LAUNCH_APP2 = 0xB7 + 0xFFF
286 | VK_OEM_1 = 0xBA + 0xFFF
287 | VK_OEM_PLUS = 0xBB + 0xFFF
288 | VK_OEM_COMMA = 0xBC + 0xFFF
289 | VK_OEM_MINUS = 0xBD + 0xFFF
290 | VK_OEM_PERIOD = 0xBE + 0xFFF
291 | VK_OEM_2 = 0xBF + 0xFFF
292 | VK_OEM_3 = 0xC0 + 0xFFF
293 | VK_OEM_4 = 0xDB + 0xFFF
294 | VK_OEM_5 = 0xDC + 0xFFF
295 | VK_OEM_6 = 0xDD + 0xFFF
296 | VK_OEM_7 = 0xDE + 0xFFF
297 | VK_OEM_8 = 0xDF + 0xFFF
298 | VK_OEM_102 = 0xE2 + 0xFFF
299 | VK_PROCESSKEY = 0xE5 + 0xFFF
300 | VK_PACKET = 0xE7 + 0xFFF
301 | VK_ATTN = 0xF6 + 0xFFF
302 | VK_CRSEL = 0xF7 + 0xFFF
303 | VK_EXSEL = 0xF8 + 0xFFF
304 | VK_EREOF = 0xF9 + 0xFFF
305 | VK_PLAY = 0xFA + 0xFFF
306 | VK_ZOOM = 0xFB + 0xFFF
307 | VK_NONAME = 0xFC + 0xFFF
308 | VK_PA1 = 0xFD + 0xFFF
309 | VK_OEM_CLEAR = 0xFE + 0xFFF
310 | )
311 |
--------------------------------------------------------------------------------
/src/keybd_event/keyboard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ds-voix/xswitcher/e7cba290dc86ab18287a60de136b50519111742e/src/keybd_event/keyboard.png
--------------------------------------------------------------------------------
/src/keys.go:
--------------------------------------------------------------------------------
1 | package main
2 | // Key (name=code) definitions. To simplifize config.
3 | // https://github.com/gvalkov/golang-evdev/blob/master/ecodes.go
4 | // awk '{if (($1 ~ "^KEY_") && ($3 ~ "^[0-9]")) print "\t\"" $1 "\": " $3 ","}' ecodes.go.src | sed 's/KEY_//'
5 | var (
6 | key_def = map[string]uint { // evdev way is too sophisticated for my goals...
7 | "RESERVED": 0,
8 | "ESC": 1,
9 | "1": 2,
10 | "2": 3,
11 | "3": 4,
12 | "4": 5,
13 | "5": 6,
14 | "6": 7,
15 | "7": 8,
16 | "8": 9,
17 | "9": 10,
18 | "0": 11,
19 | // "MINUS": 12,
20 | "-" : 12,
21 | // "EQUAL": 13,
22 | "=": 13,
23 | "BACKSPACE": 14,
24 | // "BS": 14,
25 | "TAB": 15,
26 | "Q": 16,
27 | "W": 17,
28 | "E": 18,
29 | "R": 19,
30 | "T": 20,
31 | "Y": 21,
32 | "U": 22,
33 | "I": 23,
34 | "O": 24,
35 | "P": 25,
36 | // "LEFTBRACE": 26,
37 | "L_BRACE": 26,
38 | // "RIGHTBRACE": 27,
39 | "R_BRACE": 27,
40 | "ENTER": 28,
41 | // "LEFTCTRL": 29,
42 | "L_CTRL": 29,
43 | "A": 30,
44 | "S": 31,
45 | "D": 32,
46 | "F": 33,
47 | "G": 34,
48 | "H": 35,
49 | "J": 36,
50 | "K": 37,
51 | "L": 38,
52 | "SEMICOLON": 39,
53 | // ";": 39,
54 | "APOSTROPHE": 40,
55 | // "'": 40,
56 | "GRAVE": 41,
57 | // "`": 41,
58 | // "LEFTSHIFT": 42,
59 | "L_SHIFT": 42,
60 | "BACKSLASH": 43,
61 | // "\\": 43,
62 | "Z": 44,
63 | "X": 45,
64 | "C": 46,
65 | "V": 47,
66 | "B": 48,
67 | "N": 49,
68 | "M": 50,
69 | "COMMA": 51,
70 | // ",": 51,
71 | "DOT": 52,
72 | // ".": 52,
73 | "SLASH": 53,
74 | // "/": 53,
75 | // "RIGHTSHIFT": 54,
76 | "R_SHIFT": 54,
77 | "KPASTERISK": 55,
78 | // "LEFTALT": 56,
79 | "L_ALT": 56,
80 | "SPACE": 57,
81 | // "_": 57,
82 | // "CAPSLOCK": 58,
83 | "CAPS": 58,
84 | "F1": 59,
85 | "F2": 60,
86 | "F3": 61,
87 | "F4": 62,
88 | "F5": 63,
89 | "F6": 64,
90 | "F7": 65,
91 | "F8": 66,
92 | "F9": 67,
93 | "F10": 68,
94 | // "NUMLOCK": 69,
95 | "N_LOCK": 69,
96 | // "SCROLLLOCK": 70,
97 | "S_LOCK": 70,
98 | "KP7": 71,
99 | "KP8": 72,
100 | "KP9": 73,
101 | "KPMINUS": 74,
102 | "KP4": 75,
103 | "KP5": 76,
104 | "KP6": 77,
105 | "KPPLUS": 78,
106 | "KP1": 79,
107 | "KP2": 80,
108 | "KP3": 81,
109 | "KP0": 82,
110 | "KPDOT": 83,
111 | "ZENKAKUHANKAKU": 85,
112 | "102ND": 86,
113 | "F11": 87,
114 | "F12": 88,
115 | "RO": 89,
116 | "KATAKANA": 90,
117 | "HIRAGANA": 91,
118 | "HENKAN": 92,
119 | "KATAKANAHIRAGANA": 93,
120 | "MUHENKAN": 94,
121 | "KPJPCOMMA": 95,
122 | "KPENTER": 96,
123 | // "RIGHTCTRL": 97,
124 | "R_CTRL": 97,
125 | "KPSLASH": 98,
126 | "SYSRQ": 99,
127 | // "RIGHTALT": 100,
128 | "R_ALT": 100,
129 | "LINEFEED": 101,
130 | "HOME": 102,
131 | "UP": 103,
132 | "PAGEUP": 104,
133 | "LEFT": 105,
134 | "RIGHT": 106,
135 | "END": 107,
136 | "DOWN": 108,
137 | "PAGEDOWN": 109,
138 | "INSERT": 110,
139 | "DELETE": 111,
140 | "MACRO": 112,
141 | "MUTE": 113,
142 | "VOLUMEDOWN": 114,
143 | "VOLUMEUP": 115,
144 | "POWER": 116,
145 | "KPEQUAL": 117,
146 | "KPPLUSMINUS": 118,
147 | "PAUSE": 119,
148 | "SCALE": 120,
149 | "KPCOMMA": 121,
150 | "HANGEUL": 122,
151 | "HANJA": 123,
152 | "YEN": 124,
153 | // "LEFTMETA": 125,
154 | "L_META": 125,
155 | // "RIGHTMETA": 126,
156 | "R_META": 126,
157 | "COMPOSE": 127,
158 | "STOP": 128,
159 | "AGAIN": 129,
160 | "PROPS": 130,
161 | "UNDO": 131,
162 | "FRONT": 132,
163 | "COPY": 133,
164 | "OPEN": 134,
165 | "PASTE": 135,
166 | "FIND": 136,
167 | "CUT": 137,
168 | "HELP": 138,
169 | "MENU": 139,
170 | "CALC": 140,
171 | "SETUP": 141,
172 | "SLEEP": 142,
173 | "WAKEUP": 143,
174 | "FILE": 144,
175 | "SENDFILE": 145,
176 | "DELETEFILE": 146,
177 | "XFER": 147,
178 | "PROG1": 148,
179 | "PROG2": 149,
180 | "WWW": 150,
181 | "MSDOS": 151,
182 | "COFFEE": 152,
183 | "ROTATE_DISPLAY": 153,
184 | "CYCLEWINDOWS": 154,
185 | "MAIL": 155,
186 | "BOOKMARKS": 156,
187 | "COMPUTER": 157,
188 | "BACK": 158,
189 | "FORWARD": 159,
190 | "CLOSECD": 160,
191 | "EJECTCD": 161,
192 | "EJECTCLOSECD": 162,
193 | "NEXTSONG": 163,
194 | "PLAYPAUSE": 164,
195 | "PREVIOUSSONG": 165,
196 | "STOPCD": 166,
197 | "RECORD": 167,
198 | "REWIND": 168,
199 | "PHONE": 169,
200 | "ISO": 170,
201 | "CONFIG": 171,
202 | "HOMEPAGE": 172,
203 | "REFRESH": 173,
204 | "EXIT": 174,
205 | "MOVE": 175,
206 | "EDIT": 176,
207 | "SCROLLUP": 177,
208 | "SCROLLDOWN": 178,
209 | "KPLEFTPAREN": 179,
210 | "KPRIGHTPAREN": 180,
211 | "NEW": 181,
212 | "REDO": 182,
213 | "F13": 183,
214 | "F14": 184,
215 | "F15": 185,
216 | "F16": 186,
217 | "F17": 187,
218 | "F18": 188,
219 | "F19": 189,
220 | "F20": 190,
221 | "F21": 191,
222 | "F22": 192,
223 | "F23": 193,
224 | "F24": 194,
225 | "PLAYCD": 200,
226 | "PAUSECD": 201,
227 | "PROG3": 202,
228 | "PROG4": 203,
229 | "DASHBOARD": 204,
230 | "SUSPEND": 205,
231 | "CLOSE": 206,
232 | "PLAY": 207,
233 | "FASTFORWARD": 208,
234 | "BASSBOOST": 209,
235 | "PRINT": 210,
236 | "HP": 211,
237 | "CAMERA": 212,
238 | "SOUND": 213,
239 | "QUESTION": 214,
240 | "EMAIL": 215,
241 | "CHAT": 216,
242 | "SEARCH": 217,
243 | "CONNECT": 218,
244 | "FINANCE": 219,
245 | "SPORT": 220,
246 | "SHOP": 221,
247 | "ALTERASE": 222,
248 | "CANCEL": 223,
249 | "BRIGHTNESSDOWN": 224,
250 | "BRIGHTNESSUP": 225,
251 | "MEDIA": 226,
252 | "SWITCHVIDEOMODE": 227,
253 | "KBDILLUMTOGGLE": 228,
254 | "KBDILLUMDOWN": 229,
255 | "KBDILLUMUP": 230,
256 | "SEND": 231,
257 | "REPLY": 232,
258 | "FORWARDMAIL": 233,
259 | "SAVE": 234,
260 | "DOCUMENTS": 235,
261 | "BATTERY": 236,
262 | "BLUETOOTH": 237,
263 | "WLAN": 238,
264 | "UWB": 239,
265 | "UNKNOWN": 240,
266 | "VIDEO_NEXT": 241,
267 | "VIDEO_PREV": 242,
268 | "BRIGHTNESS_CYCLE": 243,
269 | "BRIGHTNESS_AUTO": 244,
270 | "DISPLAY_OFF": 245,
271 | "WWAN": 246,
272 | "RFKILL": 247,
273 | "MICMUTE": 248,
274 | "OK": 0x160,
275 | "SELECT": 0x161,
276 | "GOTO": 0x162,
277 | "CLEAR": 0x163,
278 | "POWER2": 0x164,
279 | "OPTION": 0x165,
280 | "INFO": 0x166,
281 | "TIME": 0x167,
282 | "VENDOR": 0x168,
283 | "ARCHIVE": 0x169,
284 | "PROGRAM": 0x16a,
285 | "CHANNEL": 0x16b,
286 | "FAVORITES": 0x16c,
287 | "EPG": 0x16d,
288 | "PVR": 0x16e,
289 | "MHP": 0x16f,
290 | "LANGUAGE": 0x170,
291 | "TITLE": 0x171,
292 | "SUBTITLE": 0x172,
293 | "ANGLE": 0x173,
294 | "ZOOM": 0x174,
295 | "MODE": 0x175,
296 | "KEYBOARD": 0x176,
297 | "SCREEN": 0x177,
298 | "PC": 0x178,
299 | "TV": 0x179,
300 | "TV2": 0x17a,
301 | "VCR": 0x17b,
302 | "VCR2": 0x17c,
303 | "SAT": 0x17d,
304 | "SAT2": 0x17e,
305 | "CD": 0x17f,
306 | "TAPE": 0x180,
307 | "RADIO": 0x181,
308 | "TUNER": 0x182,
309 | "PLAYER": 0x183,
310 | "TEXT": 0x184,
311 | "DVD": 0x185,
312 | "AUX": 0x186,
313 | "MP3": 0x187,
314 | "AUDIO": 0x188,
315 | "VIDEO": 0x189,
316 | "DIRECTORY": 0x18a,
317 | "LIST": 0x18b,
318 | "MEMO": 0x18c,
319 | "CALENDAR": 0x18d,
320 | "RED": 0x18e,
321 | "GREEN": 0x18f,
322 | "YELLOW": 0x190,
323 | "BLUE": 0x191,
324 | "CHANNELUP": 0x192,
325 | "CHANNELDOWN": 0x193,
326 | "FIRST": 0x194,
327 | "LAST": 0x195,
328 | "AB": 0x196,
329 | "NEXT": 0x197,
330 | "RESTART": 0x198,
331 | "SLOW": 0x199,
332 | "SHUFFLE": 0x19a,
333 | "BREAK": 0x19b,
334 | "PREVIOUS": 0x19c,
335 | "DIGITS": 0x19d,
336 | "TEEN": 0x19e,
337 | "TWEN": 0x19f,
338 | "VIDEOPHONE": 0x1a0,
339 | "GAMES": 0x1a1,
340 | "ZOOMIN": 0x1a2,
341 | "ZOOMOUT": 0x1a3,
342 | "ZOOMRESET": 0x1a4,
343 | "WORDPROCESSOR": 0x1a5,
344 | "EDITOR": 0x1a6,
345 | "SPREADSHEET": 0x1a7,
346 | "GRAPHICSEDITOR": 0x1a8,
347 | "PRESENTATION": 0x1a9,
348 | "DATABASE": 0x1aa,
349 | "NEWS": 0x1ab,
350 | "VOICEMAIL": 0x1ac,
351 | "ADDRESSBOOK": 0x1ad,
352 | "MESSENGER": 0x1ae,
353 | "DISPLAYTOGGLE": 0x1af,
354 | "SPELLCHECK": 0x1b0,
355 | "LOGOFF": 0x1b1,
356 | "DOLLAR": 0x1b2,
357 | "EURO": 0x1b3,
358 | "FRAMEBACK": 0x1b4,
359 | "FRAMEFORWARD": 0x1b5,
360 | "CONTEXT_MENU": 0x1b6,
361 | "MEDIA_REPEAT": 0x1b7,
362 | "10CHANNELSUP": 0x1b8,
363 | "10CHANNELSDOWN": 0x1b9,
364 | "IMAGES": 0x1ba,
365 | "DEL_EOL": 0x1c0,
366 | "DEL_EOS": 0x1c1,
367 | "INS_LINE": 0x1c2,
368 | "DEL_LINE": 0x1c3,
369 | "FN": 0x1d0,
370 | "FN_ESC": 0x1d1,
371 | "FN_F1": 0x1d2,
372 | "FN_F2": 0x1d3,
373 | "FN_F3": 0x1d4,
374 | "FN_F4": 0x1d5,
375 | "FN_F5": 0x1d6,
376 | "FN_F6": 0x1d7,
377 | "FN_F7": 0x1d8,
378 | "FN_F8": 0x1d9,
379 | "FN_F9": 0x1da,
380 | "FN_F10": 0x1db,
381 | "FN_F11": 0x1dc,
382 | "FN_F12": 0x1dd,
383 | "FN_1": 0x1de,
384 | "FN_2": 0x1df,
385 | "FN_D": 0x1e0,
386 | "FN_E": 0x1e1,
387 | "FN_F": 0x1e2,
388 | "FN_S": 0x1e3,
389 | "FN_B": 0x1e4,
390 | "BRL_DOT1": 0x1f1,
391 | "BRL_DOT2": 0x1f2,
392 | "BRL_DOT3": 0x1f3,
393 | "BRL_DOT4": 0x1f4,
394 | "BRL_DOT5": 0x1f5,
395 | "BRL_DOT6": 0x1f6,
396 | "BRL_DOT7": 0x1f7,
397 | "BRL_DOT8": 0x1f8,
398 | "BRL_DOT9": 0x1f9,
399 | "BRL_DOT10": 0x1fa,
400 | "NUMERIC_0": 0x200,
401 | "NUMERIC_1": 0x201,
402 | "NUMERIC_2": 0x202,
403 | "NUMERIC_3": 0x203,
404 | "NUMERIC_4": 0x204,
405 | "NUMERIC_5": 0x205,
406 | "NUMERIC_6": 0x206,
407 | "NUMERIC_7": 0x207,
408 | "NUMERIC_8": 0x208,
409 | "NUMERIC_9": 0x209,
410 | "NUMERIC_STAR": 0x20a,
411 | "NUMERIC_POUND": 0x20b,
412 | "NUMERIC_A": 0x20c,
413 | "NUMERIC_B": 0x20d,
414 | "NUMERIC_C": 0x20e,
415 | "NUMERIC_D": 0x20f,
416 | "CAMERA_FOCUS": 0x210,
417 | "WPS_BUTTON": 0x211,
418 | "TOUCHPAD_TOGGLE": 0x212,
419 | "TOUCHPAD_ON": 0x213,
420 | "TOUCHPAD_OFF": 0x214,
421 | "CAMERA_ZOOMIN": 0x215,
422 | "CAMERA_ZOOMOUT": 0x216,
423 | "CAMERA_UP": 0x217,
424 | "CAMERA_DOWN": 0x218,
425 | "CAMERA_LEFT": 0x219,
426 | "CAMERA_RIGHT": 0x21a,
427 | "ATTENDANT_ON": 0x21b,
428 | "ATTENDANT_OFF": 0x21c,
429 | "ATTENDANT_TOGGLE": 0x21d,
430 | "LIGHTS_TOGGLE": 0x21e,
431 | "ALS_TOGGLE": 0x230,
432 | "BUTTONCONFIG": 0x240,
433 | "TASKMANAGER": 0x241,
434 | "JOURNAL": 0x242,
435 | "CONTROLPANEL": 0x243,
436 | "APPSELECT": 0x244,
437 | "SCREENSAVER": 0x245,
438 | "VOICECOMMAND": 0x246,
439 | "BRIGHTNESS_MIN": 0x250,
440 | "BRIGHTNESS_MAX": 0x251,
441 | "KBDINPUTASSIST_PREV": 0x260,
442 | "KBDINPUTASSIST_NEXT": 0x261,
443 | "KBDINPUTASSIST_PREVGROUP": 0x262,
444 | "KBDINPUTASSIST_NEXTGROUP": 0x263,
445 | "KBDINPUTASSIST_ACCEPT": 0x264,
446 | "KBDINPUTASSIST_CANCEL": 0x265,
447 | "RIGHT_UP": 0x266,
448 | "RIGHT_DOWN": 0x267,
449 | "LEFT_UP": 0x268,
450 | "LEFT_DOWN": 0x269,
451 | "ROOT_MENU": 0x26a,
452 | "MEDIA_TOP_MENU": 0x26b,
453 | "NUMERIC_11": 0x26c,
454 | "NUMERIC_12": 0x26d,
455 | "AUDIO_DESC": 0x26e,
456 | "3D_MODE": 0x26f,
457 | "NEXT_FAVORITE": 0x270,
458 | "STOP_RECORD": 0x271,
459 | "PAUSE_RECORD": 0x272,
460 | "VOD": 0x273,
461 | "UNMUTE": 0x274,
462 | "FASTREVERSE": 0x275,
463 | "SLOWREVERSE": 0x276,
464 | "DATA": 0x275,
465 | "MAX": 0x2ff,
466 | } // 768 elements 0..767
467 |
468 | key_name [KEYS_SIZE]string // "Reverse map", I consider int-array is better storage.
469 | )
470 |
--------------------------------------------------------------------------------
/src/test.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/perl
2 | # The simplest way to test complex regex against the input.
3 | if ("B:1,B:0,SPACE:1,SPACE:0,L_SHIFT:1,P:1" =~ /((((BACK)?SPACE)|([=-]|(KP)?MINUS|(KP)?ENTER|ESC|TAB)):[12]),(((CAPS:[012])|([LR]_SHIFT:[12])|(R_META:0)|((([0-9A-Z=-]|GRAVE|APOSTROPHE|SEMICOLON|[LR]_BRACE|COMMA|DOT|(BACK)?SLASH|KP[0-9])|(((BACK)?SPACE)|([=-]|(KP)?MINUS|(KP)?ENTER|ESC|TAB))):0)),)+(([0-9A-Z=-]|GRAVE|APOSTROPHE|SEMICOLON|[LR]_BRACE|COMMA|DOT|(BACK)?SLASH|KP[0-9]):1)$/) {
4 | print "matched\n"; #
5 | };
6 |
--------------------------------------------------------------------------------
/src/xswitcher.go:
--------------------------------------------------------------------------------
1 | package main
2 | /*
3 | xswitcher v1.0 pre-release
4 | Fully customizable low-level keyboard helper for X.Org-based linux desktop.
5 | /////////////////////////////////////////////////////////////////////////////
6 | Copyright (C) 2020-2021 Dmitry Svyatogorov ds@vo-ix.ru
7 | This program is free software: you can redistribute it and/or modify
8 | it under the terms of the GNU Affero General Public License as
9 | published by the Free Software Foundation, either version 3 of the
10 | License, or (at your option) any later version.
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU Affero General Public License for more details.
15 | You should have received a copy of the GNU Affero General Public License
16 | along with this program. If not, see .
17 | /////////////////////////////////////////////////////////////////////////////
18 |
19 | This soft logs the last keyboard events from Xorg-based linux desktop and does custom actions
20 | according to regex-based rules. The basic actions are to switch the language (keyboard layout)
21 | in the window, and to retype the word in new layout.
22 | Any actions can be joined into chain, to make the complex things.
23 |
24 | There is also an "Exec" action, to run any external executables.
25 |
26 | Look "xswitcher.conf" config file for details.
27 |
28 | !!! This is in fact the low-level keylogger together with the virtual keyboard. !!!
29 | (Big thanks to "github.com/gvalkov/golang-evdev" "github.com/micmonay/keybd_event")
30 |
31 | So, it must have the root privileges by design. And it can't to be configured on per-user basis.
32 | (But anybody is free to fork this project and implement any extra functionality.)
33 |
34 | Referrers:
35 | https://www.kernel.org/doc/html/latest/input/event-codes.html
36 | https://www.kernel.org/doc/html/latest/input/uinput.html
37 |
38 | https://janczer.github.io/work-with-dev-input/
39 | https://godoc.org/github.com/gvalkov/golang-evdev#example-Open
40 | https://github.com/ds-voix/VX-PBX/blob/master/x%20switcher/draft.txt
41 |
42 | https://github.com/BurntSushi/xgb/blob/master/examples/get-active-window/main.go
43 |
44 | xgb is dumb overkill. To be replaced.
45 | X11 XGetInputFocus() etc. HowTo:
46 | https://gist.github.com/kui/2622504
47 | */
48 |
49 | /*
50 | #cgo LDFLAGS: -lX11
51 | #include "C/x11.c"
52 | */
53 | import "C"
54 |
55 | import (
56 | "xswitcher/embeddedConfig"
57 | "xswitcher/exec"
58 | "xswitcher/scancodes"
59 | flag "github.com/spf13/pflag" // CLI keys like python's "argparse". More flexible, comparing with "gnuflag"
60 | "fmt"
61 | "io/ioutil"
62 | "os"
63 | "os/user"
64 | "path/filepath"
65 | "regexp"
66 | // "sort"
67 | "strings"
68 | "strconv"
69 | "syscall"
70 | "time"
71 | // "unsafe"
72 | "github.com/pelletier/go-toml" // Actual TOML parser
73 | // "github.com/gvalkov/golang-evdev" // Keyboard and mouse events
74 | // Refactored to holoplot/go-evdev:
75 | "github.com/holoplot/go-evdev" // Go support for the Linux evdev interface
76 | "github.com/micmonay/keybd_event" // Virtual keyboard !!(must be improved to deal with complex input)
77 | "github.com/kballard/go-shellquote" // joining/splitting strings using sh's word-splitting rules
78 | "github.com/fsnotify/fsnotify" // inotify on /dev/input/
79 | // Deal with clipboard
80 | "golang.design/x/clipboard"
81 | )
82 |
83 | // Config
84 | type TScanDevices struct {
85 | Test string `default:"/dev/input/event0"`
86 | Respawn int `default:"30"`
87 | Search string `default:"/dev/input/event*"`
88 | Bypass string `default:"(?i)Video|Camera"`
89 | BypassRE *(regexp.Regexp)
90 | }
91 |
92 | type TKeyboard struct {
93 | Delay int `default:"5"`
94 | }
95 |
96 | type TActionKeys struct {
97 | Layouts []int `default:"[0,1]"`
98 | Add []string
99 | Drop []string
100 | Test []string
101 | StateKeys []string
102 | }
103 |
104 | type TWindowClass struct {
105 | Regex string
106 | re *(regexp.Regexp)
107 | MouseClickDrops bool
108 | Actions string
109 | }
110 |
111 | type TActions struct {
112 | SeqLength int `default:8`
113 | WordChars string `default:"(^([0-9A-Z=-]|GRAVE|APOSTROPHE|SEMICOLON|[LR]_BRACE|COMMA|DOT|(BACK)?SLASH|KP[0-9]):0$)"`
114 | WordHead string `default:"(^([0-9A-Z]|GRAVE|APOSTROPHE|SEMICOLON|[LR]_BRACE|COMMA|DOT|(BACK)?SLASH|KP[0-9]):1$)"`
115 | NewWord []string
116 | NewSentence []string
117 | Compose []string
118 | TypeClipboard []string
119 | Custom map[string][]string // >> TAction.Name
120 | }
121 |
122 | type TAction struct {
123 | Action []string
124 | Layout int `default:"-1"`
125 | Layouts []int
126 | // Exec options
127 | Exec string
128 | Timeout int `default:"100"`
129 | Wait bool `default:"false"`
130 | SendBuffer string `default:"WORD"`
131 | UseShell bool `default:"true"`
132 | Directory string
133 | CleanEnv bool `default:"true"`
134 | Environment []string
135 | UID string
136 | GID string
137 | }
138 |
139 | type TSequence struct {
140 | OFF * regexp.Regexp
141 | ON * regexp.Regexp
142 | SEQ * regexp.Regexp
143 | }
144 |
145 | type TSequences []TSequence
146 |
147 | // Scan-codes
148 | type t_key struct {
149 | code uint16;
150 | value int32; // 1=press 2=repeat 0=release
151 | }
152 |
153 | type t_keys []t_key
154 |
155 | //type keyFunc func(event t_key)
156 | type actionFunc func(*TAction)
157 |
158 |
159 | const (
160 | DAEMON_NAME = "xswitcher"
161 | KEYS_SIZE = 768
162 | )
163 |
164 | var (
165 | CONFIG_PATH string = "/etc/xswitcher/xswitcher.conf"
166 |
167 | debug bool
168 | DEBUG *bool = &debug
169 |
170 | verbose bool
171 | VERBOSE *bool = &verbose
172 |
173 | test_mode bool
174 | TEST_MODE *bool = &test_mode
175 |
176 | // Config
177 | ScanDevices TScanDevices
178 | Keyboard TKeyboard
179 | Templates map [string]string
180 | ActionKeys TActionKeys
181 | WindowClasses []TWindowClass
182 | Actions TActions
183 | ActionSet map[string] TAction
184 |
185 | // Parse by regex
186 | ON *(regexp.Regexp) = regexp.MustCompile("(\\s|^)ON:\\([^\\s]+\\)") // "ON:(CTRL|ALT|META)"
187 | OFF *(regexp.Regexp) = regexp.MustCompile("(\\s|^)OFF:\\([^\\s]+\\)") // "OFF:(CTRL|ALT|META)"
188 | SEQ *(regexp.Regexp) = regexp.MustCompile("(\\s|^)SEQ:\\([^\\s]+\\)") // "SEQ:(@WORD@:2,@WORD@:0)"
189 | TEMPLATE *(regexp.Regexp) = regexp.MustCompile("@[A-Za-z0-9_]+@") // "@WORD@"
190 |
191 | Action = regexp.MustCompile("^Action\\..+")
192 | ActionName = regexp.MustCompile("\\..+$")
193 | WordChars *(regexp.Regexp) // Actions.WordChars
194 | WordHead *(regexp.Regexp) // Actions.WordHead
195 |
196 | // Sequences
197 | NewWord TSequences
198 | NewSentence TSequences
199 | Compose TSequences
200 | TypeClipboard TSequences
201 | ActSeq map[string] TSequences
202 |
203 | // Scan-codes processing
204 | KEYS [KEYS_SIZE]func(t_key)
205 | ADD = make(map[uint16]bool)
206 | KEY_RANGE = regexp.MustCompile(`^[\[\]A-Z0-9_=.,;/\\-]+\.\.[\[\]A-Z0-9_=.,;/\\-]+$`)
207 | KEY_SPLIT = regexp.MustCompile(`\.\.`)
208 |
209 | // Action hooks
210 | ACTIONS = make(map[string] actionFunc, 5) // (RetypeWord, Switch, Layout, Respawn, Exec)
211 |
212 | // Shared t_key queues (it's ok to share *buffered* channels *writes*)
213 | keyboardEvents = make(chan t_key, 8)
214 | miceEvents = make(chan t_key, 8)
215 |
216 | // Xorg via C-bindings
217 | display *C.struct__XDisplay
218 | revert_to C.int // Set 1-thread vars out of GC
219 | x_class *C.XClassHint
220 | // Cache ActiveWindowId() along key processing
221 | ActiveWindowId C.Window
222 | ActiveWindowClass string
223 | WC *TWindowClass
224 |
225 | // Virtual keyboard
226 | kb keybd_event.KeyBonding
227 |
228 | // Buffers
229 | WORD t_keys // addKey
230 | SENTENCE t_keys // addKey
231 | TEST t_keys // addKey + testKey
232 | REPEATED [KEYS_SIZE]bool // Deduplicate repeated codes (code:1,code:2,..code:2,code:0). There could be more then 1 "sealing" key.
233 | // A Builder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use.
234 | TAIL strings.Builder // Text representation of TEST (the last Actions.SeqLength codes)
235 | CTRL = make(map[string]bool, 10) // A set of control keys that are down. Extra "WORD" indicates RetypeWord was just performed.
236 |
237 | CTRL_WORD map[string]bool // CTRL at the beginning of the WORD
238 | CTRL_SENTENCE map[string]bool // CTRL at the beginning of the SENTENCE
239 | COMPOSE int // Compose counter
240 | EXTRA int // Extra keys (to call the Action), must not be retyped.
241 | DOWN = make(map[uint16] int) // In any case, all virtual keys MUST BE RELEASED at the end of retyping.
242 |
243 | clipboardOk = false
244 | )
245 |
246 | func config() {
247 | var (
248 | conf map [string]interface{}
249 | conf_ []byte
250 | err error
251 | )
252 | config_path := &CONFIG_PATH
253 |
254 | if env_config, ok := os.LookupEnv("CONFIG"); ok {
255 | *config_path = env_config
256 | }
257 | _ , *DEBUG = os.LookupEnv("DEBUG")
258 | _ , *VERBOSE = os.LookupEnv("VERBOSE")
259 | _ , *TEST_MODE = os.LookupEnv("TEST")
260 |
261 | F := flag.NewFlagSet("", flag.ContinueOnError)
262 | config_path = F.StringP("conf", "c", *config_path, "Non-default config location")
263 | DEBUG = F.BoolP("debug", "d", *DEBUG, "Debug log level")
264 | VERBOSE = F.BoolP("verbose", "v", *VERBOSE, "Increase log level to NOTICE")
265 | TEST_MODE = F.BoolP("test", "t", *TEST_MODE, "Only output all key events to STDERR. No actions.")
266 | F.Init("", flag.ExitOnError)
267 | F.Parse(os.Args[1:])
268 |
269 | conf_file, err := os.Open(*config_path)
270 | if err != nil {
271 | fmt.Println(fmt.Errorf("Config error: unable to open config file:\n%s", err.Error()))
272 | fmt.Println("* Using defaults!")
273 | conf_ = []byte(embeddedConfig.Toml)
274 | } else {
275 | defer conf_file.Close()
276 | conf_, err = ioutil.ReadAll(conf_file)
277 | if err != nil {
278 | fmt.Println(fmt.Errorf("Config error: unable to read config file:\n%s", err.Error()))
279 | fmt.Println("* Using defaults!")
280 | conf_ = []byte(embeddedConfig.Toml)
281 | }
282 | }
283 |
284 | if *DEBUG {
285 | fmt.Println(string(conf_))
286 | }
287 | if err := toml.Unmarshal(conf_, &conf); err != nil {
288 | panic(fmt.Errorf("Config error: unable to parse config file:\n%s", err.Error()))
289 | }
290 |
291 | for key, value := range conf {
292 | switch key {
293 | case "ScanDevices":
294 | _ScanDevices, err := toml.Marshal(value)
295 | if err != nil {
296 | panic(fmt.Errorf("Config error: unable to parse [ScanDevices]:\n%s", err.Error()))
297 | }
298 | if err = toml.Unmarshal(_ScanDevices, &ScanDevices); err != nil {
299 | panic(fmt.Errorf("Config error: unable to parse [ScanDevices]:\n%s", err.Error()))
300 | }
301 | if ScanDevices.BypassRE, err = regexp.Compile(ScanDevices.Bypass); err != nil {
302 | panic(fmt.Errorf("Config error: unable to parse [ScanDevices]. Invalid regexp for \"Bypass\".\n%s", err.Error()))
303 | }
304 | case "Templates":
305 | switch t := value.(type) {
306 | case map[string]interface{}:
307 | Templates = make(map [string]string, len(t))
308 | for k, v := range t {
309 | if _, err = regexp.Compile(v.(string)); err != nil {
310 | panic(fmt.Errorf("Config error: unable to parse [Templates]. Invalid regexp for \"%s\".\n%s", k, err.Error()))
311 | }
312 | Templates[k] = v.(string)
313 | }
314 | default:
315 | panic(fmt.Errorf("Config error: [Templates] must consist of \"name = string\" peers "))
316 | }
317 |
318 | case "ActionKeys":
319 | _ActionKeys, err := toml.Marshal(value)
320 | if err != nil {
321 | panic(fmt.Errorf("Config error: unable to parse [ActionKeys]:\n%s", err.Error()))
322 | }
323 | if err = toml.Unmarshal(_ActionKeys, &ActionKeys); err != nil {
324 | panic(fmt.Errorf("Config error: unable to parse [ActionKeys]:\n%s", err.Error()))
325 | }
326 |
327 | case "WindowClasses":
328 | switch t := value.(type) {
329 | case []map[string]interface{}:
330 | for _, v := range t {
331 | _WindowClass, err := toml.Marshal(v)
332 | if err != nil {
333 | panic(fmt.Errorf("Config error: unable to parse [[WindowClasses]]:\n%s", err.Error()))
334 | }
335 | class :=TWindowClass{}
336 | if err = toml.Unmarshal(_WindowClass, &class); err != nil {
337 | panic(fmt.Errorf("Config error: unable to parse [[WindowClasses]]:\n%s", err.Error()))
338 | }
339 |
340 | if class.Regex != "" {
341 | class.re, err = regexp.Compile(class.Regex)
342 | if err != nil {
343 | panic(fmt.Errorf("Config error: unable to parse [[WindowClasses]]. Invalid regexp \"%s\".\n%s", class.Regex, err.Error()))
344 | }
345 | } else {
346 | class.re = nil
347 | }
348 |
349 | if class.Actions != "" {
350 | if class.Actions != "Actions" { // Too complecs for the first release.
351 | panic(fmt.Errorf("Config error: Only one action set \"Actions\" is realised for [[WindowClasses]] in current version.\nUnable to serve \"%s\"", class.Actions))
352 | }
353 | }
354 | WindowClasses = append(WindowClasses, class)
355 | }
356 | default:
357 | panic(fmt.Errorf("Config error: [[WindowClasses]] must be a slice of sections, not a single [WindowClasses] section"))
358 | }
359 |
360 | case "Actions":
361 | switch t := value.(type) {
362 | case map[string]interface{}:
363 | Actions.Custom = make(map[string][]string, len(t) - 4) // 4 = count of preset keys
364 | for k, v := range t {
365 | switch k {
366 | case "SeqLength":
367 | switch t := v.(type) {
368 | case int64:
369 | if (t < 1) || (t > 255) {
370 | panic(fmt.Errorf("Config error: Actions.SeqLength must be integer betwen 1 and 255"))
371 | }
372 | Actions.SeqLength = int(t)
373 | default:
374 | panic(fmt.Errorf("Config error: Actions.SeqLength must be integer betwen 1 and 255"))
375 | }
376 | case "WordChars":
377 | switch t := v.(type) {
378 | case interface{}:
379 | Actions.WordChars = t.(string)
380 | default:
381 | panic(fmt.Errorf("Config error: \"WordChars\" value must be string"))
382 | }
383 | case "WordHead":
384 | switch t := v.(type) {
385 | case interface{}:
386 | Actions.WordHead = t.(string)
387 | default:
388 | panic(fmt.Errorf("Config error: \"WordHead\" value must be string"))
389 | }
390 | case "NewWord":
391 | switch t := v.(type) {
392 | case []interface{}:
393 | for _, seq := range t {
394 | Actions.NewWord = append(Actions.NewWord, seq.(string))
395 | }
396 | default:
397 | panic(fmt.Errorf("Config error: \"NewWord\" value must be array of strings"))
398 | }
399 | case "NewSentence":
400 | switch t := v.(type) {
401 | case []interface{}:
402 | for _, seq := range t {
403 | Actions.NewSentence = append(Actions.NewSentence, seq.(string))
404 | }
405 | default:
406 | panic(fmt.Errorf("Config error: \"NewSentence\" value must be array of strings"))
407 | }
408 | case "Compose":
409 | switch t := v.(type) {
410 | case []interface{}:
411 | for _, seq := range t {
412 | Actions.Compose = append(Actions.Compose, seq.(string))
413 | }
414 | default:
415 | panic(fmt.Errorf("Config error: \"Compose\" value must be array of strings"))
416 | }
417 | case "TypeClipboard":
418 | switch t := v.(type) {
419 | case []interface{}:
420 | for _, seq := range t {
421 | Actions.TypeClipboard = append(Actions.TypeClipboard, seq.(string))
422 | }
423 | default:
424 | panic(fmt.Errorf("Config error: \"TypeClipboard\" value must be array of strings"))
425 | }
426 | default:
427 | if Action.MatchString(k) {
428 | switch t := v.(type) {
429 | case []interface{}:
430 | name := strings.TrimLeft(ActionName.FindString(k), ".")
431 | for _, seq := range t {
432 | Actions.Custom[name] = append(Actions.Custom[name], seq.(string))
433 | }
434 | default:
435 | panic(fmt.Errorf("Config error: \"Action.\" values must be arrays of strings"))
436 | }
437 | } else {
438 | panic(fmt.Errorf("Config error: unknown key \"%s\" in [Actions] section", k))
439 | }
440 | }
441 | }
442 |
443 | default:
444 | panic(fmt.Errorf("Config error: [Actions] must consist of \"name = value\" peers "))
445 | }
446 |
447 | case "Action":
448 | switch t := value.(type) {
449 | case map[string]interface{}:
450 | ActionSet = make(map[string] TAction, len(t))
451 | for key, value := range t {
452 | _Action, err := toml.Marshal(value)
453 | if err != nil {
454 | panic(fmt.Errorf("Config error: unable to parse [Action.%s]:\n%s", key, err.Error()))
455 | }
456 | act := TAction{}
457 | if err = toml.Unmarshal(_Action, &act); err != nil {
458 | panic(fmt.Errorf("Config error: unable to parse [Action.%s]:\n%s", key, err.Error()))
459 | }
460 | ActionSet[key] = act
461 | }
462 | default:
463 | panic(fmt.Errorf("Config error: [[WindowClasses]] must be a slice of sections, not a single [WindowClasses] section %T", t))
464 | }
465 |
466 | case "Keyboard":
467 | _Keyboard, err := toml.Marshal(value)
468 | if err != nil {
469 | panic(fmt.Errorf("Config error: unable to parse [Keyboard]:\n%s", err.Error()))
470 | }
471 | if err = toml.Unmarshal(_Keyboard, &Keyboard); err != nil {
472 | panic(fmt.Errorf("Config error: unable to parse [Keyboard]:\n%s", err.Error()))
473 | }
474 |
475 | default:
476 | panic(fmt.Errorf("Config error: unknown section name [%s]", key))
477 | }
478 | }
479 | // Finally, check that ActionSet contains all Custom Actions
480 | for key, _ := range Actions.Custom {
481 | if _, ok := ActionSet[key]; !ok {
482 | panic(fmt.Errorf("Config error: Action definition not found for \"Action.%s\"", key))
483 | }
484 | }
485 | }
486 |
487 | // Substitute templates "@xxx@"
488 | func template(str string) string {
489 | tpl := TEMPLATE.FindAllStringIndex(str, -1)
490 | if tpl != nil {
491 | for i := len(tpl)-1; i >= 0; i-- {
492 | match := tpl[i]
493 | t := str[ (match[0]+1):(match[1]-1) ]
494 | if _tpl, ok := Templates[t]; !ok {
495 | fmt.Printf("Parse warning: Template definition not found for @%s@. This expression will be used \"as is\".\n", t)
496 | } else {
497 | str = str[ 0:match[0] ] + _tpl + str[ (match[1]) : ]
498 | }
499 | }
500 | }
501 | return str
502 | }
503 |
504 | func seqParse(str string, act string) (seq TSequence) {
505 | var err error
506 | // 1. Substitute templates
507 | str = template(str)
508 |
509 | // 2. "OFF:()" state
510 | tpl := OFF.FindAllStringIndex(str, -1)
511 | if tpl != nil {
512 | if len(tpl) > 1 {
513 | panic(fmt.Errorf("Parse error: Found more than 1 \"OFF\" declaration for action \"%s\"", act))
514 | } else {
515 | match := tpl[0]
516 | t := strings.TrimLeft(str[ match[0] :match[1] ], " OFF:")
517 | seq.OFF, err = regexp.Compile(strings.TrimRight(t, "$") + "$") // Match againt the end of sequence
518 | if *VERBOSE || *DEBUG {
519 | fmt.Printf("%s OFF: %s\n", act, t)
520 | }
521 | if err != nil {
522 | panic(fmt.Errorf("Parse error: Invalid regex for OFF: condition of action \"%s\"\n%s", act, err.Error()))
523 | }
524 | }
525 | }
526 | // 3. "ON:()" state
527 | tpl = ON.FindAllStringIndex(str, -1)
528 | if tpl != nil {
529 | if len(tpl) > 1 {
530 | panic(fmt.Errorf("Parse error: Found more than 1 \"ON\" declaration for action \"%s\"", act))
531 | } else {
532 | match := tpl[0]
533 | t := strings.TrimLeft(str[ match[0] :match[1] ], " ON:")
534 | seq.ON, err = regexp.Compile(strings.TrimRight(t, "$") + "$") // Match againt the end of sequence
535 | if *VERBOSE || *DEBUG {
536 | fmt.Printf("%s ON: %s\n", act, t)
537 | }
538 | if err != nil {
539 | panic(fmt.Errorf("Parse error: Invalid regex for ON: condition of action \"%s\"\n%s", act, err.Error()))
540 | }
541 | }
542 | }
543 | // 4. "SEQ:()" state
544 | tpl = SEQ.FindAllStringIndex(str, -1)
545 | if tpl != nil {
546 | if len(tpl) > 1 {
547 | panic(fmt.Errorf("Parse error: Found more than 1 \"SEQ\" declaration for action \"%s\"", act))
548 | } else {
549 | match := tpl[0]
550 | t := strings.TrimLeft(str[ match[0] :match[1] ], " SEQ:")
551 | seq.SEQ, err = regexp.Compile(strings.TrimRight(t, "$") + "$") // Match againt the end of sequence
552 | if *VERBOSE || *DEBUG {
553 | fmt.Printf("%s => %s\n", act, t)
554 | }
555 | if err != nil {
556 | panic(fmt.Errorf("Parse error: Invalid regex for SEQ: condition of action \"%s\"\n%s", act, err.Error()))
557 | }
558 | }
559 | }
560 |
561 | return seq
562 | }
563 |
564 | func sequences() {
565 | var err error
566 |
567 | for _, s := range Actions.NewWord {
568 | NewWord = append(NewWord, seqParse(s, "NewWord"))
569 | }
570 | for _, s := range Actions.NewSentence {
571 | NewSentence = append(NewSentence, seqParse(s, "NewSentence"))
572 | }
573 | for _, s := range Actions.Compose {
574 | Compose = append(Compose, seqParse(s, "Compose"))
575 | }
576 | for _, s := range Actions.TypeClipboard {
577 | TypeClipboard = append(TypeClipboard, seqParse(s, "TypeClipboard"))
578 | }
579 |
580 | ActSeq = make(map[string] TSequences)
581 | for key, value := range Actions.Custom {
582 | for _, s := range value {
583 | ActSeq[key] = append(ActSeq[key], seqParse(s, key))
584 | }
585 | }
586 |
587 | WordChars, err = regexp.Compile(template(Actions.WordChars))
588 | if err != nil {
589 | panic(fmt.Errorf("Parse error: Invalid regex for Actions.WordChars\n%s", err.Error()))
590 | }
591 | if *VERBOSE || *DEBUG {
592 | fmt.Printf("WordChars => %s\n", template(Actions.WordChars))
593 | }
594 |
595 | WordHead, err = regexp.Compile(template(Actions.WordHead))
596 | if err != nil {
597 | panic(fmt.Errorf("Parse error: Invalid regex for Actions.WordHead\n%s", err.Error()))
598 | }
599 | if *VERBOSE || *DEBUG {
600 | fmt.Printf("WordHead => %s\n", template(Actions.WordHead))
601 | }
602 |
603 | return
604 | }
605 |
606 | func parseKeys(keys []string, action func(t_key), name string) {
607 | for _, key := range keys {
608 | if k, ok := key_def[key]; ok {
609 | KEYS[k] = action
610 | } else {
611 | if KEY_RANGE.MatchString(key) {
612 | k1 := uint(0)
613 | k2 := uint(0)
614 | kk := KEY_SPLIT.Split(key, 2)
615 | if k1, ok = key_def[ kk[0] ]; !ok {
616 | panic(fmt.Sprintf("Parse error: Invalid key for %s: %s", name, key))
617 | }
618 | if k2, ok = key_def[ kk[1] ]; !ok {
619 | panic(fmt.Sprintf("Parse error: Invalid key for %s: %s", name, key))
620 | }
621 |
622 | for k := k1; k <= k2 ; k++ {
623 | KEYS[k] = action
624 | if name == "Add" { // I found no way to take the valid pointer to func in go
625 | ADD[uint16(k)] = true
626 | }
627 | }
628 | } else {
629 | panic(fmt.Sprintf("Parse error: Invalid key for %s: %s", name, key))
630 | }
631 | }
632 | }
633 | }
634 |
635 | func keys() {
636 | for name, code := range key_def { // Invert key_def[] to key_name[]
637 | key_name[code] = name
638 | }
639 | // Extra key aliases
640 | key_def["MINUS"] = 12
641 | key_def["EQUAL"] = 13
642 | key_def["["] = 26
643 | key_def["]"] = 27
644 | key_def[";"] = 39
645 | key_def["'"] = 40
646 | key_def["`"] = 41
647 | key_def["\\"] = 43
648 | key_def[","] = 51
649 | key_def["."] = 52
650 | key_def["/"] = 53
651 |
652 | for i, _ := range KEYS { // All defaults to testKey()
653 | KEYS[i] = testKey
654 | }
655 |
656 | parseKeys(ActionKeys.Add, addKey, "Add")
657 | parseKeys(ActionKeys.Drop, dropKey, "Drop")
658 | parseKeys(ActionKeys.Test, testKey, "Test")
659 |
660 | return
661 | }
662 |
663 | // There must be 1 buffer per each X-window.
664 | // Or just to reset the buffer on each focus change?
665 | func getActiveWindowId() (idChanged bool) { // _Ctype_Window == uint32
666 | idChanged = true
667 | ActiveWindowId_old := ActiveWindowId
668 | if C.XGetInputFocus(display, &ActiveWindowId, &revert_to) == 0 {
669 | ActiveWindowId = 0
670 | fmt.Println("ActiveWindowId = 0", C.XGetInputFocus(display, &ActiveWindowId, &revert_to))
671 | }
672 |
673 | if ActiveWindowId == ActiveWindowId_old { return false}
674 |
675 | if ActiveWindowId <= 1 {
676 | ActiveWindowClass = ""
677 | fmt.Println("ActiveWindowId <= 1")
678 | return
679 | }
680 |
681 | // !!! "X Error of failed request: BadWindow (invalid Window parameter)" in case of window was gone.
682 | // https://eli.thegreenplace.net/2019/passing-callbacks-and-pointers-to-cgo/
683 | // https://artem.krylysov.com/blog/2017/04/13/handling-cpp-exceptions-in-go/
684 | // >>> https://stackoverflow.com/questions/32947511/cgo-cant-set-callback-in-c-struct-from-go
685 | // C.XFlush(display)
686 | if C.XGetClassHint(display, ActiveWindowId, x_class) > 0 { // "VirtualBox Machine"
687 | if ActiveWindowClass != C.GoString(x_class.res_name) {
688 | ActiveWindowClass = C.GoString(x_class.res_name)
689 | fmt.Println("=", ActiveWindowClass)
690 | }
691 | } else {
692 | if C.XGetClassHint(display, ActiveWindowId - 1, x_class) > 0 { // https://antofthy.gitlab.io/info/X/WindowID.txt
693 | // However the reported ID is generally wrong for GTK apps (like Firefox) and the windows immediate parent is actually needed...
694 | // Typically for GTK the parent window is 1 less than the focus window ... But there is no gurantee that the ID is one less.
695 | if ActiveWindowClass != C.GoString(x_class.res_name) {
696 | ActiveWindowClass = C.GoString(x_class.res_name)
697 | fmt.Println("*", ActiveWindowClass)
698 | }
699 | } else {
700 | fmt.Println("Empty ActiveWindowClass. M.b. gnome \"window\"?")
701 | }
702 | }
703 | if C.xerror == C.True { // ??? Is there some action needed?
704 | C.xerror = C.False
705 | }
706 | return
707 | }
708 |
709 | func copyCTRL(c map[string]bool) (cp map[string]bool) {
710 | cp = make(map[string]bool, 8)
711 | for k, v := range c {
712 | cp[k] = v
713 | }
714 | return
715 | }
716 |
717 | func dropBuffers() {
718 | TEST = nil
719 | WORD = nil
720 | SENTENCE = nil
721 | delete(CTRL, "WORD")
722 | CTRL_WORD = copyCTRL(CTRL)
723 | CTRL_SENTENCE = copyCTRL(CTRL)
724 | COMPOSE = 0
725 | }
726 |
727 | func newWord() {
728 | end := len(WORD) - 1
729 | if (end >= 0) && (WORD[end].value == 1) {
730 | WORD = WORD[end:]
731 | } else {
732 | WORD = nil
733 | }
734 |
735 | delete(CTRL, "WORD")
736 | CTRL_WORD = copyCTRL(CTRL)
737 | COMPOSE = 0
738 | }
739 |
740 | func DropBuffers(A *TAction) {
741 | dropBuffers()
742 | }
743 |
744 | func Clean(A *TAction) {
745 | newWord()
746 | }
747 |
748 | func checkLanguageId() bool {
749 | state := new(C.struct__XkbStateRec)
750 | C.XkbGetState(display, C.XkbUseCoreKbd, state);
751 |
752 | for _, l := range ActionKeys.Layouts {
753 | if l == int(state.group) { return true }
754 | }
755 |
756 | return false
757 | }
758 |
759 | func getXModifiers() uint32 {
760 | state := new(C.struct__XkbStateRec)
761 | C.XkbGetState(display, C.XkbUseCoreKbd, state);
762 |
763 | if (state.mods & 2) > 0 { // CAPSLOCK = 2
764 | CTRL[ key_name[evdev.KEY_CAPSLOCK] ] = true
765 | } else {
766 | delete(CTRL, key_name[evdev.KEY_CAPSLOCK])
767 | }
768 |
769 | if (state.mods & 16) > 0 { // NUMLOCK = 16
770 | CTRL[ key_name[evdev.KEY_NUMLOCK] ] = true
771 | } else {
772 | delete(CTRL, key_name[evdev.KEY_NUMLOCK])
773 | }
774 |
775 | return uint32(state.mods)
776 | }
777 |
778 | // Check language if (lang < 0), set language if (lang >= 0)
779 | func Language(lang int) (int) {
780 | state := new(C.struct__XkbStateRec)
781 | layout := C.uint(0)
782 |
783 | C.XkbGetState(display, C.XkbUseCoreKbd, state);
784 | if lang >= 0 {
785 | if int(state.group) != lang {
786 | CTRL["WORD"] = true
787 | }
788 | layout = C.uint(lang)
789 | C.XkbLockGroup(display, C.XkbUseCoreKbd, layout);
790 | C.XkbGetState(display, C.XkbUseCoreKbd, state);
791 | }
792 |
793 | return int(state.group)
794 | }
795 |
796 | // Push or release the key on virtual keyboard
797 | func sendKey(key t_key) {
798 | switch key.value {
799 | case 0:
800 | kb.Up(key.code)
801 | kb.Sync()
802 | default:
803 | kb.Down(key.code)
804 | kb.Sync()
805 | }
806 | time.Sleep(time.Duration(Keyboard.Delay) * time.Millisecond)
807 | }
808 |
809 | // Single key press on virtual keyboard
810 | func pressKey(key int) {
811 | sendKey(t_key{uint16(key), 1})
812 | sendKey(t_key{uint16(key), 0})
813 | }
814 |
815 | // ACTIONS (RetypeWord, Switch, Layout, Respawn, Exec)
816 | func RetypeWord(A *TAction) {
817 | if (len(WORD) - EXTRA) < 1 { // WTF?!
818 | fmt.Println("RetypeWord error: WORD is smaller than EXTRA!", EXTRA)
819 | newWord()
820 | return
821 | }
822 | count := 0 // Count chars to be deleted
823 | seq := 0 // Incremental key event counter
824 | // Patch "orphaned" key releases.
825 | o := make(map[uint16] bool) // True since key-down till key-up.
826 | for i := 0; i < (len(WORD) - EXTRA); i++ {
827 | if WORD[i].value == 0 {
828 | if !o[WORD[i].code] {
829 | continue
830 | } else {
831 | o[WORD[i].code] = false
832 | }
833 | } else {
834 | o[WORD[i].code] = true
835 | }
836 |
837 | if WordChars.MatchString(key_name[WORD[i].code] + ":" + strconv.Itoa(int(WORD[i].value))) {
838 | count++
839 | }
840 | if WORD[i].value == 0 {
841 | switch WORD[i].code {
842 | case uint16(key_def["SPACE"]):
843 | count++
844 | case uint16(key_def["BACKSPACE"]):
845 | fmt.Println("RetypeWord error: BACKSPACE inside WORD!")
846 | newWord()
847 | return
848 | }
849 | }
850 | }
851 |
852 | // Clean the word
853 | for i := 0; i < count - COMPOSE; i++ {
854 | pressKey(evdev.KEY_BACKSPACE)
855 | }
856 |
857 | // Initial CTRL state
858 | for k, v := range CTRL_WORD {
859 | if v && ! CTRL[k] {
860 | switch key_def[k] {
861 | case evdev.KEY_CAPSLOCK:
862 | pressKey(evdev.KEY_CAPSLOCK)
863 | case evdev.KEY_NUMLOCK:
864 | pressKey(evdev.KEY_NUMLOCK)
865 | default:
866 | sendKey(t_key{uint16(key_def[k]), 1})
867 | DOWN[uint16(key_def[k])] = seq
868 | seq++
869 | }
870 | }
871 | }
872 |
873 | // Retype WORD
874 | RETYPE := len(WORD) - EXTRA
875 |
876 | if *VERBOSE {
877 | fmt.Printf("RETYPE: %v", CTRL_WORD) // Helpfull to debug e.g. keyboard bounce
878 | // "RETYPE: {17 1}{16 0}{17 0} :DONE" >> Oh, shi!
879 | }
880 |
881 | for i := 0; i < RETYPE; i++ {
882 | if WORD[i].value == 0 {
883 | if !o[WORD[i].code] {
884 | switch WORD[i].code { // !! There must be StateKeys-driven check
885 | case evdev.KEY_LEFTCTRL, evdev.KEY_LEFTSHIFT, evdev.KEY_LEFTALT, evdev.KEY_RIGHTCTRL, evdev.KEY_RIGHTSHIFT, evdev.KEY_RIGHTALT, evdev.KEY_LEFTMETA, evdev.KEY_RIGHTMETA:
886 | default:
887 | if *VERBOSE {
888 | fmt.Printf("{%d x}", WORD[i].code)
889 | }
890 | continue
891 | }
892 | } else {
893 | o[WORD[i].code] = false
894 | }
895 | } else {
896 | o[WORD[i].code] = true
897 | }
898 | sendKey(WORD[i])
899 | if WORD[i].value == 1 {
900 | DOWN[WORD[i].code] = seq
901 | } else {
902 | delete(DOWN, WORD[i].code)
903 | }
904 | seq++
905 | if *VERBOSE {
906 | fmt.Printf("%v",WORD[i])
907 | }
908 | }
909 | if *VERBOSE {
910 | fmt.Printf(" :DONE\n")
911 | }
912 | WORD = WORD[ 0 : (len(WORD) - EXTRA)]
913 | CTRL["WORD"] = true
914 |
915 | // Clear virtual keyboard state
916 | if len(DOWN) > 0 {
917 | fmt.Printf("RetypeWord warning: found pushed keys after retyping was done! %v", DOWN)
918 | for k, _ := range DOWN {
919 | sendKey(t_key{k, 0})
920 | }
921 | }
922 | }
923 |
924 | // ToDo: newWord() | dropBuffers() must be implemented here in "smart" way.
925 | // Nested action: leave buffers as is. Or implement extra option "what to do with buffers".
926 | // Single action: drop. Or be smarter and remember the layout inside key sequences...
927 | func Switch(A *TAction) {
928 | next := 0
929 | l := Language(-1)
930 |
931 | for i := 0; i < len(A.Layouts); i++ {
932 | if l == A.Layouts[i] {
933 | next = l + 1
934 | }
935 | }
936 |
937 | if next >= len(A.Layouts) {
938 | next = 0
939 | }
940 |
941 | Language(A.Layouts[next])
942 |
943 | CTRL["WORD"] = true
944 | }
945 |
946 | func Layout(A *TAction) {
947 | Language(A.Layout)
948 | }
949 |
950 | func Exec(A *TAction) {
951 | /*
952 | Exec string
953 | Timeout int `default:"100"`
954 | Wait bool `default:"false"`
955 | SendBuffer string `default:"WORD"`
956 | UseShell bool `default:"true"`
957 | Directory string
958 | CleanEnv bool `default:"true"`
959 | Environment []string
960 | UID string
961 | GID string
962 | */
963 | var c exec.Command;
964 | args, err := shellquote.Split(A.Exec)
965 | if err != nil {
966 | fmt.Printf("Exec error: %s", err.Error)
967 | return
968 | }
969 |
970 | if len(args) == 0 {
971 | fmt.Println("Exec error: Empty \"Exec\" value!")
972 | return
973 | }
974 |
975 | c.UseShell = A.UseShell
976 | if A.UseShell {
977 | c.Command = A.Exec
978 | } else {
979 | c.Command = args[0]
980 | if len(args) > 1 {
981 | c.Args = args[1:]
982 | }
983 | }
984 |
985 | if A.SendBuffer != "" {
986 | switch A.SendBuffer {
987 | case "WORD":
988 | c.StdIn = []byte(fmt.Sprintf("%v",WORD))
989 | case "SENTENCE":
990 | c.StdIn = []byte(fmt.Sprintf("%v",SENTENCE))
991 | default:
992 | c.StdIn = []byte(A.SendBuffer)
993 | }
994 | }
995 |
996 | c.Timeout = float64(A.Timeout)
997 | c.No_wait = ! A.Wait
998 | c.Set_dir = A.Directory
999 |
1000 | if ! A.CleanEnv {
1001 | c.Set_env = os.Environ()
1002 | }
1003 | c.Set_env = append(c.Set_env, A.Environment...)
1004 |
1005 | // UID & GID
1006 | user_, err := user.Lookup(A.UID)
1007 | if err != nil {
1008 | fmt.Sprintf("Exec: user \"%s\" invalid: %v", A.UID, err)
1009 | return
1010 | }
1011 | u64, err := strconv.ParseUint(user_.Uid, 10, 32)
1012 | if err != nil {
1013 | fmt.Sprintf("Exec: non-integer uid! Is it linux?")
1014 | return
1015 | }
1016 | c.UID = uint32(u64)
1017 |
1018 | gid := user_.Gid
1019 | if len(A.GID) > 0 {
1020 | group, err := user.LookupGroup(A.GID)
1021 | if err != nil {
1022 | fmt.Sprintf("Exec: group \"%s\" invalid: %v", A.GID, err)
1023 | }
1024 | gid = group.Gid
1025 | }
1026 | g64, err := strconv.ParseUint(gid, 10, 32)
1027 | if err != nil {
1028 | fmt.Sprintf("Exec: non-integer gid! Is it linux?")
1029 | return
1030 | }
1031 | c.GID= uint32(g64)
1032 |
1033 |
1034 | if *VERBOSE || *DEBUG {
1035 | fmt.Printf("Exec: %v %v\n", c, CTRL_WORD)
1036 | }
1037 | r := exec.ExecCommand(&c)
1038 |
1039 | if *VERBOSE || *DEBUG {
1040 | fmt.Printf("%v = %v\n", string(r.StdOut), string(r.StdErr))
1041 | }
1042 |
1043 | }
1044 |
1045 | // Perform actions depending on WindowClasses[]
1046 | func setWindowActions() {
1047 | WC = nil
1048 | // Depending on WindowClass
1049 | for _, w := range WindowClasses {
1050 | if w.re != nil {
1051 | if ActiveWindowClass == "" { // Empty class name match empty regex
1052 | continue
1053 | } else {
1054 | if w.re.MatchString(ActiveWindowClass) {
1055 | WC = &w
1056 | break
1057 | }
1058 | }
1059 | } else {
1060 | WC = &w
1061 | break
1062 | }
1063 | }
1064 | return
1065 | }
1066 |
1067 | func testAction(t *TSequences) bool {
1068 | TEST:
1069 | for _, test := range *t {
1070 | if test.OFF != nil {
1071 | for ctrl, state := range CTRL {
1072 | if state && test.OFF.MatchString(ctrl) { continue TEST }
1073 | }
1074 | }
1075 | if test.ON != nil {
1076 | if len(CTRL) < 1 { continue TEST }
1077 | on := false
1078 | for ctrl, state := range CTRL {
1079 | if state && test.ON.MatchString(ctrl) {
1080 | on = true
1081 | break
1082 | }
1083 | }
1084 | if !on { continue TEST }
1085 | }
1086 | if test.SEQ != nil {
1087 | if test.SEQ.MatchString(TAIL.String()[1:]) {
1088 | tail := test.SEQ.FindString(TAIL.String()[1:]) // The last keys must be omited, e.g. while retyping word.
1089 | // Count tail commas
1090 | EXTRA = strings.Count(tail, ",") + 1
1091 | skip := 0
1092 | for i := 1; i <= EXTRA; i++ { // Check that the extra keys are in ADD[] collection
1093 | if !ADD[ TEST[len(TEST) - i].code ] {
1094 | skip++ // Collected key is not an "EXTRA"
1095 | }
1096 | }
1097 | EXTRA -= skip
1098 | return true
1099 | }
1100 | }
1101 | }
1102 | return false
1103 | }
1104 |
1105 | // ActionSet is the chain of (one ore more) TAction
1106 | func doAction(name *string) { // name of ActionSet
1107 | a, ok := ActionSet[*name]
1108 | if !ok { return } // Action not found?!
1109 |
1110 | for _, act := range a.Action {
1111 | if Action.MatchString(act) { // Action.xxx >> recursive call
1112 | if *DEBUG {
1113 | fmt.Println(act, "[]")
1114 | }
1115 | name := strings.TrimLeft(ActionName.FindString(act), ".")
1116 | doAction(&name)
1117 | } else {
1118 | if _, ok = ACTIONS[act]; !ok {
1119 | fmt.Printf("WTF! No such action \"%s\"", act)
1120 | return
1121 | }
1122 | if *DEBUG {
1123 | fmt.Println(act)
1124 | }
1125 | ACTIONS[act](&a)
1126 | }
1127 | }
1128 |
1129 | return
1130 | }
1131 |
1132 | func doWindowActions() {
1133 | TAIL.Reset()
1134 |
1135 | if WC == nil { return }
1136 | if WC.Actions == "" { return }
1137 |
1138 | // Test sequence
1139 | l := Actions.SeqLength
1140 | if l > len(TEST) {
1141 | l = len(TEST)
1142 | }
1143 | for i := len(TEST) - l ; i < len(TEST); i++ {
1144 | TAIL.WriteString("," + key_name[TEST[i].code] + ":" + strconv.Itoa(int(TEST[i].value)))
1145 | }
1146 | if *DEBUG {
1147 | fmt.Println(TAIL.String()[1:])
1148 | }
1149 | if testAction(&NewSentence) {
1150 | if *VERBOSE || *DEBUG {
1151 | fmt.Printf("NewSentence: %s\n", TAIL.String()[1:])
1152 | }
1153 | dropBuffers()
1154 | return
1155 | }
1156 | if testAction(&Compose) {
1157 | if *VERBOSE || *DEBUG {
1158 | fmt.Printf("Compose: %s\n", TAIL.String()[1:])
1159 | }
1160 | COMPOSE++
1161 | return
1162 | }
1163 | if testAction(&TypeClipboard) {
1164 | if *VERBOSE || *DEBUG {
1165 | fmt.Printf("TypeClipboard: %s\n", TAIL.String()[1:])
1166 | }
1167 | typeClipboard(nil)
1168 | return
1169 | }
1170 | if testAction(&NewWord) {
1171 | if *VERBOSE || *DEBUG {
1172 | fmt.Printf("NewWord: %s\n", TAIL.String()[1:])
1173 | }
1174 | newWord()
1175 | return
1176 | }
1177 | for name, act := range ActSeq { // Is there some reason to do more then 1 action?
1178 | if testAction(&act) {
1179 | if *VERBOSE || *DEBUG {
1180 | fmt.Printf("%s: %s\n", name, TAIL.String()[1:])
1181 | }
1182 | doAction(&name)
1183 | }
1184 | }
1185 | return
1186 | }
1187 |
1188 | func checkAppend(event t_key, slice ...*t_keys) {
1189 | if event.value == 2 { // Repeated code
1190 | if REPEATED[event.code] {
1191 | return
1192 | } else {
1193 | REPEATED[event.code] = true
1194 | }
1195 | } else {
1196 | REPEATED[event.code] = false
1197 | }
1198 |
1199 | switch event.code {
1200 | case evdev.KEY_LEFTCTRL, evdev.KEY_LEFTSHIFT, evdev.KEY_LEFTALT, evdev.KEY_RIGHTCTRL, evdev.KEY_RIGHTSHIFT, evdev.KEY_RIGHTALT, evdev.KEY_LEFTMETA, evdev.KEY_RIGHTMETA:
1201 | if event.value > 0 {
1202 | CTRL[ key_name[event.code] ] = true
1203 | } else {
1204 | delete(CTRL, key_name[event.code])
1205 | }
1206 | if *DEBUG {
1207 | fmt.Println(CTRL)
1208 | }
1209 | }
1210 | getXModifiers() // X can lag while setting NUMLOCK state (and m.b. CAPSLOCK too), so check it after each key event
1211 |
1212 | if ! checkLanguageId() { return } // Don't proceed with extra languages
1213 |
1214 |
1215 | if getActiveWindowId() { // New focused window detected
1216 | // Drop buffers, but store this event
1217 | dropBuffers()
1218 | setWindowActions()
1219 | }
1220 |
1221 | for _, key := range slice {
1222 | *key = append(*key, event)
1223 | }
1224 |
1225 | doWindowActions()
1226 | return
1227 | }
1228 |
1229 | func addKey(event t_key) {
1230 | checkAppend(event, &TEST, &WORD, &SENTENCE)
1231 | return
1232 | }
1233 |
1234 | func testKey(event t_key) {
1235 | checkAppend(event, &TEST)
1236 | return
1237 | }
1238 |
1239 | func dropKey(event t_key) {
1240 | dropBuffers()
1241 | return
1242 | }
1243 |
1244 | func events(device *evdev.InputDevice) {
1245 | name, _ := device.Name()
1246 | for {
1247 | event, err := device.ReadOne()
1248 | if err != nil {
1249 | fmt.Printf("Closing device \"%s\" due to an error:\n\"\"\" %s \"\"\"\n", name, err)
1250 | return
1251 | }
1252 |
1253 | // fmt.Printf(" K type %v, %v = %v\n", evdev.TypeName(event.Type), event.Code, event.Value)
1254 | if event.Type == evdev.EV_KEY { // Key events
1255 | if (event.Code >= evdev.BTN_LEFT) && (event.Code <= evdev.BTN_TASK) { // Mouse keys
1256 | miceEvents <- t_key{uint16(event.Code), event.Value}
1257 | } else {
1258 | if key_name[uint16(event.Code)] != "" { // Don't collect unknown input
1259 | keyboardEvents <- t_key{uint16(event.Code), event.Value}
1260 | }
1261 | }
1262 | }
1263 | }
1264 | }
1265 |
1266 | func connectEvents(connectPath string) {
1267 | devicePaths, err := evdev.ListDevicePaths()
1268 | if err != nil {
1269 | panic(fmt.Sprintf("Events error: Unable to list devices: %s", err))
1270 | return
1271 | }
1272 | for _, dev := range devicePaths {
1273 | if (connectPath != "") && (dev.Path != connectPath) {
1274 | continue
1275 | }
1276 | skip := true
1277 | d, err := evdev.Open(dev.Path)
1278 | if err != nil {
1279 | fmt.Printf("? %s:\t%s\n", dev.Path, dev.Name)
1280 | fmt.Printf("Cannot read %s: %v\n", dev.Path, err)
1281 | continue
1282 | }
1283 | if ScanDevices.BypassRE.MatchString(dev.Name) {
1284 | fmt.Printf("- %s:\t%s\n", dev.Path, dev.Name)
1285 | continue
1286 | }
1287 |
1288 | for _, t := range d.CapableTypes() {
1289 | // fmt.Printf(" Event type %d (%s)\n", t, evdev.TypeName(t))
1290 | if t == evdev.EV_KEY {
1291 | go events(d)
1292 | skip = false
1293 | fmt.Printf(" %s:\t%s\n", dev.Path, dev.Name)
1294 | break
1295 | }
1296 | }
1297 | if skip {
1298 | fmt.Printf("x %s:\t%s\n", dev.Path, dev.Name)
1299 | }
1300 | }
1301 | return
1302 | }
1303 |
1304 | // https://gravitational.com/blog/golang-ssh-bastion-graceful-restarts/
1305 | func forkChild() (*os.Process, error) {
1306 | // Pass stdin, stdout, and stderr to the child.
1307 | files := []*os.File{
1308 | os.Stdin,
1309 | os.Stdout,
1310 | os.Stderr,
1311 | }
1312 |
1313 | // Get current process name and directory.
1314 | execName, err := os.Executable()
1315 | if err != nil {
1316 | return nil, err
1317 | }
1318 | execDir := filepath.Dir(execName)
1319 |
1320 | // Spawn child process.
1321 | p, err := os.StartProcess(execName, os.Args, &os.ProcAttr{
1322 | Dir: execDir,
1323 | Env: os.Environ(),
1324 | Files: files,
1325 | Sys: &syscall.SysProcAttr{},
1326 | })
1327 | if err != nil {
1328 | return nil, err
1329 | }
1330 |
1331 | return p, nil
1332 | }
1333 |
1334 | func Respawn(*TAction) { // Completelly respawn xswitcher.
1335 | p, err := forkChild()
1336 | if err != nil {
1337 | fmt.Printf("Unable to fork child: %v.\n", err)
1338 | return
1339 | }
1340 | fmt.Printf("Forked child %v.\n", p.Pid)
1341 | os.Exit(0)
1342 | }
1343 |
1344 | func typeClipboard(A *TAction) { // Try to type the text from clipboard to virtual keyboard.
1345 | if ! clipboardOk {
1346 | err := clipboard.Init()
1347 | if err != nil {
1348 | fmt.Printf("Unable to read from the clipboard: %v.\n", err)
1349 | return
1350 | }
1351 | }
1352 | clipboardOk = true
1353 | b := clipboard.Read(clipboard.FmtText)
1354 | if b == nil { return }
1355 |
1356 | // fmt.Println(scancodes.SequenceForString(string(b)))
1357 | // return
1358 | clip := strings.Split(scancodes.SequenceForString(string(b)), " ")
1359 | for _, cc := range clip {
1360 | // fmt.Printf("%v\n", cc)
1361 | c := strings.Split(cc, "+")
1362 | if len(c) > 1 {
1363 | sendKey(t_key{uint16(key_def["L_SHIFT"]), 1})
1364 | sendKey(t_key{uint16(key_def[c[1]]), 1})
1365 | sendKey(t_key{uint16(key_def[c[1]]), 0})
1366 | sendKey(t_key{uint16(key_def["L_SHIFT"]), 0})
1367 | } else {
1368 | if cc == "Enter" { cc = "ENTER" }
1369 | if cc == "Space" { cc = "SPACE" }
1370 | sendKey(t_key{uint16(key_def[cc]), 1})
1371 | sendKey(t_key{uint16(key_def[cc]), 0})
1372 | }
1373 | }
1374 | }
1375 |
1376 | func serve() {
1377 | var event t_key
1378 |
1379 | stat, err := os.Stat(ScanDevices.Test)
1380 | if err != nil {
1381 | panic(err)
1382 | }
1383 | now := time.Now()
1384 |
1385 | // Must wait for DE to be started. Otherwise, DE sees stupid keyboard and unmaps my rigth alt|win keys at all!
1386 | if now.Sub(stat.ModTime()) < (time.Duration(ScanDevices.Respawn) * time.Second) {
1387 | go func() {
1388 | time.Sleep((time.Duration(ScanDevices.Respawn) * time.Second) - now.Sub(stat.ModTime()))
1389 | Respawn(nil)
1390 | }()
1391 | }
1392 |
1393 | display = C.XOpenDisplay(nil);
1394 | if display == nil {
1395 | panic("Error while XOpenDisplay()!")
1396 | }
1397 | // Set callback https://stackoverflow.com/questions/32947511/cgo-cant-set-callback-in-c-struct-from-go
1398 | C.set_handle_error()
1399 | x_class = C.XAllocClassHint()
1400 |
1401 | for {
1402 | select {
1403 | case event = <- miceEvents: // code is always 0x4, while value is 0x90000 + button(1,2,3...)
1404 | if WC != nil && WC.MouseClickDrops {
1405 | dropKey(event)
1406 | }
1407 | case event = <- keyboardEvents:
1408 | if event.code < 0 || event.code > 767 { // Fuse against out-of-bounds: in old times there was need in.
1409 | fmt.Printf("!!! Invalid event code: %d\n", event.code);
1410 | } else {
1411 | if *TEST_MODE {
1412 | fmt.Fprintf(os.Stderr, ",%s:%d", key_name[event.code], event.value)
1413 | continue
1414 | }
1415 | KEYS[event.code](event)
1416 | }
1417 | }
1418 | }
1419 | }
1420 |
1421 | func main() {
1422 | var err error
1423 | defer func() { // Report panic, if one occured
1424 | if *DEBUG { return } // StackTrace is only interesting along debug
1425 | if r := recover(); r != nil {
1426 | fmt.Printf("%v\n", r)
1427 | }
1428 | }()
1429 |
1430 | // Hooks hashtable
1431 | ACTIONS["DropBuffers"] = DropBuffers // Drop all buffers
1432 | ACTIONS["Clean"] = Clean // New word (clean word buffers)
1433 | ACTIONS["RetypeWord"] = RetypeWord
1434 | ACTIONS["Switch"] = Switch
1435 | ACTIONS["Layout"] = Layout
1436 | ACTIONS["Respawn"] = Respawn
1437 | ACTIONS["TypeClipboard"] = typeClipboard // Try to type the text from clipboard to virtual keyboard
1438 | ACTIONS["Exec"] = Exec
1439 |
1440 | config() // Parse config
1441 | sequences() // Compile expressions
1442 | keys() // Initialize key actions
1443 |
1444 | connectEvents("") // Start keyloggers
1445 |
1446 | // Attach virtual keyboard
1447 | kb, err = keybd_event.NewKeyBonding()
1448 | if err != nil {
1449 | panic(err)
1450 | }
1451 |
1452 | // Create new inotify watcher.
1453 | watcher, err := fsnotify.NewWatcher()
1454 | if err != nil {
1455 | panic(err)
1456 | }
1457 | defer watcher.Close()
1458 |
1459 | go func() {
1460 | for {
1461 | select {
1462 | case event, ok := <-watcher.Events:
1463 | if !ok {
1464 | fmt.Printf("***WTF***: read(watcher.Events) != ok\n")
1465 | continue
1466 | }
1467 | if event.Has(fsnotify.Create) {
1468 | fmt.Printf("New input device: %s\n", event.Name)
1469 | time.Sleep(1000 * time.Millisecond)
1470 | connectEvents(event.Name)
1471 | }
1472 | case err, ok := <-watcher.Errors:
1473 | if !ok {
1474 | fmt.Printf("***WTF***: read(watcher.Errors) != ok\n")
1475 | continue
1476 | }
1477 | fmt.Printf("watcher error:", err)
1478 | }
1479 | }
1480 | }()
1481 |
1482 | // inotify on "/dev/input"
1483 | err = watcher.Add("/dev/input")
1484 | if err != nil {
1485 | panic(err)
1486 | }
1487 |
1488 | serve() // Main loop
1489 | }
1490 |
--------------------------------------------------------------------------------
/xswitcher.conf:
--------------------------------------------------------------------------------
1 | # xswitcher config file. Uses TOML markup language.
2 | [ScanDevices]
3 | # Must exist on start. Self-respawn in case it is younger then 30s
4 | Test = "/dev/input/event0"
5 | Respawn = 30
6 | # Search mask
7 | Search = "/dev/input/event*"
8 | # In my thinkPads there are such a pseudo-keyboards whith tons of unnecessary events.
9 | Bypass = "(?i)Video|Camera" # "(?i)" obviously differs from "classic" pcre's.
10 |
11 | [Keyboard]
12 | Delay = 5 # Delay in the virtual keyboard before sending the next event
13 |
14 | [Templates] # "@name@" to simplify expressions
15 | # Words can consist of these chars (regex) !!! There must be only "canonic" key names, or regex will fail to match !!!
16 | "WORD" = "([0-9A-Z=-]|GRAVE|APOSTROPHE|SEMICOLON|[LR]_BRACE|COMMA|DOT|(BACK)?SLASH|KP[0-9])"
17 | "SEPARATOR" = "(((BACK)?SPACE)|([=-]|(KP)?MINUS|(KP)?ENTER|ESC|TAB))"
18 | "COMPOSE" = "([0-9=-]|[LR]_BRACE)"
19 |
20 | # actions = (Add, Drop, Test), key codes are defined in "keys.go".
21 | # !!! To be converted into jump matrix inside. Avoid stupid cyclic tests!!!
22 | [ActionKeys]
23 | Layouts = [0, 1] # Don't impact extra languages (e.g., Chinese)
24 |
25 | # Collect key and do the test for command sequence
26 | # !!! Repeat codes (code=2) must be collected once per key!
27 | Add = ["1..0", "-", "=", "BACKSPACE", "Q..]", "L_CTRL..CAPS", "N_LOCK", "S_LOCK",
28 | "KP7..KPDOT", "R_CTRL", "KPSLASH", "R_ALT", "KPEQUAL..PAUSE",
29 | "KPCOMMA", "L_META..COMPOSE", "KPLEFTPAREN", "KPRIGHTPAREN"]
30 |
31 | # Drop all collected keys, including this. This is default action.
32 | Drop = ["ESC", "TAB", "ENTER", "KPENTER", "LINEFEED..POWER"]
33 |
34 | # Store extra map for these keys, when any is in "down" state.
35 | # State is checked via "OFF:"|"ON:" conditions in action.
36 | # (Also, state of these keys must persist between buffer drops.)
37 | # ToDo: StateKeys are hardcoded now.
38 | StateKeys = ["L_CTRL", "L_SHIFT", "L_ALT", "L_META", "CAPS", "N_LOCK", "S_LOCK",
39 | "R_CTRL", "R_SHIFT", "R_ALT", "R_META"]
40 |
41 | # Test only, but don't collect.
42 | # E.g., I use F12 instead of BREAK on dumb laptops whith shitty keyboards (new ThinkPads)
43 | Test = ["F1..F10", "ZENKAKUHANKAKU", "102ND", "F11", "F12",
44 | "RO..KPJPCOMMA", "SYSRQ", "SCALE", "HANGEUL..YEN",
45 | "STOP..SCROLLDOWN", "NEW..MAX"]
46 |
47 |
48 | # Some behaviour can depend on application currently doing the input.
49 | # During runtime, [WindowClasses] are checked in the order in wich they are declared in this config.
50 | [[WindowClasses]]
51 | # VNC, VirtualBox, qemu etc. emulates there input independently, so never intercept.
52 | # With the exception of some stupid VNC clients, which does high-level (layout-based) keyboard input.
53 | Regex = "^(VirtualBox|Focus-Proxy-Window)"
54 | Actions = "" # Do nothing while focus stays in VirtualBox | ATEN-based java VNC-console
55 |
56 | [[WindowClasses]]
57 | Regex = "^konsole"
58 | # In general, mouse clicks leads to unpredictable (at the low-level where xswitcher resides) cursor jumps.
59 | # So, it's good choise to drop all buffers after click.
60 | # But some windows, e.g. terminals, can stay out of this problem.
61 | MouseClickDrops = false
62 | Actions = "Actions"
63 |
64 | [[WindowClasses]] # Default behaviour: no Regex (or wildcard like ".")
65 | MouseClickDrops = true
66 | Actions = "Actions"
67 |
68 |
69 | # action = [ test1, test2, ... ]
70 | # test = (ON|OFF|SEQ):(regex)
71 | # "ON:(regex)" - True if at least one of pressed state keys matches regex.
72 | # "OFF:(regex)" - True if no one of state keys matches regex.
73 | # Note the virtual state key "WORD". It's "pressed" just after the RetypeWord and stays down until NewWord.
74 | # "SEQ:(regex)" — True if last key events (the comma-separated chain of up to SeqLength events) matches regex.
75 | # Use "xswitcher -t" in command line to view typed chain in STDERR.
76 | [Actions]
77 | # Inverse regex is hard to understand, so extract negation to external condition.
78 | # Expresions will be checked in direct order, one-by-one. Condition succceds when ALL results are True.
79 | # Maximum key sequence length, extra keys will be dropped. More length - more CPU.
80 | SeqLength = 12
81 | # Count only those chars in word which must be removed (by sending the same count of BS keys) while "RetypeWord".
82 | WordChars = "(^@WORD@:0$)"
83 | # Drop word buffer and start collecting new one
84 | # !!! Note that (@WORD@:1) /key-press/ at the end of regex allows to collect the last char,
85 | # while (@WORD@:0) cuts the WORD strictly at the end of sequence. !!!
86 | # --- In my layout, R_META selects 5'th layout and R_ALT does "compose". ---
87 | NewWord = [ "SEQ:(@SEPARATOR@:[12]),(((CAPS:[012])|([LR]_SHIFT:[12])|(R_META:0)|((@WORD@|@SEPARATOR@):0)),)*(@WORD@:1)", # "@WORD@:0" then collects the char
88 | "SEQ:(@WORD@:2,@WORD@:0)", # Drop repeated char at all: unlikely it needs correction
89 | "SEQ:(BACKSPACE:0)", # Drop buffer just afrer BACKSPACE
90 | # Control sequences. !!! Must be dropped ASAP.
91 | "SEQ:((([LR]_CTRL|L_ALT|[LR]_META):[12])(,((@WORD@|@SEPARATOR@):[012]))+(,(([LR]_CTRL|L_ALT|[LR]_META):0))+(,@WORD@:1)?)", # "@WORD@:0" then collects the char
92 | "ON:(WORD) SEQ:(,@WORD@:1)" ] # New input after previous correction. "@WORD@:0" then collects the char
93 | # Drop all buffers
94 | NewSentence = [ "SEQ:(ENTER:0)" ]
95 |
96 | # In some windows the single char must be deleted by single BS, so there is need in compose sequence detector.
97 | Compose = [ "OFF:(CTRL|L_ALT|META|SHIFT) SEQ:(R_ALT:1(,R_ALT:2)?(,[LR]_SHIFT:[12])*(,@COMPOSE@:1,@COMPOSE@:0)(,[LR]_SHIFT:0)?(,@COMPOSE@:1,@COMPOSE@:0),R_ALT:0)",
98 | "OFF:(CTRL|L_ALT|META|SHIFT) SEQ:(R_ALT:1(,R_ALT:2)?(,[LR]_SHIFT:[12])*,@COMPOSE@:1,@COMPOSE@:0(,[LR]_SHIFT:0)?,R_ALT:0(,[LR]_SHIFT:0)?,@COMPOSE@:1,@COMPOSE@:0)" ]
99 |
100 | # !!! Note that xswitcher counts extra keys as the length of matched SEQ:() !!!
101 | # So, any regex for "RetypeWord" SEQ must be EXACT ONE. Otherwise, xswitcher will generate the troubles for You.
102 | "Action.RetypeWord" = [ "OFF:(CTRL|ALT|META|SHIFT) SEQ:(PAUSE:1,PAUSE:0)",
103 | "OFF:(CTRL|ALT|META|SHIFT) SEQ:(F12:1,F12:0)" ]
104 |
105 | "Action.CyclicSwitch" = [ "OFF:(R_CTRL|ALT|META|SHIFT) SEQ:(L_CTRL:1,L_CTRL:0)" ] # Single short LEFT CONTROL
106 | "Action.Respawn" = [ "OFF:(CTRL|ALT|META|SHIFT) SEQ:(S_LOCK:2,S_LOCK:0)" ] # Long-pressed SCROLL LOCK
107 |
108 | "Action.Layout0" = [ "OFF:(CTRL|ALT|META|R_SHIFT) SEQ:(L_SHIFT:1,L_SHIFT:0)" ] # Single short LEFT SHIFT
109 | "Action.Layout1" = [ "OFF:(CTRL|ALT|META|L_SHIFT) SEQ:(R_SHIFT:1,R_SHIFT:0)" ] # Single short RIGHT SHIFT
110 |
111 | "Action.Hook1" = [ "OFF:(CTRL|R_ALT|META|SHIFT) SEQ:(L_ALT:1,L_ALT:0)" ]
112 |
113 |
114 | # Action is the array, so actions could be chained (m.b., infinitely... Have I to check this?).
115 | # For each action type, extra named parameters could be collected. Invalid parameters will be ignored(?).
116 | [Action.RetypeWord] # Switch layout, drop last word and type it again
117 | Action = [ "Action.CyclicSwitch", "RetypeWord" ] # Call Switch() between layouts tuned below, then RetypeWord()
118 |
119 | [Action.CyclicSwitch] # Cyclic layout switching
120 | Action = [ "Switch" ] # Internal layout switcher func
121 | Layouts = [0, 1]
122 |
123 | [Action.Layout0] # Direct layout selection
124 | Action = [ "Layout" ] # Internal layout selection func
125 | Layout = 0
126 |
127 | [Action.Layout1] # Direct layout selection
128 | Action = [ "Layout" ] # Internal layout selection func
129 | Layout = 1
130 |
131 | [Action.Respawn] # Completely respawn xswitcher. Reload config as well
132 | Action = [ "Respawn" ]
133 |
134 | [Action.Hook1] # Run external commands
135 | Action = [ "Exec" ]
136 | Exec = "cat > /tmp/xxx" # All the input after the 1'st space will be reassembled into the CLI args.
137 | # Timeout = 1000 # Wait up to 1 second, then kill the executing process.
138 | # Wait = true # Wait for termination, then output the result to STDOUT|STDERR.
139 | # External hook can process collected buffer by it's own means.
140 | # The last typed word, or sentence, or just the custom string could be passed to stdIn.
141 | SendBuffer = "WORD" # "WORD"|"SENTENCE"|"any custom input\n"
142 |
143 | UseShell = true # Execute inside /bin/bash
144 | # Directory = "/path/to/" # Change the working directory to this one.
145 | CleanEnv = true # Run command inside the clean environment.
146 | Environment = [ "var=value" ] # A set of environment variables.
147 |
148 | # Use the specific user/group.
149 | UID = "root"
150 | GID = "root"
151 |
--------------------------------------------------------------------------------