K65 Studio: Linux control app for the Corsair K65 PLUS Wireless

Bragi protocol over hidraw, device service with heartbeat and
notifications, PySide6 UI with animated preview, profiles, tray,
autostart, udev rule and installer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-23 21:02:59 +02:00
commit 7e276912da
23 files changed
+2631

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
__pycache__/
*.pyc
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+64
View File
@@ -0,0 +1,64 @@
# K65 Studio
Linux-Software für die **Corsair K65 PLUS Wireless**: Beleuchtung, Helligkeit, Spielmodus,
Ruhezustand, Akkustand und Profile, also das, was iCUE unter Windows für diese Tastatur erledigt.
Läuft im Tray und hält die Einstellungen, solange du angemeldet bist.
Getestet unter CachyOS (KDE/Wayland) mit dem Slipstream-Empfänger `1b1c:2b07`.
## Installation
```sh
sudo pacman -S --needed pyside6 # falls noch nicht vorhanden
./install.sh
```
`install.sh` installiert die App nach `~/.local/share/k65studio`, einen Starter `k65studio` und
einen Menüeintrag. Außerdem richtet es (mit `sudo`) die udev-Regel
`/etc/udev/rules.d/60-k65studio.rules` ein, damit dein Benutzer ohne Root-Rechte auf die
Tastatur zugreifen darf.
Ohne Installation direkt aus dem Repository starten (die udev-Regel muss trotzdem installiert sein):
```sh
python3 -m k65studio
```
## Funktionen
| Bereich | Was geht |
| --- | --- |
| Beleuchtung | Statisch, Regenbogenwelle, Spiralregenbogen, Farbwelle, Farbwechsel, Farbpuls, Regen, Aquarell, Tippen (Taste/Welle), Visier, Aus. Mit eigenen Farben oder Zufallsfarben und drei Geschwindigkeiten. |
| Helligkeit | 0–100 % |
| Spielmodus | Sperrt wahlweise Win/Super-Taste, Alt+Tab, Alt+F4, Shift+Tab |
| Energie | Ruhezustand nach X Minuten |
| Status | Verbindung, Akkustand (mit Warnung bei 15 %), Firmware von Tastatur und Empfänger, Seriennummer |
| Profile | Beliebig viele, umschaltbar im Fenster und im Tray-Menü |
| Programm | Tray-Icon, Autostart beim Anmelden, einzelne Instanz |
Im Funkbetrieb rendert die Tastatur die Effekte selbst. Per-Key-Farben gibt es kabellos auch
unter iCUE nicht.
## Wie es funktioniert
Die App spricht das Corsair-„Bragi“-Protokoll direkt über `/dev/hidraw` (Interface 1 des
Empfängers). Beim Start schaltet sie die Tastatur in den Software-Modus und schickt alle 10
Sekunden einen Heartbeat. Beim Beenden gibt sie die Tastatur an den Hardware-Modus zurück
(abschaltbar unter *Einstellungen*).
Das Protokollwissen stammt aus den Open-Source-Projekten
[OpenLinkHub](https://github.com/jurkovic-nikola/OpenLinkHub) und
[OpenRGB](https://gitlab.com/CalcProgrammer1/OpenRGB).
Einstellungen liegen in `~/.config/k65studio/config.json`.
## Entwicklung
```sh
python3 -m unittest discover -s tests
python3 -m k65studio --debug
```
## Lizenz
GPL-3.0-or-later
Executable
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
# Installs K65 Studio for the current user (app) and the udev rule (system, needs sudo).
set -eu
SRC="$(cd "$(dirname "$0")" && pwd)"
PREFIX="${PREFIX:-$HOME/.local}"
APPDIR="$PREFIX/share/k65studio"
python3 -c "import PySide6" 2>/dev/null || { echo "PySide6 fehlt: sudo pacman -S pyside6"; exit 1; }
mkdir -p "$APPDIR" "$PREFIX/bin" "$PREFIX/share/applications" "$PREFIX/share/icons/hicolor/scalable/apps"
rm -rf "$APPDIR/k65studio"
cp -r "$SRC/k65studio" "$APPDIR/"
find "$APPDIR" -name __pycache__ -prune -exec rm -rf {} +
cat > "$PREFIX/bin/k65studio" <<LAUNCHER
#!/bin/sh
PYTHONPATH="$APPDIR\${PYTHONPATH:+:\$PYTHONPATH}" exec python3 -m k65studio "\$@"
LAUNCHER
chmod +x "$PREFIX/bin/k65studio"
cp "$SRC/packaging/k65studio.desktop" "$PREFIX/share/applications/"
cp "$SRC/k65studio/assets/k65studio.svg" "$PREFIX/share/icons/hicolor/scalable/apps/"
echo "App installiert nach $APPDIR (Start: k65studio)"
if [ ! -f /etc/udev/rules.d/60-k65studio.rules ] || ! cmp -s "$SRC/packaging/60-k65studio.rules" /etc/udev/rules.d/60-k65studio.rules; then
echo "Installiere udev-Regel (sudo)..."
sudo install -m 644 "$SRC/packaging/60-k65studio.rules" /etc/udev/rules.d/60-k65studio.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --subsystem-match=hidraw
fi
echo "Fertig."
+1
View File
@@ -0,0 +1 @@
__version__ = "0.1.0"
+17
View File
@@ -0,0 +1,17 @@
import argparse
import logging
def run() -> int:
parser = argparse.ArgumentParser(prog="k65studio", description="Corsair K65 PLUS Wireless für Linux")
parser.add_argument("--minimized", action="store_true", help="nur im Tray starten")
parser.add_argument("--debug", action="store_true", help="ausführliches Logging")
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
from .app import main
return main(minimized=args.minimized)
if __name__ == "__main__":
raise SystemExit(run())
+158
View File
@@ -0,0 +1,158 @@
"""Application wiring: Qt app, tray icon, single instance and the device service."""
from __future__ import annotations
import os
import signal
import sys
from pathlib import Path
from PySide6.QtCore import QObject, QTimer, Signal
from PySide6.QtGui import QAction, QActionGroup, QIcon
from PySide6.QtNetwork import QLocalServer, QLocalSocket
from PySide6.QtWidgets import QApplication, QMenu, QSystemTrayIcon
from .device import DeviceService, DeviceState
from .profiles import Config
from .ui.main_window import MainWindow
from .ui.style import STYLESHEET
ICON = Path(__file__).parent / "assets" / "k65studio.svg"
INSTANCE_NAME = f"k65studio-{os.getuid()}"
LOW_BATTERY = 15
class _Bridge(QObject):
state = Signal(object)
class App:
def __init__(self, argv: list[str], minimized: bool):
self.qapp = QApplication(argv)
self.qapp.setApplicationName("K65 Studio")
self.qapp.setDesktopFileName("k65studio")
self.qapp.setQuitOnLastWindowClosed(False)
self.qapp.setStyleSheet(STYLESHEET)
self.icon = QIcon(str(ICON))
self.qapp.setWindowIcon(self.icon)
self.config = Config.load()
self.window = MainWindow(self.config)
self.window.closeEvent = self._close_window
self.bridge = _Bridge()
self.bridge.state.connect(self._on_state)
self.device = DeviceService(self.bridge.state.emit)
self.window.profile_changed.connect(lambda profile: self.device.apply(profile))
self.window.reinit_requested.connect(self._reinit)
self._warned_battery = False
self._hint_shown = False
self.tray = self._build_tray() if QSystemTrayIcon.isSystemTrayAvailable() else None
self.server = QLocalServer()
QLocalServer.removeServer(INSTANCE_NAME)
self.server.listen(INSTANCE_NAME)
self.server.newConnection.connect(self._show_window)
self.qapp.aboutToQuit.connect(self._shutdown)
signal.signal(signal.SIGTERM, lambda *_: self.qapp.quit())
signal.signal(signal.SIGINT, lambda *_: self.qapp.quit())
self.device.start(self.config.profile)
if not ((minimized or self.config.start_minimized) and self.tray):
self._show_window()
def _build_tray(self) -> QSystemTrayIcon:
tray = QSystemTrayIcon(self.icon)
tray.setToolTip("K65 Studio")
menu = QMenu()
menu.addAction("Öffnen", self._show_window)
self.profile_menu = menu.addMenu("Profil")
self.profile_menu.aboutToShow.connect(self._fill_profile_menu)
menu.addSeparator()
menu.addAction("Beenden", self.qapp.quit)
tray.setContextMenu(menu)
tray.activated.connect(lambda reason: reason == QSystemTrayIcon.Trigger and self._toggle_window())
tray.show()
self._tray_menu = menu
return tray
def _fill_profile_menu(self) -> None:
self.profile_menu.clear()
group = QActionGroup(self.profile_menu)
for name in self.config.profiles:
act = QAction(name, self.profile_menu, checkable=True, checked=name == self.config.active)
act.triggered.connect(lambda _=False, n=name: self.window.activate_profile(n))
group.addAction(act)
self.profile_menu.addAction(act)
def _show_window(self) -> None:
while self.server.hasPendingConnections():
self.server.nextPendingConnection().close()
self.window.showNormal()
self.window.raise_()
self.window.activateWindow()
def _toggle_window(self) -> None:
if self.window.isVisible():
self.window.hide()
else:
self._show_window()
def _close_window(self, event) -> None:
if self.tray is None:
event.accept()
self.qapp.quit()
return
event.ignore()
self.window.hide()
if not self._hint_shown:
self._hint_shown = True
self.tray.showMessage("K65 Studio", "Läuft im Hintergrund weiter, damit die Beleuchtung erhalten bleibt.",
self.icon, 4000)
def _on_state(self, state: DeviceState) -> None:
self.window.set_state(state)
if self.tray is None:
return
if state.keyboard and state.battery is not None:
self.tray.setToolTip(f"K65 Studio · K65 PLUS · Akku {state.battery} %")
if state.battery <= LOW_BATTERY and not self._warned_battery:
self._warned_battery = True
self.tray.showMessage("Akku schwach", f"K65 PLUS: noch {state.battery} %. Bitte bald laden.",
QSystemTrayIcon.Warning, 8000)
elif state.battery > LOW_BATTERY + 5:
self._warned_battery = False
else:
self.tray.setToolTip("K65 Studio · Tastatur nicht verbunden")
def _reinit(self) -> None:
self.device.stop(restore_hardware=False)
self.device = DeviceService(self.bridge.state.emit)
self.device.start(self.config.profile)
def _shutdown(self) -> None:
self.config.save()
self.device.stop(restore_hardware=self.config.restore_hardware_on_exit)
if self.tray:
self.tray.hide()
def run(self) -> int:
# Wake the interpreter regularly so Python signal handlers (SIGTERM/SIGINT) run.
self._sig_timer = QTimer(interval=300, timeout=lambda: None)
self._sig_timer.start()
return self.qapp.exec()
def notify_running_instance() -> bool:
sock = QLocalSocket()
sock.connectToServer(INSTANCE_NAME)
ok = sock.waitForConnected(300)
sock.close()
return ok
def main(minimized: bool = False) -> int:
if notify_running_instance():
return 0
return App(sys.argv, minimized).run()
+20
View File
@@ -0,0 +1,20 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#19d3c5"/>
<stop offset="0.5" stop-color="#7a2cff"/>
<stop offset="1" stop-color="#ff2d95"/>
</linearGradient>
</defs>
<rect x="3" y="15" width="58" height="34" rx="7" fill="#15171b" stroke="url(#g)" stroke-width="3"/>
<g fill="url(#g)">
<rect x="9" y="21" width="6" height="5" rx="1.2"/><rect x="17" y="21" width="6" height="5" rx="1.2"/>
<rect x="25" y="21" width="6" height="5" rx="1.2"/><rect x="33" y="21" width="6" height="5" rx="1.2"/>
<rect x="41" y="21" width="6" height="5" rx="1.2"/><rect x="49" y="21" width="6" height="5" rx="1.2"/>
<rect x="9" y="29" width="9" height="5" rx="1.2"/><rect x="20" y="29" width="6" height="5" rx="1.2"/>
<rect x="28" y="29" width="6" height="5" rx="1.2"/><rect x="36" y="29" width="6" height="5" rx="1.2"/>
<rect x="44" y="29" width="11" height="5" rx="1.2"/>
<rect x="9" y="37" width="7" height="6" rx="1.2"/><rect x="18" y="37" width="26" height="6" rx="1.2"/>
<rect x="46" y="37" width="9" height="6" rx="1.2"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

+39
View File
@@ -0,0 +1,39 @@
"""XDG autostart entry for starting minimized at login."""
from __future__ import annotations
import os
import shutil
import sys
from pathlib import Path
AUTOSTART_FILE = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "autostart" / "k65studio.desktop"
def _exec_line() -> str:
launcher = shutil.which("k65studio")
if launcher:
return f"{launcher} --minimized"
project = Path(__file__).resolve().parent.parent
return f"sh -c 'cd \"{project}\" && exec \"{sys.executable}\" -m k65studio --minimized'"
def is_enabled() -> bool:
return AUTOSTART_FILE.exists()
def set_enabled(enabled: bool) -> None:
if not enabled:
AUTOSTART_FILE.unlink(missing_ok=True)
return
AUTOSTART_FILE.parent.mkdir(parents=True, exist_ok=True)
AUTOSTART_FILE.write_text(
"[Desktop Entry]\n"
"Type=Application\n"
"Name=K65 Studio\n"
"Comment=Corsair K65 PLUS Wireless Beleuchtung und Einstellungen\n"
f"Exec={_exec_line()}\n"
"Icon=k65studio\n"
"X-GNOME-Autostart-enabled=true\n"
"X-KDE-autostart-after=panel\n"
)
+167
View File
@@ -0,0 +1,167 @@
"""Corsair "Bragi" protocol as spoken by the K65 PLUS Wireless and its Slipstream receiver.
Every packet is 64 bytes: [target, command, args...].
target 0x08 = the device behind this USB interface (receiver, or keyboard when wired)
target 0x09 = the keyboard paired to the receiver (wireless)
Responses echo [target, command, status, data...]; status 0 means success.
Protocol knowledge from the OpenLinkHub (GPL-3.0) and OpenRGB (GPL-2.0+) projects.
"""
from __future__ import annotations
import struct
from dataclasses import dataclass
VENDOR_CORSAIR = 0x1B1C
PID_SLIPSTREAM_K65 = 0x2B07
PIDS_K65_PLUS_WIRED = (0x2B10, 0x2B11, 0x2B23)
TARGET_LOCAL = 0x08
TARGET_PAIRED = 0x09
# Commands
CMD_SET = 0x01
CMD_GET = 0x02
CMD_CLOSE = 0x05
CMD_WRITE_FIRST = 0x06
CMD_WRITE_NEXT = 0x07
CMD_READ = 0x08
CMD_PREPARE = 0x09
CMD_OPEN = 0x0D
CMD_HEARTBEAT = 0x12
CMD_DEVICE_LIST = 0x24
# Properties (CMD_SET / CMD_GET)
PROP_BRIGHTNESS = 0x02 # u16, 0..1000
PROP_MODE = 0x03 # 1 = hardware, 2 = software
PROP_SLEEP = 0x0E # u32, milliseconds
PROP_BATTERY = 0x0F # u16, per mille
PROP_FIRMWARE = 0x13
PROP_GAME_MODE = 0x45 # 0/1
PROP_LOCKS = 0x4A # bitmask, see LOCK_*
MODE_HARDWARE = 0x01
MODE_SOFTWARE = 0x02
LOCK_WIN = 0x01
LOCK_ALT_TAB = 0x02
LOCK_ALT_F4 = 0x04
LOCK_SHIFT_TAB = 0x08
# Writable resources
RESOURCE_LIGHTING = 0x6D60
RESOURCE_KEYMAP = 0x02
HANDLE = 0x01
CHUNK_FIRST = 61 # 64 - [target, cmd, handle]
KEYMAP_SIZE = 123
# Notifications (second vendor interface)
NOTIFY_CONNECTION = 0x36
# Lighting effect ids
FX_STATIC = 0x207E
FX_COLOR_PULSE = 0xAD4F
FX_COLOR_SHIFT = 0xA5FA
FX_COLOR_WAVE = 0x7BFF
FX_RAINBOW_WAVE = 0xB94C
FX_RAIN = 0xA07E
FX_SPIRAL_RAINBOW = 0xAB87
FX_WATERCOLOR = 0x0022
FX_TYPE_KEY = 0xB1F9
FX_TYPE_RIPPLE = 0x09A2
FX_VISOR = 0x90C0
COLORS_NONE = 0x00
COLORS_SPECIFIC = 0x01
COLORS_RANDOM = 0x02
COLORS_ALT = 0x03
SPEED_SLOW = 0x03
SPEED_MEDIUM = 0x04
SPEED_FAST = 0x05
# Default keymap: HID usage -> function code. 57 = regular key, 59 = key with an Fn layer,
# 63 = modifier. Everything else stays 0x01 (no key at that position).
_FN_LAYER = {18, 19, 47, 48, 55, 56, 58, 59, 60, 61, *range(64, 70)}
_MODIFIERS = {105, 106, 107, 109, 110, 111, 122}
_REGULAR = {*range(4, 18), *range(20, 47), *range(49, 50), *range(51, 55), 57,
62, 63, 74, 75, 76, *range(78, 83), 108}
_REGULAR -= _FN_LAYER
def default_keymap() -> bytes:
table = bytearray([0x01] * KEYMAP_SIZE)
for usage in _REGULAR:
table[usage] = 57
for usage in _FN_LAYER:
table[usage] = 59
for usage in _MODIFIERS:
table[usage] = 63
return bytes(table)
def packet(target: int, *parts: bytes | int) -> bytes:
out = bytearray([target])
for p in parts:
out += bytes([p]) if isinstance(p, int) else p
if len(out) > 64:
raise ValueError("packet exceeds 64 bytes")
return bytes(out)
def set_property(target: int, prop: int, value: bytes) -> bytes:
return packet(target, CMD_SET, prop, 0x00, value)
def get_property(target: int, prop: int) -> bytes:
return packet(target, CMD_GET, prop)
def block_packets(target: int, payload: bytes, declared: int | None = None) -> list[bytes]:
"""Split a length-prefixed block write to HANDLE into first/next packets."""
framed = struct.pack("<HH", len(payload) if declared is None else declared, 0) + payload
chunks = [framed[i:i + CHUNK_FIRST] for i in range(0, len(framed), CHUNK_FIRST)]
return [packet(target, CMD_WRITE_FIRST if i == 0 else CMD_WRITE_NEXT, HANDLE, c)
for i, c in enumerate(chunks)]
@dataclass(frozen=True)
class Rgb:
r: int
g: int
b: int
@classmethod
def from_hex(cls, value: str) -> "Rgb":
value = value.lstrip("#")
return cls(int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16))
def hex(self) -> str:
return f"#{self.r:02x}{self.g:02x}{self.b:02x}"
LIGHTING_BLOCK_SIZE = 96
def lighting_packets(target: int, effect: int, color_mode: int = COLORS_NONE, speed: int = 0,
direction: int = 0, colors: list[Rgb] | tuple[Rgb, ...] = ()) -> list[bytes]:
"""Hardware lighting effect: id, color mode, speed, direction, then colors as (A, B, G, R)."""
body = bytearray(struct.pack("<H", effect))
body += bytes([color_mode, speed, direction, 0x00])
if colors:
body.append(len(colors))
for c in colors:
body += bytes([0xFF, c.b, c.g, c.r])
# Same declared lengths OpenLinkHub uses; everything past the colors is zero padding.
declared = 93 if effect == FX_STATIC else 89
return block_packets(target, bytes(body.ljust(LIGHTING_BLOCK_SIZE, b"\x00")), declared)
def parse_u16(resp: bytes, offset: int = 3) -> int:
return struct.unpack_from("<H", resp, offset)[0]
def parse_firmware(resp: bytes) -> str:
return f"{resp[3]}.{resp[4]}.{struct.unpack_from('<H', resp, 5)[0]}"
+381
View File
@@ -0,0 +1,381 @@
"""K65 PLUS Wireless device service.
A background thread owns the hidraw handles. It finds the Slipstream receiver (or a wired
keyboard), keeps the keyboard in software mode with heartbeats, applies profiles and reports
state changes through a callback.
"""
from __future__ import annotations
import logging
import queue
import struct
import threading
import time
from dataclasses import dataclass, field, replace
from typing import Callable
from . import bragi, effects
from .hidraw import Hidraw, enumerate_hidraw
from .profiles import Profile
log = logging.getLogger(__name__)
HEARTBEAT_INTERVAL = 10.0
DISCOVERY_INTERVAL = 2.0
RECONNECT_DELAY = 3.0
TIMEOUT = 0.5
class DeviceError(Exception):
pass
class PermissionProblem(DeviceError):
pass
@dataclass(frozen=True)
class DeviceState:
receiver: bool = False # receiver (or wired keyboard) present and opened
keyboard: bool = False # keyboard reachable
wireless: bool = True
battery: int | None = None # percent
keyboard_firmware: str = ""
receiver_firmware: str = ""
serial: str = ""
error: str = ""
class Transport:
def __init__(self, path: str):
self.dev = Hidraw(path)
self.lock = threading.Lock()
def close(self) -> None:
self.dev.close()
def transfer(self, pkt: bytes, timeout: float = TIMEOUT) -> bytes:
with self.lock:
self.dev.drain()
self.dev.write(pkt)
deadline = time.monotonic() + timeout
while (left := deadline - time.monotonic()) > 0:
resp = self.dev.read(left)
if resp and resp[0] == pkt[0] and resp[1] == pkt[1]:
return resp
raise DeviceError(f"no response to {pkt[:4].hex(' ')}")
def command(self, pkt: bytes, timeout: float = TIMEOUT) -> bytes:
resp = self.transfer(pkt, timeout)
if resp[2] != 0:
raise DeviceError(f"status {resp[2]:#04x} for {pkt[:4].hex(' ')}")
return resp
class Keyboard:
"""Commands for the keyboard, addressed through `target` on `transport`."""
def __init__(self, transport: Transport, target: int):
self.t = transport
self.target = target
def heartbeat(self) -> None:
self.t.command(bragi.packet(self.target, bragi.CMD_HEARTBEAT))
def set_mode(self, mode: int) -> None:
self.t.command(bragi.set_property(self.target, bragi.PROP_MODE, bytes([mode])))
def battery(self) -> int:
resp = self.t.command(bragi.get_property(self.target, bragi.PROP_BATTERY))
return round(bragi.parse_u16(resp) / 10)
def firmware(self) -> str:
return bragi.parse_firmware(self.t.command(bragi.get_property(self.target, bragi.PROP_FIRMWARE)))
def brightness(self, percent: int) -> None:
value = struct.pack("<H", max(0, min(100, percent)) * 10)
self.t.command(bragi.set_property(self.target, bragi.PROP_BRIGHTNESS, value))
def sleep_timer(self, minutes: int) -> None:
value = struct.pack("<I", max(1, minutes) * 60_000)
self.t.command(bragi.set_property(self.target, bragi.PROP_SLEEP, value))
def locks(self, game_mode: bool, flags: int) -> None:
self.t.command(bragi.set_property(self.target, bragi.PROP_LOCKS, bytes([flags if game_mode else 0])))
self.t.command(bragi.set_property(self.target, bragi.PROP_GAME_MODE, bytes([int(game_mode)])))
def _close_handle(self) -> None:
self.t.transfer(bragi.packet(self.target, bragi.CMD_CLOSE, bragi.HANDLE, bragi.HANDLE))
def _write_block(self, open_args: bytes, packets: list[bytes], settle: float = 0.0) -> None:
self._close_handle()
self.t.command(bragi.packet(self.target, bragi.CMD_OPEN, bragi.HANDLE, open_args))
if settle:
time.sleep(settle)
self.t.transfer(bragi.packet(self.target, bragi.CMD_PREPARE, bragi.HANDLE))
try:
for p in packets:
self.t.command(p)
finally:
self._close_handle()
def lighting(self, packets: list[bytes]) -> None:
self._write_block(struct.pack("<H", bragi.RESOURCE_LIGHTING), packets, settle=0.5)
def keymap(self) -> None:
self._write_block(bytes([bragi.RESOURCE_KEYMAP]),
bragi.block_packets(self.target, bragi.default_keymap()))
def apply(self, p: Profile, prev: Profile | None = None) -> None:
"""Send `p`; with `prev` given, only the settings that differ from it."""
def changed(*names: str) -> bool:
return prev is None or any(getattr(p, n) != getattr(prev, n) for n in names)
if prev is None:
self.set_mode(bragi.MODE_SOFTWARE)
if changed("effect", "colors", "random_colors", "speed"):
self.lighting(effects.encode(self.target, p.effect, p.colors, p.random_colors, p.speed))
if changed("brightness"):
self.brightness(p.brightness)
if changed("sleep_minutes"):
self.sleep_timer(p.sleep_minutes)
if changed("game_mode", "lock_win", "lock_alt_tab", "lock_alt_f4", "lock_shift_tab"):
flags = ((bragi.LOCK_WIN if p.lock_win else 0) | (bragi.LOCK_ALT_TAB if p.lock_alt_tab else 0)
| (bragi.LOCK_ALT_F4 if p.lock_alt_f4 else 0)
| (bragi.LOCK_SHIFT_TAB if p.lock_shift_tab else 0))
self.locks(p.game_mode, flags)
if prev is None:
self.keymap()
@dataclass
class _Handles:
transport: Transport
notify: Hidraw | None
keyboard: Keyboard
receiver: Keyboard | None # the receiver itself, wireless only
paths: tuple[str, ...] = field(default_factory=tuple)
def close(self) -> None:
self.transport.close()
if self.notify:
self.notify.close()
def find_interfaces() -> tuple[str, str | None, bool] | None:
"""Return (command hidraw, notification hidraw, wireless) for the first K65 PLUS found."""
devs = [d for d in enumerate_hidraw(bragi.VENDOR_CORSAIR) if d.bus == 3]
for pids, wireless in (((bragi.PID_SLIPSTREAM_K65,), True), (bragi.PIDS_K65_PLUS_WIRED, False)):
cmd = next((d for d in devs if d.product_id in pids and d.interface == 1), None)
if cmd:
notify = next((d for d in devs if d.product_id == cmd.product_id and d.interface == 2), None)
return cmd.path, notify.path if notify else None, wireless
return None
class DeviceService:
"""Runs the device loop in a thread. `on_state` is called from that thread."""
def __init__(self, on_state: Callable[[DeviceState], None]):
self.on_state = on_state
self.state = DeviceState()
self._profile: Profile | None = None
self._applied: Profile | None = None # what the keyboard currently has
self._jobs: queue.Queue[tuple[str, object]] = queue.Queue()
self._stop = threading.Event()
self._restore_hardware = True
self._thread = threading.Thread(target=self._run, name="k65-device", daemon=True)
self._h: _Handles | None = None
self._reconnect_at: float | None = None
# --- public API (any thread) ---
def start(self, profile: Profile) -> None:
self._profile = replace(profile, colors=list(profile.colors))
self._thread.start()
def apply(self, profile: Profile) -> None:
self._jobs.put(("apply", replace(profile, colors=list(profile.colors))))
def stop(self, restore_hardware: bool = True, timeout: float = 3.0) -> None:
self._restore_hardware = restore_hardware
self._stop.set()
self._thread.join(timeout)
# --- device thread ---
def _set(self, **changes) -> None:
new = replace(self.state, **changes)
if new != self.state:
self.state = new
self.on_state(new)
def _run(self) -> None:
next_heartbeat = 0.0
while not self._stop.is_set():
if self._h is None:
if not self._open():
self._stop.wait(DISCOVERY_INTERVAL)
continue
next_heartbeat = time.monotonic() + HEARTBEAT_INTERVAL
try:
self._process_jobs()
self._read_notifications(0.2)
now = time.monotonic()
if self._reconnect_at is not None and now >= self._reconnect_at:
self._reconnect_at = None
self._init_keyboard()
if now >= next_heartbeat:
next_heartbeat = now + HEARTBEAT_INTERVAL
self._heartbeat()
except OSError as e:
log.warning("device lost: %s", e)
self._close()
self._set(receiver=False, keyboard=False, battery=None, error="Gerät getrennt")
self._shutdown()
def _open(self) -> bool:
found = find_interfaces()
if not found:
self._set(receiver=False, keyboard=False, error="Kein K65 PLUS gefunden")
return False
cmd_path, notify_path, wireless = found
try:
transport = Transport(cmd_path)
notify = Hidraw(notify_path) if notify_path else None
except PermissionError:
self._set(receiver=False, keyboard=False,
error=f"Keine Berechtigung für {cmd_path}. udev-Regel installieren (siehe README).")
return False
except OSError as e:
self._set(receiver=False, keyboard=False, error=str(e))
return False
target = bragi.TARGET_PAIRED if wireless else bragi.TARGET_LOCAL
receiver = Keyboard(transport, bragi.TARGET_LOCAL) if wireless else None
self._h = _Handles(transport, notify, Keyboard(transport, target), receiver)
self._set(receiver=True, wireless=wireless, error="")
if receiver:
try:
self._set(receiver_firmware=receiver.firmware(), serial=self._paired_serial())
receiver.set_mode(bragi.MODE_SOFTWARE)
except DeviceError as e:
log.warning("receiver init: %s", e)
self._init_keyboard()
return True
def _paired_serial(self) -> str:
"""Read the receiver's pairing list and return the keyboard serial."""
t = self._h.transport
res = struct.pack("<B", bragi.CMD_DEVICE_LIST)
t.transfer(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_CLOSE, bragi.HANDLE, res))
t.command(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_OPEN, 0x00, res))
t.transfer(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_PREPARE, 0x00, res))
buf = t.command(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_READ, 0x00, res))
t.transfer(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_CLOSE, bragi.HANDLE))
if buf[5] == 0:
return ""
return buf[11:11 + buf[10]].decode("ascii", "replace")
def _init_keyboard(self) -> None:
kb = self._h.keyboard
try:
kb.heartbeat()
except DeviceError:
self._set(keyboard=False, battery=None)
return
try:
kb.set_mode(bragi.MODE_SOFTWARE)
self._set(keyboard=True, keyboard_firmware=kb.firmware(), battery=self._battery(kb))
self._applied = None
if self._profile:
kb.apply(self._profile)
self._applied = self._profile
self._set(error="")
except DeviceError as e:
log.warning("keyboard init: %s", e)
self._set(error=f"Initialisierung fehlgeschlagen: {e}")
def _battery(self, kb: Keyboard) -> int | None:
if not self.state.wireless:
return None
try:
return kb.battery()
except DeviceError:
return self.state.battery
def _heartbeat(self) -> None:
if self._h.receiver:
try:
self._h.receiver.heartbeat()
except DeviceError as e:
log.debug("receiver heartbeat: %s", e)
try:
self._h.keyboard.heartbeat()
except DeviceError:
self._set(keyboard=False, battery=None)
return
if not self.state.keyboard:
self._init_keyboard()
else:
self._set(battery=self._battery(self._h.keyboard))
def _process_jobs(self) -> None:
latest = None
while True:
try:
job, arg = self._jobs.get_nowait()
except queue.Empty:
break
if job == "apply":
latest = arg
if latest is None:
return
self._profile = latest
if self.state.keyboard:
try:
self._h.keyboard.apply(latest, self._applied)
self._applied = latest
self._set(error="")
except DeviceError as e:
self._applied = None
self._set(error=f"Profil konnte nicht angewendet werden: {e}")
def _read_notifications(self, timeout: float) -> None:
notify = self._h.notify
if notify is None:
time.sleep(timeout)
return
data = notify.read(timeout)
while data:
self._handle_notification(data)
data = notify.read(0)
def _handle_notification(self, data: bytes) -> None:
if len(data) < 6:
return
if data[1] == 0x01 and data[2] == bragi.NOTIFY_CONNECTION:
if data[4] == 0x02:
self._reconnect_at = time.monotonic() + RECONNECT_DELAY
elif data[4] == 0x00:
self._set(keyboard=False, battery=None)
elif data[2] == bragi.PROP_BATTERY:
level = round(bragi.parse_u16(data, 4) / 10)
if level > 0:
self._set(battery=level)
def _close(self) -> None:
if self._h:
self._h.close()
self._h = None
def _shutdown(self) -> None:
if self._h and self._restore_hardware:
for dev in (self._h.keyboard, self._h.receiver):
if dev is None:
continue
try:
dev.set_mode(bragi.MODE_HARDWARE)
except (DeviceError, OSError) as e:
log.debug("hardware mode: %s", e)
self._close()
+62
View File
@@ -0,0 +1,62 @@
"""Catalog of the hardware lighting effects the K65 PLUS renders on its own."""
from __future__ import annotations
from dataclasses import dataclass
from . import bragi
@dataclass(frozen=True)
class Effect:
key: str
label: str
fx: int
max_colors: int = 0 # how many user colors the effect takes
random_colors: bool = False # supports "random colors" instead of user colors
speed: bool = True
direction: int = 0
fixed_color_mode: int | None = None
fixed_colors: tuple[bragi.Rgb, ...] = ()
SPEEDS = {"slow": bragi.SPEED_SLOW, "medium": bragi.SPEED_MEDIUM, "fast": bragi.SPEED_FAST}
SPEED_LABELS = {"slow": "Langsam", "medium": "Mittel", "fast": "Schnell"}
_WHITE = bragi.Rgb(255, 255, 255)
_BLACK = bragi.Rgb(0, 0, 0)
EFFECTS: dict[str, Effect] = {e.key: e for e in (
Effect("static", "Statische Farbe", bragi.FX_STATIC, max_colors=1, speed=False),
Effect("rainbow_wave", "Regenbogenwelle", bragi.FX_RAINBOW_WAVE, direction=0x04),
Effect("spiral_rainbow", "Spiralregenbogen", bragi.FX_SPIRAL_RAINBOW, direction=0x06),
Effect("color_wave", "Farbwelle", bragi.FX_COLOR_WAVE, max_colors=2, random_colors=True, direction=0x04),
Effect("color_shift", "Farbwechsel", bragi.FX_COLOR_SHIFT, max_colors=2, random_colors=True),
Effect("color_pulse", "Farbpuls", bragi.FX_COLOR_PULSE, max_colors=2, random_colors=True),
Effect("rain", "Regen", bragi.FX_RAIN, max_colors=2, random_colors=True, direction=0x01),
Effect("watercolor", "Aquarell", bragi.FX_WATERCOLOR,
fixed_color_mode=bragi.COLORS_ALT, fixed_colors=(_WHITE,)),
Effect("type_key", "Tippen: Taste", bragi.FX_TYPE_KEY, max_colors=2, random_colors=True),
Effect("type_ripple", "Tippen: Welle", bragi.FX_TYPE_RIPPLE, max_colors=2, random_colors=True),
Effect("visor", "Visier", bragi.FX_VISOR, max_colors=2, random_colors=True),
Effect("off", "Aus", bragi.FX_STATIC, speed=False,
fixed_color_mode=bragi.COLORS_SPECIFIC, fixed_colors=(_BLACK,)),
)}
def encode(target: int, effect_key: str, colors: list[str], random: bool, speed: str) -> list[bytes]:
effect = EFFECTS.get(effect_key, EFFECTS["static"])
if effect.fixed_color_mode is not None:
mode, rgb = effect.fixed_color_mode, list(effect.fixed_colors)
elif effect.max_colors and not (random and effect.random_colors):
mode = bragi.COLORS_SPECIFIC
rgb = [bragi.Rgb.from_hex(c) for c in colors[:effect.max_colors]] or [_WHITE]
elif effect.random_colors:
mode, rgb = bragi.COLORS_RANDOM, []
else:
mode, rgb = bragi.COLORS_NONE, []
return bragi.lighting_packets(
target, effect.fx, mode,
SPEEDS.get(speed, bragi.SPEED_MEDIUM) if effect.speed else 0,
effect.direction, rgb,
)
+90
View File
@@ -0,0 +1,90 @@
"""Minimal hidraw transport and device discovery (Linux only, no external deps)."""
from __future__ import annotations
import os
import re
import select
from dataclasses import dataclass
from pathlib import Path
REPORT_SIZE = 64
SYSFS_HIDRAW = Path("/sys/class/hidraw")
@dataclass(frozen=True)
class HidrawInfo:
path: str # /dev/hidrawN
vendor_id: int
product_id: int
interface: int # USB bInterfaceNumber, -1 if unknown (e.g. Bluetooth)
name: str
bus: int # 3 = USB, 5 = Bluetooth
def enumerate_hidraw(vendor_id: int | None = None) -> list[HidrawInfo]:
devices: list[HidrawInfo] = []
if not SYSFS_HIDRAW.exists():
return devices
for entry in sorted(SYSFS_HIDRAW.iterdir()):
try:
uevent = (entry / "device" / "uevent").read_text()
except OSError:
continue
fields = dict(line.split("=", 1) for line in uevent.splitlines() if "=" in line)
hid_id = fields.get("HID_ID", "")
m = re.fullmatch(r"([0-9A-Fa-f]+):([0-9A-Fa-f]+):([0-9A-Fa-f]+)", hid_id)
if not m:
continue
bus, vid, pid = (int(x, 16) for x in m.groups())
if vendor_id is not None and vid != vendor_id:
continue
# .../1-2:1.1/0003:1B1C:2B07.0002 -> interface 1
real = os.path.realpath(entry / "device")
im = re.search(r":\d+\.(\d+)/[^/]+$", real)
devices.append(HidrawInfo(
path=f"/dev/{entry.name}",
vendor_id=vid,
product_id=pid,
interface=int(im.group(1)) if im else -1,
name=fields.get("HID_NAME", ""),
bus=bus,
))
return devices
class Hidraw:
"""A raw HID device without numbered reports (report id byte 0 is stripped by the kernel)."""
def __init__(self, path: str):
self.path = path
self.fd = os.open(path, os.O_RDWR | os.O_NONBLOCK)
def close(self) -> None:
if self.fd >= 0:
os.close(self.fd)
self.fd = -1
def write(self, data: bytes) -> None:
if len(data) > REPORT_SIZE:
raise ValueError(f"report too long: {len(data)} > {REPORT_SIZE}")
os.write(self.fd, b"\x00" + data.ljust(REPORT_SIZE, b"\x00"))
def read(self, timeout: float) -> bytes | None:
ready, _, _ = select.select([self.fd], [], [], timeout)
if not ready:
return None
try:
return os.read(self.fd, REPORT_SIZE)
except BlockingIOError:
return None
def drain(self) -> None:
while self.read(0) is not None:
pass
def __enter__(self) -> "Hidraw":
return self
def __exit__(self, *exc) -> None:
self.close()
+55
View File
@@ -0,0 +1,55 @@
"""Key geometry of the K65 PLUS (75 %, ISO-DE) in key units."""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class Key:
label: str
x: float
y: float
w: float = 1.0
h: float = 1.0
iso_enter: bool = False
@property
def cx(self) -> float:
return self.x + self.w / 2
@property
def cy(self) -> float:
return self.y + self.h / 2
def _row(y: float, x: float, keys: list[tuple[str, float] | str]) -> list[Key]:
out = []
for k in keys:
label, w = (k, 1.0) if isinstance(k, str) else k
out.append(Key(label, x, y, w))
x += w
return out
def _build() -> list[Key]:
keys = [Key("Esc", 0, 0)]
for group, start in ((("F1", "F2", "F3", "F4"), 1.25), (("F5", "F6", "F7", "F8"), 5.5),
(("F9", "F10", "F11", "F12"), 9.75)):
keys += _row(0, start, list(group))
keys.append(Key("Entf", 15, 0))
keys += _row(1.25, 0, ["^", *"1234567890", "ß", "´", ("⌫", 2.0), "Pos1"])
keys += _row(2.25, 0, [("Tab", 1.5), *"QWERTZUIOP", "Ü", "+"])
keys.append(Key("↵", 13.5, 2.25, 1.5, 2.0, iso_enter=True))
keys.append(Key("Bild↑", 15, 2.25))
keys += _row(3.25, 0, [("Caps", 1.75), *"ASDFGHJKL", "Ö", "Ä", "#"])
keys.append(Key("Bild↓", 15, 3.25))
keys += _row(4.25, 0, [("⇧", 1.25), "<", *"YXCVBNM", ",", ".", "-", ("⇧", 1.75), "↑"])
keys += _row(5.25, 0, [("Strg", 1.25), ("Win", 1.25), ("Alt", 1.25), ("", 6.25),
"AltGr", "Fn", "Strg", "←", "↓", "→"])
return keys
KEYS: list[Key] = _build()
WIDTH = 16.0
HEIGHT = 6.25
+65
View File
@@ -0,0 +1,65 @@
"""Profiles and app settings, stored as JSON in ~/.config/k65studio/config.json."""
from __future__ import annotations
import json
import os
from dataclasses import asdict, dataclass, field
from pathlib import Path
CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "k65studio"
CONFIG_FILE = CONFIG_DIR / "config.json"
@dataclass
class Profile:
effect: str = "static"
colors: list[str] = field(default_factory=lambda: ["#00e5ff", "#ff2d95"])
random_colors: bool = False
speed: str = "medium"
brightness: int = 100 # percent
sleep_minutes: int = 15
game_mode: bool = False
lock_win: bool = True
lock_alt_tab: bool = False
lock_alt_f4: bool = False
lock_shift_tab: bool = False
@classmethod
def from_dict(cls, data: dict) -> "Profile":
known = {k: v for k, v in data.items() if k in cls.__dataclass_fields__}
return cls(**known)
@dataclass
class Config:
active: str = "Standard"
profiles: dict[str, Profile] = field(default_factory=lambda: {"Standard": Profile()})
start_minimized: bool = False
restore_hardware_on_exit: bool = True
@property
def profile(self) -> Profile:
if self.active not in self.profiles:
self.active = next(iter(self.profiles))
return self.profiles[self.active]
@classmethod
def load(cls) -> "Config":
try:
data = json.loads(CONFIG_FILE.read_text())
except (OSError, ValueError):
return cls()
profiles = {name: Profile.from_dict(p) for name, p in data.get("profiles", {}).items()}
return cls(
active=data.get("active", "Standard"),
profiles=profiles or {"Standard": Profile()},
start_minimized=data.get("start_minimized", False),
restore_hardware_on_exit=data.get("restore_hardware_on_exit", True),
)
def save(self) -> None:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
tmp = CONFIG_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(asdict(self), indent=2, ensure_ascii=False))
tmp.replace(CONFIG_FILE)
View File
Whitespace-only changes.
+450
View File
@@ -0,0 +1,450 @@
"""Main window: device view on top, settings pages below (iCUE-style)."""
from __future__ import annotations
from dataclasses import replace
from PySide6.QtCore import Qt, QTimer, Signal
from PySide6.QtGui import QColor
from PySide6.QtWidgets import (
QButtonGroup, QCheckBox, QColorDialog, QComboBox, QFrame, QGridLayout, QHBoxLayout,
QInputDialog, QLabel, QListWidget, QListWidgetItem, QMainWindow, QMessageBox,
QProgressBar, QPushButton, QSlider, QSpinBox, QStackedWidget, QVBoxLayout, QWidget,
)
from .. import autostart
from ..device import DeviceState
from ..effects import EFFECTS, SPEED_LABELS
from ..profiles import Config, Profile
from .preview import KeyboardPreview
PRESETS = ["#ff0000", "#ff7a00", "#ffd400", "#3bff3b", "#19d3c5", "#0077ff", "#7a2cff", "#ff2d95", "#ffffff"]
def _card() -> tuple[QFrame, QVBoxLayout]:
frame = QFrame(objectName="card")
lay = QVBoxLayout(frame)
lay.setContentsMargins(18, 16, 18, 16)
lay.setSpacing(10)
return frame, lay
def _label(text: str, name: str = "") -> QLabel:
lbl = QLabel(text)
if name:
lbl.setObjectName(name)
lbl.setWordWrap(True)
return lbl
class MainWindow(QMainWindow):
profile_changed = Signal(object) # Profile to send to the keyboard
reinit_requested = Signal()
def __init__(self, config: Config):
super().__init__()
self.config = config
self.state = DeviceState()
self._loading = False
self._save_timer = QTimer(self, singleShot=True, interval=600, timeout=self.config.save)
self.setWindowTitle("K65 Studio")
self.resize(1240, 900)
root = QWidget()
outer = QVBoxLayout(root)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
outer.addWidget(self._build_header())
body = QHBoxLayout()
body.setContentsMargins(16, 16, 16, 16)
body.setSpacing(16)
self.nav = QListWidget(objectName="nav")
self.nav.setFixedWidth(200)
for name in ("Beleuchtung", "Leistung", "Einstellungen", "Geräteinfo"):
self.nav.addItem(name)
body.addWidget(self.nav)
right = QVBoxLayout()
right.setSpacing(16)
preview_card, preview_lay = _card()
self.preview = KeyboardPreview()
preview_lay.addWidget(self.preview, 1)
preview_lay.addWidget(_label("Vorschau (simuliert). Die Tastatur berechnet den Effekt selbst.", "hint"))
right.addWidget(preview_card, 4)
self.pages = QStackedWidget()
self.pages.addWidget(self._build_lighting())
self.pages.addWidget(self._build_performance())
self.pages.addWidget(self._build_settings())
self.pages.addWidget(self._build_info())
right.addWidget(self.pages, 5)
body.addLayout(right, 1)
outer.addLayout(body, 1)
self.setCentralWidget(root)
self.nav.currentRowChanged.connect(self.pages.setCurrentIndex)
self.nav.setCurrentRow(0)
self._reload_profiles()
self.set_state(self.state)
# ---------- header ----------
def _build_header(self) -> QFrame:
header = QFrame(objectName="header")
lay = QHBoxLayout(header)
lay.setContentsMargins(20, 12, 20, 12)
lay.setSpacing(10)
lay.addWidget(_label("K65 STUDIO", "title"))
lay.addSpacing(24)
lay.addWidget(_label("Profil", "muted"))
self.profile_box = QComboBox()
self.profile_box.setMinimumWidth(180)
self.profile_box.currentTextChanged.connect(self._select_profile)
lay.addWidget(self.profile_box)
for text, slot in (("Neu", self._new_profile), ("Umbenennen", self._rename_profile),
("Löschen", self._delete_profile)):
b = QPushButton(text)
b.clicked.connect(slot)
lay.addWidget(b)
lay.addStretch(1)
self.conn_chip = QLabel(objectName="chip")
self.battery_chip = QLabel(objectName="chip")
lay.addWidget(self.conn_chip)
lay.addWidget(self.battery_chip)
return header
# ---------- pages ----------
def _build_lighting(self) -> QWidget:
page = QWidget()
lay = QHBoxLayout(page)
lay.setContentsMargins(0, 0, 0, 0)
lay.setSpacing(16)
fx_card, fx_lay = _card()
fx_lay.addWidget(_label("Effekt", "section"))
self.effect_list = QListWidget()
for key, effect in EFFECTS.items():
item = QListWidgetItem(effect.label)
item.setData(Qt.UserRole, key)
self.effect_list.addItem(item)
self.effect_list.currentItemChanged.connect(self._effect_selected)
fx_lay.addWidget(self.effect_list)
fx_card.setFixedWidth(260)
lay.addWidget(fx_card)
opt_card, opt = _card()
opt.addWidget(_label("Farben", "section"))
colors = QHBoxLayout()
self.color_buttons = []
for i in range(2):
b = QPushButton(objectName="color")
b.clicked.connect(lambda _=False, i=i: self._pick_color(i))
colors.addWidget(b)
self.color_buttons.append(b)
self.random_box = QCheckBox("Zufällige Farben")
self.random_box.toggled.connect(lambda v: self._update(random_colors=v))
colors.addSpacing(12)
colors.addWidget(self.random_box)
colors.addStretch(1)
opt.addLayout(colors)
swatches = QHBoxLayout()
swatches.setSpacing(6)
swatches.addWidget(_label("Schnellwahl:", "muted"))
for c in PRESETS:
s = QPushButton(objectName="swatch")
s.setStyleSheet(f"background: {c}; border: 2px solid #2c313a;")
s.setToolTip(c)
s.clicked.connect(lambda _=False, c=c: self._set_color(0, c))
swatches.addWidget(s)
swatches.addStretch(1)
opt.addLayout(swatches)
self.colors_hint = _label("", "hint")
opt.addWidget(self.colors_hint)
opt.addWidget(_label("Geschwindigkeit", "section"))
speeds = QHBoxLayout()
self.speed_group = QButtonGroup(self)
for key, text in SPEED_LABELS.items():
b = QPushButton(text, checkable=True)
b.setProperty("speed", key)
self.speed_group.addButton(b)
speeds.addWidget(b)
speeds.addStretch(1)
self.speed_group.buttonClicked.connect(lambda b: self._update(speed=b.property("speed")))
opt.addLayout(speeds)
opt.addWidget(_label("Helligkeit", "section"))
bright = QHBoxLayout()
self.brightness = QSlider(Qt.Horizontal, minimum=0, maximum=100, singleStep=5, pageStep=10)
self.brightness_value = _label("", "muted")
self.brightness_value.setFixedWidth(48)
self.brightness.valueChanged.connect(self._brightness_changed)
bright.addWidget(self.brightness, 1)
bright.addWidget(self.brightness_value)
opt.addLayout(bright)
opt.addStretch(1)
lay.addWidget(opt_card, 1)
return page
def _build_performance(self) -> QWidget:
card, lay = _card()
lay.addWidget(_label("Spielmodus", "section"))
lay.addWidget(_label("Wenn der Spielmodus aktiv ist, sperrt die Tastatur die ausgewählten "
"Tasten und Kombinationen, damit sie im Spiel nicht versehentlich auslösen.", "muted"))
self.game_mode = QCheckBox("Spielmodus aktivieren")
self.game_mode.toggled.connect(self._game_mode_changed)
lay.addWidget(self.game_mode)
self.locks = {
"lock_win": QCheckBox("Windows-/Super-Taste sperren"),
"lock_alt_tab": QCheckBox("Alt + Tab sperren"),
"lock_alt_f4": QCheckBox("Alt + F4 sperren"),
"lock_shift_tab": QCheckBox("Shift + Tab sperren"),
}
for name, box in self.locks.items():
box.toggled.connect(lambda v, name=name: self._update(**{name: v}))
box.setContentsMargins(24, 0, 0, 0)
lay.addWidget(box)
lay.addStretch(1)
return card
def _build_settings(self) -> QWidget:
card, lay = _card()
lay.addWidget(_label("Energie", "section"))
row = QHBoxLayout()
row.addWidget(QLabel("Ruhezustand nach"))
self.sleep = QSpinBox(minimum=1, maximum=120, suffix=" min")
self.sleep.valueChanged.connect(lambda v: self._update(sleep_minutes=v))
row.addWidget(self.sleep)
row.addWidget(QLabel("ohne Eingabe (gilt im Funkbetrieb)", objectName="muted"))
row.addStretch(1)
lay.addLayout(row)
lay.addWidget(_label("Programm", "section"))
self.autostart = QCheckBox("Beim Anmelden automatisch starten (im Tray)")
self.autostart.setChecked(autostart.is_enabled())
self.autostart.toggled.connect(autostart.set_enabled)
lay.addWidget(self.autostart)
self.start_min = QCheckBox("Minimiert starten")
self.start_min.setChecked(self.config.start_minimized)
self.start_min.toggled.connect(lambda v: self._set_config(start_minimized=v))
lay.addWidget(self.start_min)
self.restore_hw = QCheckBox("Beim Beenden an die Tastatur zurückgeben (Hardware-Beleuchtung)")
self.restore_hw.setChecked(self.config.restore_hardware_on_exit)
self.restore_hw.toggled.connect(lambda v: self._set_config(restore_hardware_on_exit=v))
lay.addWidget(self.restore_hw)
reinit = QPushButton("Tastatur neu initialisieren")
reinit.clicked.connect(self.reinit_requested)
row = QHBoxLayout()
row.addWidget(reinit)
row.addStretch(1)
lay.addSpacing(8)
lay.addLayout(row)
lay.addStretch(1)
return card
def _build_info(self) -> QWidget:
card, lay = _card()
lay.addWidget(_label("CORSAIR K65 PLUS WIRELESS", "section"))
grid = QGridLayout()
grid.setHorizontalSpacing(24)
grid.setVerticalSpacing(8)
self.info = {}
for i, (key, text) in enumerate((("conn", "Verbindung"), ("serial", "Seriennummer"),
("kb_fw", "Firmware Tastatur"), ("rx_fw", "Firmware Empfänger"),
("battery", "Akku"))):
grid.addWidget(_label(text, "muted"), i, 0)
value = QLabel("–")
value.setTextInteractionFlags(Qt.TextSelectableByMouse)
grid.addWidget(value, i, 1)
self.info[key] = value
self.battery_bar = QProgressBar(maximum=100, textVisible=False)
self.battery_bar.setFixedWidth(220)
grid.addWidget(self.battery_bar, 5, 1)
grid.setColumnStretch(2, 1)
lay.addLayout(grid)
self.error_label = _label("", "hint")
lay.addWidget(self.error_label)
lay.addStretch(1)
return card
# ---------- profile handling ----------
@property
def profile(self) -> Profile:
return self.config.profile
def _reload_profiles(self) -> None:
self._loading = True
self.profile_box.clear()
self.profile_box.addItems(list(self.config.profiles))
self.profile_box.setCurrentText(self.config.active)
self._loading = False
self._load_profile_into_ui()
def _load_profile_into_ui(self) -> None:
p = self.profile
self._loading = True
for i in range(self.effect_list.count()):
if self.effect_list.item(i).data(Qt.UserRole) == p.effect:
self.effect_list.setCurrentRow(i)
self.random_box.setChecked(p.random_colors)
for b in self.speed_group.buttons():
b.setChecked(b.property("speed") == p.speed)
self.brightness.setValue(p.brightness)
self.brightness_value.setText(f"{p.brightness} %")
self.game_mode.setChecked(p.game_mode)
for name, box in self.locks.items():
box.setChecked(getattr(p, name))
self.sleep.setValue(p.sleep_minutes)
self._loading = False
self._refresh_controls()
self.preview.set_profile(p)
def _refresh_controls(self) -> None:
p = self.profile
effect = EFFECTS.get(p.effect, EFFECTS["static"])
for i, b in enumerate(self.color_buttons):
c = p.colors[i] if i < len(p.colors) else "#ffffff"
fg = "#000" if QColor(c).lightness() > 140 else "#fff"
b.setStyleSheet(f"background: {c}; color: {fg}; border: 1px solid #3a404a;")
b.setText(c.upper())
b.setVisible(i < effect.max_colors)
b.setEnabled(not (p.random_colors and effect.random_colors))
self.random_box.setVisible(effect.random_colors)
if effect.max_colors == 0:
hints = {"off": "Beleuchtung ist ausgeschaltet.",
"watercolor": "Dieser Effekt verwendet feste Farben."}
self.colors_hint.setText(hints.get(p.effect, "Dieser Effekt verwendet den Regenbogen."))
elif effect.max_colors == 2:
self.colors_hint.setText("Zwei Farben, zwischen denen der Effekt wechselt.")
else:
self.colors_hint.setText("")
for b in self.speed_group.buttons():
b.setEnabled(effect.speed)
for box in self.locks.values():
box.setEnabled(p.game_mode)
def _update(self, **changes) -> None:
if self._loading:
return
self.config.profiles[self.config.active] = replace(self.profile, **changes)
self._refresh_controls()
self.preview.set_profile(self.profile)
self.profile_changed.emit(self.profile)
self._save_timer.start()
def _set_config(self, **changes) -> None:
for k, v in changes.items():
setattr(self.config, k, v)
self._save_timer.start()
def _select_profile(self, name: str) -> None:
if self._loading or not name or name == self.config.active:
return
self.activate_profile(name)
def activate_profile(self, name: str) -> None:
if name not in self.config.profiles:
return
self.config.active = name
self.config.save()
self._reload_profiles()
self.profile_changed.emit(self.profile)
def _ask_name(self, title: str, default: str) -> str | None:
name, ok = QInputDialog.getText(self, title, "Name:", text=default)
name = name.strip()
if not ok or not name:
return None
if name in self.config.profiles:
QMessageBox.warning(self, title, f"Ein Profil „{name}“ gibt es schon.")
return None
return name
def _new_profile(self) -> None:
name = self._ask_name("Neues Profil", f"Profil {len(self.config.profiles) + 1}")
if name:
self.config.profiles[name] = replace(self.profile, colors=list(self.profile.colors))
self.activate_profile(name)
def _rename_profile(self) -> None:
old = self.config.active
name = self._ask_name("Profil umbenennen", old)
if name:
self.config.profiles = {(name if k == old else k): v for k, v in self.config.profiles.items()}
self.config.active = name
self.config.save()
self._reload_profiles()
def _delete_profile(self) -> None:
if len(self.config.profiles) <= 1:
QMessageBox.information(self, "Profil löschen", "Das letzte Profil kann nicht gelöscht werden.")
return
name = self.config.active
if QMessageBox.question(self, "Profil löschen", f"Profil „{name}“ löschen?") != QMessageBox.Yes:
return
del self.config.profiles[name]
self.activate_profile(next(iter(self.config.profiles)))
# ---------- control callbacks ----------
def _effect_selected(self, item: QListWidgetItem | None, _prev=None) -> None:
if item is not None:
self._update(effect=item.data(Qt.UserRole))
def _set_color(self, index: int, color: str) -> None:
colors = list(self.profile.colors) + ["#ffffff"] * (2 - len(self.profile.colors))
colors[index] = color
self._update(colors=colors, random_colors=False)
self.random_box.blockSignals(True)
self.random_box.setChecked(False)
self.random_box.blockSignals(False)
def _pick_color(self, index: int) -> None:
current = QColor(self.profile.colors[index] if index < len(self.profile.colors) else "#ffffff")
color = QColorDialog.getColor(current, self, "Farbe wählen")
if color.isValid():
self._set_color(index, color.name())
def _brightness_changed(self, value: int) -> None:
self.brightness_value.setText(f"{value} %")
self._update(brightness=value)
def _game_mode_changed(self, value: bool) -> None:
self._update(game_mode=value)
# ---------- device state ----------
def set_state(self, s: DeviceState) -> None:
self.state = s
self.preview.set_connected(s.keyboard)
if s.keyboard:
mode = "Funk (Slipstream)" if s.wireless else "USB-Kabel"
self.conn_chip.setText(f"● Verbunden · {mode}")
self.conn_chip.setStyleSheet("color: #3ddc84;")
elif s.receiver:
self.conn_chip.setText("● Empfänger bereit · Tastatur schläft/aus")
self.conn_chip.setStyleSheet("color: #f5b942;")
else:
self.conn_chip.setText("● Nicht verbunden")
self.conn_chip.setStyleSheet("color: #ef5350;")
if s.battery is not None:
self.battery_chip.setText(f"Akku {s.battery} %")
self.battery_chip.setStyleSheet("color: #ef5350;" if s.battery <= 15 else "")
self.battery_chip.show()
else:
self.battery_chip.hide()
self.info["conn"].setText(self.conn_chip.text().lstrip("● ").strip())
self.info["serial"].setText(s.serial or "–")
self.info["kb_fw"].setText(s.keyboard_firmware or "–")
self.info["rx_fw"].setText(s.receiver_firmware or ("–" if s.wireless else "nicht vorhanden (Kabel)"))
self.info["battery"].setText(f"{s.battery} %" if s.battery is not None else "–")
self.battery_bar.setValue(s.battery or 0)
self.error_label.setText(s.error)
self.error_label.setStyleSheet("color: #ef5350;" if s.error else "")
+217
View File
@@ -0,0 +1,217 @@
"""Animated keyboard preview that approximates the hardware effects."""
from __future__ import annotations
import colorsys
import math
import random
import time
from PySide6.QtCore import QRectF, Qt, QTimer
from PySide6.QtGui import QColor, QFont, QPainter, QPainterPath, QPen
from PySide6.QtWidgets import QWidget
from .. import layout
from ..profiles import Profile
SPEED_FACTOR = {"slow": 0.5, "medium": 1.0, "fast": 1.8}
RGB = tuple[float, float, float]
def _hex(c: str) -> RGB:
q = QColor(c)
return q.redF(), q.greenF(), q.blueF()
def _hue(h: float) -> RGB:
return colorsys.hsv_to_rgb(h % 1.0, 1.0, 1.0)
def _mix(a: RGB, b: RGB, t: float) -> RGB:
return tuple(x + (y - x) * t for x, y in zip(a, b))
def _scale(a: RGB, f: float) -> RGB:
return tuple(x * f for x in a)
class KeyboardPreview(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setMinimumHeight(220)
self.profile = Profile()
self.connected = True
self._t0 = time.monotonic()
self._presses: list[tuple[float, layout.Key, RGB]] = []
self._next_press = 0.0
self._rand = random.Random(7)
self._palette_seed = [self._rand.random() for _ in range(64)]
self._timer = QTimer(self, interval=33, timeout=self.update)
self._timer.start()
def set_profile(self, profile: Profile) -> None:
self.profile = profile
self.update()
def set_connected(self, connected: bool) -> None:
self.connected = connected
self.update()
def showEvent(self, e):
self._timer.start()
super().showEvent(e)
def hideEvent(self, e):
self._timer.stop()
super().hideEvent(e)
# --- effect simulation ---
def _colors(self) -> tuple[RGB, RGB]:
cs = self.profile.colors + ["#ffffff", "#ffffff"]
return _hex(cs[0]), _hex(cs[1])
def _random(self, n: int) -> RGB:
return _hue(self._palette_seed[n % len(self._palette_seed)])
def _key_color(self, k: layout.Key, t: float) -> RGB:
p = self.profile
s = SPEED_FACTOR.get(p.speed, 1.0)
c0, c1 = self._colors()
rnd = p.random_colors
x, y = k.cx / layout.WIDTH, k.cy / layout.HEIGHT
match p.effect:
case "off":
return (0, 0, 0)
case "static":
return c0
case "rainbow_wave":
return _hue(x - t * 0.25 * s)
case "spiral_rainbow":
a = math.atan2(y - 0.5, (x - 0.5) * 2.5) / (2 * math.pi)
return _hue(a + t * 0.2 * s)
case "color_wave":
phase = x - t * 0.3 * s
n = math.floor(phase)
band = 0.5 + 0.5 * math.cos((phase - n) * 2 * math.pi)
col = self._random(-n) if rnd else (c0 if n % 2 == 0 else c1)
return _scale(col, band ** 2)
case "color_shift":
phase = t * 0.25 * s
n = math.floor(phase)
a = self._random(n) if rnd else (c0 if n % 2 == 0 else c1)
b = self._random(n + 1) if rnd else (c1 if n % 2 == 0 else c0)
return _mix(a, b, 0.5 - 0.5 * math.cos((phase - n) * math.pi))
case "color_pulse":
phase = t * 0.5 * s
n = math.floor(phase)
col = self._random(n) if rnd else (c0 if n % 2 == 0 else c1)
return _scale(col, math.sin((phase - n) * math.pi) ** 2)
case "rain":
col_i = int(k.cx * 2)
seed = self._palette_seed[col_i % 64]
head = ((t * 0.5 * s + seed * 3) % 1.6) * layout.HEIGHT - 1
d = head - k.cy
lvl = max(0.0, 1 - d / 2.0) if d >= 0 else 0.0
col = self._random(col_i) if rnd else (c0 if col_i % 2 else c1)
return _scale(col, lvl)
case "watercolor":
h = 0.5 + 0.25 * math.sin(x * 4 + t * 0.6 * s) + 0.25 * math.sin(y * 5 - t * 0.4 * s)
return colorsys.hsv_to_rgb(h % 1.0, 0.55, 1.0)
case "type_key" | "type_ripple":
return self._typing(k, t, c0, c1)
case "visor":
pos = (math.sin(t * 1.2 * s) * 0.5 + 0.5) * layout.WIDTH
lvl = max(0.0, 1 - abs(k.cx - pos) / 2.5)
col = self._random(int(t * 1.2 * s / math.pi)) if rnd else c0
return _scale(col, lvl)
return c0
def _typing(self, k: layout.Key, t: float, c0: RGB, c1: RGB) -> RGB:
level = 0.0
best: RGB = (0, 0, 0)
for start, key, col in self._presses:
age = t - start
if self.profile.effect == "type_key":
if key is k:
lvl = max(0.0, 1 - age / 1.2)
else:
continue
else:
d = math.hypot(k.cx - key.cx, k.cy - key.cy)
front = age * 9 * SPEED_FACTOR.get(self.profile.speed, 1.0)
lvl = max(0.0, 1 - abs(d - front) / 1.2) * max(0.0, 1 - age / 1.6)
if lvl > level:
level, best = lvl, col
return _scale(best, level)
def _update_presses(self, t: float) -> None:
if self.profile.effect not in ("type_key", "type_ripple"):
self._presses.clear()
return
if t >= self._next_press:
key = self._rand.choice(layout.KEYS)
c0, c1 = self._colors()
col = _hue(self._rand.random()) if self.profile.random_colors else c0
self._presses.append((t, key, col))
self._next_press = t + self._rand.uniform(0.15, 0.6)
self._presses = [p for p in self._presses if t - p[0] < 2.0]
# --- painting ---
def paintEvent(self, _):
t = time.monotonic() - self._t0
self._update_presses(t)
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
margin = 18
unit = min((self.width() - 2 * margin) / (layout.WIDTH + 0.5),
(self.height() - 2 * margin) / (layout.HEIGHT + 0.5))
bw, bh = unit * (layout.WIDTH + 0.5), unit * (layout.HEIGHT + 0.5)
ox, oy = (self.width() - bw) / 2, (self.height() - bh) / 2
body = QRectF(ox, oy, bw, bh)
p.setPen(QPen(QColor("#2c2f36"), 1.5))
p.setBrush(QColor("#15171b"))
p.drawRoundedRect(body, unit * 0.35, unit * 0.35)
bright = self.profile.brightness / 100 if self.connected else 0.0
font = QFont(self.font())
font.setPixelSize(max(7, int(unit * 0.24)))
p.setFont(font)
pad = unit * 0.07
kx, ky = ox + unit * 0.25, oy + unit * 0.25
for k in layout.KEYS:
r, g, b = _scale(self._key_color(k, t), bright)
glow = QColor.fromRgbF(min(r, 1), min(g, 1), min(b, 1))
rect = QRectF(kx + k.x * unit + pad, ky + k.y * unit + pad, k.w * unit - 2 * pad, k.h * unit - 2 * pad)
if k.iso_enter:
top, stem = QPainterPath(), QPainterPath()
top.addRoundedRect(QRectF(rect.x(), rect.y(), rect.width(), unit - 2 * pad), 4, 4)
stem.addRoundedRect(QRectF(rect.x() + unit * 0.25, rect.y(), rect.width() - unit * 0.25,
rect.height()), 4, 4)
path = top.united(stem)
else:
path = QPainterPath()
path.addRoundedRect(rect, 4, 4)
# Keycap: dark top, the light leaks around the edge like on the real board.
p.setPen(QPen(glow, max(1.5, unit * 0.05)))
cap = QColor.fromRgbF(0.09 + r * 0.22, 0.10 + g * 0.22, 0.11 + b * 0.22)
p.setBrush(cap)
p.drawPath(path)
if k.label:
p.setPen(QColor.fromRgbF(0.35 + min(r, 1) * 0.65, 0.35 + min(g, 1) * 0.65,
0.35 + min(b, 1) * 0.65))
label_rect = QRectF(rect.x(), rect.y(), rect.width(), unit - 2 * pad)
p.drawText(label_rect, Qt.AlignCenter, k.label)
if not self.connected:
p.setPen(QColor("#9aa0aa"))
f = QFont(self.font())
f.setPixelSize(15)
p.setFont(f)
p.drawText(body, Qt.AlignCenter, "Tastatur nicht verbunden")
p.end()
+56
View File
@@ -0,0 +1,56 @@
ACCENT = "#19d3c5"
STYLESHEET = f"""
QWidget {{
background: #101216;
color: #e6e8eb;
font-size: 13px;
}}
QLabel, QCheckBox {{ background: transparent; }}
QLabel#title {{ font-size: 18px; font-weight: 600; letter-spacing: 1px; }}
QLabel#section {{ font-size: 15px; font-weight: 600; margin-top: 4px; }}
QLabel#muted, QLabel#hint {{ color: #8b919c; }}
QLabel#chip {{
background: #1b1e24; border: 1px solid #2a2e36; border-radius: 11px;
padding: 3px 10px;
}}
QFrame#header {{ background: #0b0d10; border-bottom: 1px solid #22262d; }}
QFrame#card {{ background: #161920; border: 1px solid #23272f; border-radius: 10px; }}
QListWidget {{
background: transparent; border: none; outline: none;
}}
QListWidget::item {{
padding: 9px 12px; border-radius: 6px; margin: 1px 0;
}}
QListWidget::item:hover {{ background: #1b1f26; }}
QListWidget::item:selected {{ background: #1f2a2e; color: {ACCENT}; }}
QListWidget#nav::item {{ padding: 12px 14px; font-size: 14px; }}
QPushButton {{
background: #1d2128; border: 1px solid #2c313a; border-radius: 6px; padding: 7px 14px;
}}
QPushButton:hover {{ border-color: {ACCENT}; }}
QPushButton:checked {{ background: #17393a; border-color: {ACCENT}; color: {ACCENT}; }}
QPushButton:disabled {{ color: #5a606a; border-color: #23272e; }}
QPushButton#swatch {{ border-radius: 14px; padding: 0; min-width: 28px; min-height: 28px; max-width: 28px; max-height: 28px; }}
QPushButton#color {{ min-width: 110px; min-height: 34px; font-weight: 600; }}
QComboBox, QSpinBox {{
background: #1d2128; border: 1px solid #2c313a; border-radius: 6px; padding: 5px 10px; min-height: 22px;
}}
QComboBox:hover, QSpinBox:hover {{ border-color: {ACCENT}; }}
QComboBox QAbstractItemView {{ background: #1d2128; selection-background-color: #1f2a2e; }}
QCheckBox {{ spacing: 10px; padding: 4px 0; }}
QCheckBox::indicator {{ width: 18px; height: 18px; border-radius: 4px; border: 1px solid #3a404a; background: #1d2128; }}
QCheckBox::indicator:checked {{ background: {ACCENT}; border-color: {ACCENT}; }}
QCheckBox:disabled {{ color: #5a606a; }}
QSlider::groove:horizontal {{ height: 6px; background: #262a32; border-radius: 3px; }}
QSlider::sub-page:horizontal {{ background: {ACCENT}; border-radius: 3px; }}
QSlider::handle:horizontal {{ width: 16px; margin: -6px 0; border-radius: 8px; background: #e6e8eb; }}
QProgressBar {{ background: #262a32; border: none; border-radius: 4px; height: 8px; text-align: center; }}
QProgressBar::chunk {{ background: {ACCENT}; border-radius: 4px; }}
QScrollArea {{ border: none; }}
QScrollBar:vertical {{ background: transparent; width: 8px; margin: 2px; }}
QScrollBar::handle:vertical {{ background: #2c313a; border-radius: 3px; min-height: 30px; }}
QScrollBar::handle:vertical:hover {{ background: #3a404a; }}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{ height: 0; }}
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {{ background: transparent; }}
"""
+2
View File
@@ -0,0 +1,2 @@
# K65 Studio: give the logged-in user access to the Corsair K65 PLUS (receiver and wired keyboard)
SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1b1c", ATTRS{idProduct}=="2b07|2b10|2b11|2b23", TAG+="uaccess"
+11
View File
@@ -0,0 +1,11 @@
[Desktop Entry]
Type=Application
Name=K65 Studio
GenericName=Tastatur-Beleuchtung
Comment=Corsair K65 PLUS Wireless Beleuchtung und Einstellungen
Exec=k65studio
Icon=k65studio
Terminal=false
Categories=Settings;HardwareSettings;Utility;
Keywords=corsair;keyboard;rgb;tastatur;beleuchtung;
StartupWMClass=k65studio
+59
View File
@@ -0,0 +1,59 @@
import unittest
from k65studio import bragi, effects
from k65studio.layout import KEYS, WIDTH
from k65studio.profiles import Config, Profile
class PacketTests(unittest.TestCase):
def test_static_color_matches_known_good_capture(self):
pkts = effects.encode(bragi.TARGET_PAIRED, "static", ["#ff0080"], False, "medium")
self.assertEqual(len(pkts), 2)
self.assertEqual(pkts[0][:15].hex(" "), "09 06 01 5d 00 00 00 7e 20 01 00 00 00 01 ff")
self.assertEqual(pkts[0][15:18], bytes([0x80, 0x00, 0xFF])) # B, G, R
self.assertEqual(pkts[1][:3], bytes([0x09, 0x07, 0x01]))
def test_rainbow_wave_header(self):
pkt = effects.encode(bragi.TARGET_PAIRED, "rainbow_wave", [], False, "fast")[0]
self.assertEqual(pkt[3:12].hex(" "), "59 00 00 00 4c b9 00 05 04")
def test_random_colors_have_no_color_list(self):
pkt = effects.encode(bragi.TARGET_PAIRED, "color_shift", ["#ffffff"], True, "slow")[0]
self.assertEqual(pkt[7:13].hex(" "), "fa a5 02 03 00 00")
self.assertEqual(pkt[13], 0)
def test_two_specific_colors(self):
pkt = effects.encode(bragi.TARGET_PAIRED, "color_pulse", ["#010203", "#040506"], False, "medium")[0]
self.assertEqual(pkt[9], bragi.COLORS_SPECIFIC)
self.assertEqual(pkt[13], 2)
self.assertEqual(pkt[14:22], bytes([0xFF, 3, 2, 1, 0xFF, 6, 5, 4]))
def test_packets_fit_report(self):
for key in effects.EFFECTS:
for p in effects.encode(bragi.TARGET_PAIRED, key, ["#123456", "#654321"], False, "medium"):
self.assertLessEqual(len(p), 64)
def test_keymap_block(self):
pkts = bragi.block_packets(bragi.TARGET_PAIRED, bragi.default_keymap())
self.assertEqual(len(pkts), 3)
self.assertEqual(pkts[0][3:5], bytes([123, 0]))
class LayoutTests(unittest.TestCase):
def test_rows_fit_board(self):
for k in KEYS:
self.assertLessEqual(k.x + k.w, WIDTH + 1e-9, k)
class ProfileTests(unittest.TestCase):
def test_unknown_fields_are_ignored(self):
p = Profile.from_dict({"effect": "rain", "bogus": 1})
self.assertEqual(p.effect, "rain")
def test_active_falls_back_to_existing_profile(self):
c = Config(active="weg", profiles={"A": Profile()})
self.assertIs(c.profile, c.profiles["A"])
if __name__ == "__main__":
unittest.main()
Executable
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
PREFIX="${PREFIX:-$HOME/.local}"
rm -rf "$PREFIX/share/k65studio" "$PREFIX/bin/k65studio" \
"$PREFIX/share/applications/k65studio.desktop" \
"$PREFIX/share/icons/hicolor/scalable/apps/k65studio.svg" \
"${XDG_CONFIG_HOME:-$HOME/.config}/autostart/k65studio.desktop"
if [ -f /etc/udev/rules.d/60-k65studio.rules ]; then
sudo rm /etc/udev/rules.d/60-k65studio.rules && sudo udevadm control --reload-rules
fi
echo "Entfernt. Profile bleiben in ${XDG_CONFIG_HOME:-$HOME/.config}/k65studio erhalten."