Initial commit

This commit is contained in:
Seth Hillbrand
2026-02-15 12:50:49 -08:00
commit c17ab8607c
61 changed files with 11607 additions and 0 deletions
+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>.
+19
View File
@@ -0,0 +1,19 @@
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "yolocam-gui"
version = "0.1.0"
description = "PySide6 GUI for controlling YoloCam S3 camera"
license = "GPL-3.0-or-later"
requires-python = ">=3.10"
dependencies = [
"yolocam",
]
[project.scripts]
yolocam-gui = "yolocam_gui.app:run"
[tool.setuptools.packages.find]
include = ["yolocam_gui*"]
+3
View File
@@ -0,0 +1,3 @@
yolocam
PySide6>=6.5
opencv-python>=4.8
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Launch YoloCam."""
from yolocam_gui.app import run
if __name__ == "__main__":
run()
+18
View File
@@ -0,0 +1,18 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""YoloCam - Camera control application for YoloCam S3."""
__version__ = "0.1.0"
+46
View File
@@ -0,0 +1,46 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Application entry point and QApplication setup."""
import sys
import logging
from PySide6.QtWidgets import QApplication
from .ui.theme import build_stylesheet
from .ui.main_window import MainWindow
from .controller import CameraController
log = logging.getLogger(__name__)
def run():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
app = QApplication(sys.argv)
app.setApplicationName("YoloCam")
app.setStyle("Fusion")
app.setStyleSheet(build_stylesheet())
window = MainWindow()
controller = CameraController(window, parent=window)
window.set_controller(controller)
window.show()
sys.exit(app.exec())
@@ -0,0 +1,64 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""YoloCam S3 backend library for camera control over TCP protobuf."""
from .camera_client import CameraClient
from .presets import PresetManager
from yolocam.params import (
PARAMS, ParamDef, PARAM_CATEGORIES,
ISO_VALUES, SHUTTER_TABLE, SHUTTER_REVERSE, APERTURE_TABLE,
ZOOM_RAW_MIN, ZOOM_RAW_MAX, ZOOM_MULT_MIN, ZOOM_MULT_MAX,
zoom_raw_to_mult, zoom_mult_to_raw,
sharpness_to_wire, sharpness_from_wire,
format_value, format_shutter, format_aperture, format_zoom,
is_readable, is_writable,
)
from yolocam.protocol import (
CAMERA_IP, CAMERA_PORT, DEFAULT_TIMEOUT,
pack_frame, unpack_frame, xor_checksum,
)
__all__ = [
"CameraClient",
"PresetManager",
"PARAMS",
"ParamDef",
"PARAM_CATEGORIES",
"ISO_VALUES",
"SHUTTER_TABLE",
"SHUTTER_REVERSE",
"APERTURE_TABLE",
"ZOOM_RAW_MIN",
"ZOOM_RAW_MAX",
"ZOOM_MULT_MIN",
"ZOOM_MULT_MAX",
"zoom_raw_to_mult",
"zoom_mult_to_raw",
"sharpness_to_wire",
"sharpness_from_wire",
"format_value",
"format_shutter",
"format_aperture",
"format_zoom",
"is_readable",
"is_writable",
"CAMERA_IP",
"CAMERA_PORT",
"DEFAULT_TIMEOUT",
"pack_frame",
"unpack_frame",
"xor_checksum",
]
@@ -0,0 +1,61 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Qt-integrated camera client for the YoloCam S3.
Thin wrapper around YoloCamClient that emits PySide6 signals for GUI integration.
"""
from PySide6.QtCore import QObject, Signal
from yolocam.client import YoloCamClient
from yolocam.protocol import CAMERA_IP, CAMERA_PORT, DEFAULT_TIMEOUT
class CameraClient(QObject, YoloCamClient):
"""Camera client with Qt signal integration.
Overrides YoloCamClient hook methods to emit signals, allowing GUI widgets
to receive updates via Qt's signal/slot mechanism.
"""
camera_connected = Signal()
camera_disconnected = Signal()
param_changed = Signal(str, object)
error_occurred = Signal(str)
recording_state_changed = Signal(bool)
recording_duration_changed = Signal(int)
def __init__(self, ip=CAMERA_IP, port=CAMERA_PORT, timeout=DEFAULT_TIMEOUT, parent=None):
QObject.__init__(self, parent)
YoloCamClient.__init__(self, ip, port, timeout)
def _on_connected(self):
self.camera_connected.emit()
def _on_disconnected(self):
self.camera_disconnected.emit()
def _on_error(self, message):
self.error_occurred.emit(message)
def _on_param_changed(self, name, value):
self.param_changed.emit(name, value)
def _on_recording_state_changed(self, recording):
self.recording_state_changed.emit(recording)
def _on_recording_duration_changed(self, duration):
self.recording_duration_changed.emit(duration)
+176
View File
@@ -0,0 +1,176 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Preset management for YoloCam S3 camera settings.
Presets are stored as JSON files in ~/.config/yolocam-gui/presets/.
Each preset is a dict mapping parameter names to raw protocol values.
"""
import json
import logging
import os
from pathlib import Path
from typing import Any, Dict, List, Optional
from yolocam.params import PARAMS, is_readable, is_writable
log = logging.getLogger(__name__)
PRESETS_DIR = Path(os.path.expanduser("~/.config/yolocam-gui/presets"))
# Parameters to include in presets (readable + writable, skip device info and set-only)
PRESET_PARAMS = [
name for name, pdef in PARAMS.items()
if is_readable(pdef) and is_writable(pdef)
]
DEFAULT_PRESET: Dict[str, int] = {
"brightness": 50,
"sharpness": 0,
"contrast": 50,
"saturation": 50,
"hue": 50,
"gamma": 50,
"zoom": 50,
"exposure-mode": 0,
"exposure-ev": 8,
"exposure-iso": 400,
"exposure-time": 16666,
"exposure-aperture": 10,
"exposure-lock": 0,
"anti-flicker": 0,
"dynamic-range": 50,
"hdr": 0,
"wb-mode": 1,
"wb-temp": 5500,
"wb-temp-shift": 64,
"wb-lock": 0,
"focus-mode": 1,
"focus-level": 0,
"focus-caf": 0,
"distortion": 0,
"shading": 0,
"au-volume": 50,
"au-denoise": 0,
"au-gain": 0,
}
class PresetManager:
"""Save, load, and apply camera parameter presets."""
def __init__(self, presets_dir: Optional[Path] = None):
self._dir = presets_dir or PRESETS_DIR
self._dir.mkdir(parents=True, exist_ok=True)
def _preset_path(self, name: str) -> Path:
safe_name = "".join(c if c.isalnum() or c in "-_ " else "_" for c in name)
return self._dir / f"{safe_name}.json"
def list_presets(self) -> List[str]:
"""Return sorted list of saved preset names."""
names = []
for p in self._dir.glob("*.json"):
try:
data = json.loads(p.read_text())
names.append(data.get("name", p.stem))
except (json.JSONDecodeError, OSError):
continue
return sorted(names)
def save_preset(self, name: str, params: Dict[str, Any]) -> None:
"""Save a preset to disk."""
data = {"name": name, "params": params}
path = self._preset_path(name)
path.write_text(json.dumps(data, indent=2))
log.info("Saved preset '%s' to %s", name, path)
def load_preset(self, name: str) -> Optional[Dict[str, Any]]:
"""Load a preset by name. Returns the params dict or None."""
path = self._preset_path(name)
if not path.exists():
log.warning("Preset '%s' not found at %s", name, path)
return None
try:
data = json.loads(path.read_text())
return data.get("params", {})
except (json.JSONDecodeError, OSError) as exc:
log.error("Failed to load preset '%s': %s", name, exc)
return None
def delete_preset(self, name: str) -> bool:
"""Delete a saved preset. Returns True if deleted."""
path = self._preset_path(name)
if not path.exists():
return False
path.unlink()
log.info("Deleted preset '%s'", name)
return True
def get_current_state(self, client: Any) -> Dict[str, Any]:
"""Read all preset-eligible parameters from the camera.
The client argument is a CameraClient instance (import avoided to prevent circular deps).
"""
state: Dict[str, Any] = {}
for name in PRESET_PARAMS:
raw = client.get_param_raw(name)
if raw is not None:
state[name] = raw
return state
def apply_preset(self, client: Any, name: str) -> bool:
"""Load a preset and apply all its parameters to the camera.
Returns True if the preset was found and applied (individual param
failures are logged but do not fail the overall operation).
"""
params = self.load_preset(name)
if params is None:
if name == "Default":
params = DEFAULT_PRESET
else:
return False
success_count = 0
total = len(params)
for param_name, value in params.items():
if param_name not in PARAMS:
log.warning("Skipping unknown parameter in preset: %s", param_name)
continue
if client.set_param(param_name, value):
success_count += 1
else:
log.warning("Failed to set %s=%s from preset '%s'", param_name, value, name)
log.info("Applied preset '%s': %d/%d parameters set", name, success_count, total)
return True
def save_default(self) -> None:
"""Write the built-in Default preset to disk."""
self.save_preset("Default", DEFAULT_PRESET)
+608
View File
@@ -0,0 +1,608 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Controller that wires UI signals to the CameraClient backend.
Handles value conversions (zoom mult/raw, sharpness wire format, WB mode inversion),
the initialization sequence, preset management, and all panel interactions.
All background threads marshal UI updates through _ui_update (Signal) to ensure
widget manipulation only happens on the main thread.
"""
import logging
import threading
from typing import Any, Optional
from PySide6.QtCore import QObject, Signal, Slot
from .backend.camera_client import CameraClient
from yolocam.params import (
zoom_mult_to_raw, zoom_raw_to_mult,
sharpness_to_wire, sharpness_from_wire,
)
from .backend.presets import PresetManager
log = logging.getLogger(__name__)
INIT_PARAMS = [
"sharpness", "contrast", "saturation",
"exposure-mode", "shading",
"zoom",
"wb-mode", "wb-temp", "wb-temp-shift", "wb-lock",
"exposure-ev", "anti-flicker", "exposure-iso", "exposure-time", "exposure-lock",
"dynamic-range",
"focus-mode", "focus-level", "focus-caf", "focus-trigger",
"hdr",
"hue", "brightness",
"clut-attr",
]
INIT_AUDIO_PARAMS = [
"au-volume", "au-denoise", "au-gain", "au-delay", "au-reverb",
]
INIT_STREAM_PARAMS = [
"hdmi-format", "hdmi-color",
]
class CameraController(QObject):
"""Connects all panel UI signals to the CameraClient and manages initialization."""
connection_changed = Signal(str)
status_message = Signal(str)
_ui_update = Signal(str, object)
_presets_refreshed = Signal(list)
def __init__(self, window, parent: Optional[QObject] = None):
super().__init__(parent)
self._window = window
self._panel = window.params_panel
self._color_panel = window.color_panel
self._console_panel = window.console_panel
self._stream_panel = window.stream_panel
self._settings_panel = window.settings_panel
self._client = CameraClient(parent=self)
self._presets = PresetManager()
self._connected = False
self._wb_red_offset = 10
self._wb_blue_offset = 10
self._tuning_brightness = 50
self._tuning_color_temp = 5500
self._ui_update.connect(self._update_ui_widget)
self._presets_refreshed.connect(self._panel.preset_bar.set_presets)
self._client.camera_connected.connect(self._on_connected)
self._client.camera_disconnected.connect(self._on_disconnected)
self._client.error_occurred.connect(self._on_error)
self._client.recording_state_changed.connect(self._console_panel.set_recording_state)
self._client.recording_duration_changed.connect(self._console_panel.set_recording_duration)
self._panel.param_changed.connect(self._on_param_changed)
self._panel.refresh_requested.connect(self.refresh_all)
self._panel.save_scene_requested.connect(self._on_save_scene)
self._panel.preset_bar.preset_selected.connect(self._on_preset_selected)
self._panel.preset_bar.preset_deleted.connect(self._on_preset_deleted)
self._panel.white_balance.eyedropper_requested.connect(self._on_eyedropper_requested)
self._window.video_widget.color_sampled.connect(self._on_color_sampled)
self._window.video_widget.eyedropper_deactivated.connect(
lambda: self._panel.white_balance.set_eyedropper_active(False)
)
self._color_panel.param_changed.connect(self._on_param_changed)
self._console_panel.param_changed.connect(self._on_param_changed)
self._stream_panel.param_changed.connect(self._on_param_changed)
self._settings_panel.format_sd_requested.connect(self._on_format_sd)
self._refresh_presets()
@property
def client(self) -> CameraClient:
return self._client
def connect_camera(self):
"""Initiate connection to camera in a background thread."""
self.status_message.emit("Connecting...")
def _connect():
try:
self._client.open()
except Exception as exc:
log.error("Connection failed: %s", exc)
threading.Thread(target=_connect, daemon=True, name="camera-connect").start()
def disconnect_camera(self):
self._client.close()
@Slot()
def refresh_all(self):
"""Read all parameters from camera and update UI."""
if not self._connected:
self.status_message.emit("Not connected")
return
self.status_message.emit("Reading parameters...")
def _read():
self._read_init_params()
self._read_audio_params()
self._read_stream_params()
self._read_wb_offset()
self._read_device_info()
self.status_message.emit("Ready")
threading.Thread(target=_read, daemon=True, name="param-refresh").start()
def _on_connected(self):
self._connected = True
self.connection_changed.emit("connected")
self.status_message.emit("Connected")
self._update_camera_combo("Y-CAM (connected)")
self._window.video_widget.auto_start()
self.refresh_all()
def _on_disconnected(self):
self._connected = False
self.connection_changed.emit("disconnected")
self.status_message.emit("Disconnected")
self._update_camera_combo("Y-CAM (disconnected)")
def _on_error(self, msg: str):
log.error("Camera error: %s", msg)
self.status_message.emit(f"Error: {msg}")
def _update_camera_combo(self, text: str):
combo = self._panel.camera_combo
combo.blockSignals(True)
combo.clear()
combo.addItem(text)
combo.blockSignals(False)
@Slot(str, object)
def _on_param_changed(self, name: str, value: Any):
"""Handle a UI parameter change by sending it to the camera."""
if not self._connected:
return
if name == "recording-start":
self._do_recording(True)
return
if name == "recording-stop":
self._do_recording(False)
return
if name == "ai-tracking":
self._do_ai_tracking(int(value))
return
if name == "clut-enable":
self._do_clut_enable(bool(value))
return
if name == "clut-attr":
self._do_clut_attr(int(value))
return
if name == "clut-reset":
self._do_clut_reset()
return
if name == "clut-grid-changed":
self._do_clut_grid(value)
return
if name == "wb-blue-offset":
self._wb_blue_offset = int(value)
self._do_wb_offset()
return
if name == "wb-red-offset":
self._wb_red_offset = int(value)
self._do_wb_offset()
return
if name == "color-hue":
wire_val = int(round(int(value) * 100.0 / 360.0))
self._send_param("hue", wire_val)
return
if name == "color-saturation":
self._send_param("saturation", int(value))
return
if name == "color-brightness":
self._send_param("brightness", int(value))
return
if name == "tuning-brightness":
self._tuning_brightness = int(value)
self._do_tuning()
return
if name == "tuning-color-temp":
self._tuning_color_temp = int(value)
self._do_tuning()
return
wire_value = self._ui_to_wire(name, value)
log.debug("UI -> camera: %s = %r (wire: %r)", name, value, wire_value)
def _send():
success = self._client.set_param(name, wire_value)
if not success:
log.warning("Failed to set %s=%r", name, wire_value)
threading.Thread(target=_send, daemon=True, name=f"set-{name}").start()
def _send_param(self, name: str, wire_value: Any):
"""Send a raw wire value to the camera in a background thread."""
if not self._connected:
return
def _send():
self._client.set_param(name, wire_value)
threading.Thread(target=_send, daemon=True, name=f"set-{name}").start()
def _do_recording(self, start: bool):
def _run():
if start:
success = self._client.start_recording()
else:
success = self._client.stop_recording()
if not success:
log.warning("Recording %s failed", "start" if start else "stop")
self._client.recording_state_changed.emit(not start)
threading.Thread(target=_run, daemon=True, name="recording").start()
def _do_ai_tracking(self, mode: int):
def _run():
self._client.set_ai_tracking(mode)
threading.Thread(target=_run, daemon=True, name="ai-tracking").start()
def _do_clut_enable(self, enabled: bool):
def _run():
self._client.set_clut_enabled(enabled)
threading.Thread(target=_run, daemon=True, name="clut-enable").start()
def _do_clut_attr(self, value: int):
def _run():
self._client.set_clut_attr(value)
threading.Thread(target=_run, daemon=True, name="clut-attr").start()
def _do_clut_reset(self):
def _run():
self._client.reset_clut()
self._client.set_clut_attr(0)
self._ui_update.emit("clut-attr", 0)
threading.Thread(target=_run, daemon=True, name="clut-reset").start()
def _do_clut_grid(self, grid_data: dict):
def _run():
if grid_data.get("mode") == "fast":
from yolocam.clut import fast_grid_to_clut
clut = fast_grid_to_clut(grid_data["grid"], grid_data.get("luma"))
else:
from yolocam.clut import hsv_grid_to_clut, LUMA_LEVELS, SAT_COLUMNS, HUE_SECTORS
wheel_hue = grid_data.get("hue", [])
wheel_sat = grid_data.get("sat", [])
wheel_luma = grid_data.get("luma", [])
n_hue = HUE_SECTORS + 1
hue_grid = [[[0.0] * n_hue for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
sat_grid = [[[1.0] * n_hue for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
luma_grid = [[[0.0] * n_hue for _ in range(SAT_COLUMNS)] for _ in range(LUMA_LEVELS)]
for h in range(min(n_hue, len(wheel_hue))):
for s in range(min(SAT_COLUMNS, len(wheel_hue[h]) if h < len(wheel_hue) else 0)):
hv = wheel_hue[h][s] if h < len(wheel_hue) and s < len(wheel_hue[h]) else 0.0
sv = wheel_sat[h][s] if h < len(wheel_sat) and s < len(wheel_sat[h]) else 0.0
lv = wheel_luma[h][s] if h < len(wheel_luma) and s < len(wheel_luma[h]) else 0.0
sat_scale = 1.0 + sv / 100.0
for l in range(LUMA_LEVELS):
hue_grid[l][s][h] = hv
sat_grid[l][s][h] = sat_scale
luma_grid[l][s][h] = lv / 100.0
clut = hsv_grid_to_clut(hue_grid, sat_grid, luma_grid)
self._client.send_clut(clut, hsv_data="{}")
self._client.set_clut_attr(0)
threading.Thread(target=_run, daemon=True, name="clut-grid").start()
def _on_eyedropper_requested(self):
self._window.video_widget.set_eyedropper_mode(True)
def _on_color_sampled(self, r: int, g: int, b: int):
self._panel.white_balance.set_eyedropper_active(False)
from yolocam.color import rgb_to_cct
temp = rgb_to_cct(r, g, b)
self._ui_update.emit("wb-mode", 0)
self._ui_update.emit("wb-temp", temp)
self.status_message.emit(f"WB: {temp}K from RGB({r},{g},{b})")
def _apply():
self._client.set_param("wb-mode", 0)
self._client.set_param("wb-temp", temp)
threading.Thread(target=_apply, daemon=True, name="eyedropper-wb").start()
def _do_wb_offset(self):
def _run():
self._client.set_wb_offset(self._wb_red_offset, self._wb_blue_offset)
threading.Thread(target=_run, daemon=True, name="wb-offset").start()
def _do_tuning(self):
def _run():
self._client.set_tuning(self._tuning_brightness, 0, self._tuning_color_temp)
threading.Thread(target=_run, daemon=True, name="tuning").start()
def _on_format_sd(self):
def _run():
self.status_message.emit("Formatting SD card...")
success = self._client.format_sd_card()
if success:
self.status_message.emit("SD card formatted")
else:
self.status_message.emit("SD card format failed")
threading.Thread(target=_run, daemon=True, name="format-sd").start()
def _ui_to_wire(self, name: str, value: Any) -> Any:
"""Convert UI-facing values to wire protocol values.
Note: zoom is NOT converted here because set_param() already handles
the multiplier-to-raw conversion internally.
"""
if name == "sharpness":
return sharpness_to_wire(int(value))
if name == "wb-mode":
return int(value)
if name in ("shading", "hdr", "exposure-lock", "wb-lock", "focus-caf", "au-gain", "uvc"):
return 1 if value else 0
if name == "zoom":
return float(value)
return int(value)
def _wire_to_ui(self, name: str, raw: int) -> Any:
"""Convert wire protocol values to UI-facing values."""
if name == "zoom":
return zoom_raw_to_mult(raw)
if name == "sharpness":
return sharpness_from_wire(raw)
return raw
def _read_init_params(self):
"""Read initialization parameters and emit UI updates via signal."""
for name in INIT_PARAMS:
raw = self._client.get_param_raw(name)
if raw is None:
continue
ui_val = self._wire_to_ui(name, raw)
self._ui_update.emit(name, ui_val)
def _read_audio_params(self):
"""Read audio parameters and emit UI updates via signal."""
for name in INIT_AUDIO_PARAMS:
raw = self._client.get_param_raw(name)
if raw is None:
continue
self._ui_update.emit(name, raw)
def _read_stream_params(self):
"""Read stream/HDMI parameters and emit UI updates via signal."""
for name in INIT_STREAM_PARAMS:
raw = self._client.get_param_raw(name)
if raw is None:
continue
self._ui_update.emit(name, raw)
def _read_wb_offset(self):
"""Read WB offset compound message and cache the values."""
from yolocam import yolocam_pb2 as pb
resp = self._client.request(pb.CID_WHITE_BALANCE_OFFSET)
if resp is None or not resp.HasField("body"):
return
body = resp.body
if body.WhichOneof("value") == "white_balance_offset":
self._wb_red_offset = body.white_balance_offset.offset_r
self._wb_blue_offset = body.white_balance_offset.offset_b
self._ui_update.emit("wb-red-offset-display", self._wb_red_offset)
self._ui_update.emit("wb-blue-offset-display", self._wb_blue_offset)
def _read_device_info(self):
"""Read device info and emit UI updates via signal."""
version_str = self._client.get_param("version")
if version_str:
self._ui_update.emit("device-firmware", version_str)
lens_str = self._client.get_param("lens-detail")
if lens_str:
self._ui_update.emit("device-lens", lens_str)
@Slot(str, object)
def _update_ui_widget(self, name: str, value: Any):
"""Route a parameter value to the appropriate UI widget setter.
Always runs on the main thread via the _ui_update signal connection.
"""
p = self._panel
if name == "sharpness":
p.image.set_sharpness(int(value))
elif name == "contrast":
p.image.set_contrast(int(value))
elif name == "saturation":
p.image.set_saturation(int(value))
self._color_panel.set_saturation(int(value))
elif name == "dynamic-range":
p.image.set_dynamic_range(int(value))
elif name == "frame-rate":
p.graphics.set_frame_rate(int(value))
elif name == "shading":
p.graphics.set_shading(bool(value))
elif name == "zoom":
p.zoom.set_zoom(float(value))
self._console_panel.set_zoom(float(value))
elif name == "focus-mode":
p.focus.set_focus_mode(int(value))
elif name == "focus-level":
p.focus.set_focus_area(int(value))
elif name == "focus-caf":
p.focus.set_focus_power(bool(value))
elif name == "focus-trigger":
p.focus.set_focus_speed(int(value))
elif name == "exposure-mode":
p.exposure.set_exposure_mode(int(value))
elif name == "hdr":
p.exposure.set_hdr(bool(value))
elif name == "anti-flicker":
p.exposure.set_anti_flicker(int(value))
elif name == "exposure-ev":
p.exposure.set_ev(int(value))
elif name == "exposure-iso":
p.exposure.set_iso(int(value))
elif name == "exposure-time":
p.exposure.set_shutter(int(value))
elif name == "exposure-lock":
p.exposure.set_exposure_lock(bool(value))
elif name == "wb-mode":
p.white_balance.set_wb_mode(int(value))
elif name == "wb-temp":
p.white_balance.set_temperature(int(value))
elif name == "wb-temp-shift":
p.white_balance.set_temp_shift(int(value))
elif name == "wb-lock":
p.white_balance.set_wb_lock(bool(value))
elif name == "au-volume":
p.audio.set_volume(int(value))
elif name == "au-denoise":
p.audio.set_noise_reduction(int(value))
elif name == "au-delay":
p.audio.set_delay(int(value))
elif name == "au-gain":
p.audio.set_auto_gain(bool(value))
elif name == "au-reverb":
p.audio.set_reverb(int(value))
elif name == "hue":
hue_360 = int(round(int(value) * 360.0 / 100.0))
self._color_panel.set_hue(hue_360)
elif name == "brightness":
self._color_panel.set_brightness(int(value))
elif name == "hdmi-format":
self._stream_panel.set_hdmi_format(int(value))
elif name == "hdmi-color":
self._stream_panel.set_hdmi_color(int(value))
elif name == "wb-red-offset-display":
p.white_balance.set_red_offset(int(value))
elif name == "wb-blue-offset-display":
p.white_balance.set_blue_offset(int(value))
elif name == "device-firmware":
self._settings_panel.set_firmware_info(str(value))
elif name == "device-lens":
self._settings_panel.set_lens_info(str(value))
elif name == "clut-attr":
self._color_panel.set_clut_attr(int(value))
elif name == "device-disk":
self._settings_panel.set_disk_info(value[0], value[1])
def _on_save_scene(self):
"""Save current camera state as a preset."""
if not self._connected:
self.status_message.emit("Connect to camera first")
return
from PySide6.QtWidgets import QInputDialog
name, ok = QInputDialog.getText(
self._panel, "Save Preset", "Preset name:"
)
if not ok or not name:
return
self.status_message.emit(f"Saving preset '{name}'...")
def _save():
state = self._presets.get_current_state(self._client)
self._presets.save_preset(name, state)
self._presets_refreshed.emit(self._presets.list_presets())
self.status_message.emit(f"Preset '{name}' saved")
threading.Thread(target=_save, daemon=True, name="save-preset").start()
def _on_preset_selected(self, name: str):
"""Apply a preset to the camera."""
if not self._connected:
self.status_message.emit("Connect to camera first")
return
self.status_message.emit(f"Applying preset '{name}'...")
def _apply():
self._presets.apply_preset(self._client, name)
self._read_init_params()
self._read_audio_params()
self.status_message.emit(f"Preset '{name}' applied")
threading.Thread(target=_apply, daemon=True, name="apply-preset").start()
def _on_preset_deleted(self, name: str):
"""Delete a preset."""
self._presets.delete_preset(name)
self._refresh_presets()
def _refresh_presets(self):
names = self._presets.list_presets()
self._panel.preset_bar.set_presets(names)
+15
View File
@@ -0,0 +1,15 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
+164
View File
@@ -0,0 +1,164 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Main application window."""
import logging
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QKeySequence, QShortcut
from PySide6.QtWidgets import (
QMainWindow, QWidget, QHBoxLayout, QScrollArea, QStackedWidget, QSizePolicy,
)
from .theme import COLOR_BG_PANEL, COLOR_BORDER
from .sidebar import Sidebar
from .video_widget import VideoWidget
from .panels import ImageParamsPanel, ColorPanel, ConsolePanel, StreamPanel, SettingsPanel
log = logging.getLogger(__name__)
class MainWindow(QMainWindow):
"""YoloCam main window with sidebar, stacked panels, and video feed."""
def __init__(self):
super().__init__()
self.setWindowTitle("YoloCam")
self.resize(1100, 570)
self._build_menu_bar()
self.statusBar().showMessage("Disconnected")
central = QWidget()
self.setCentralWidget(central)
root_layout = QHBoxLayout(central)
root_layout.setContentsMargins(0, 0, 0, 0)
root_layout.setSpacing(0)
self.sidebar = Sidebar()
self.sidebar.page_changed.connect(self._on_page_changed)
root_layout.addWidget(self.sidebar)
self.params_panel = ImageParamsPanel()
self.color_panel = ColorPanel()
self.console_panel = ConsolePanel()
self.stream_panel = StreamPanel()
self.settings_panel = SettingsPanel()
self._stacked = QStackedWidget()
self._panels = [
self.params_panel,
self.color_panel,
self.console_panel,
self.stream_panel,
self.settings_panel,
]
for panel in self._panels:
scroll = QScrollArea()
scroll.setWidget(panel)
scroll.setWidgetResizable(True)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
scroll.setStyleSheet(f"""
QScrollArea {{ border-right: 1px solid {COLOR_BORDER}; background-color: {COLOR_BG_PANEL}; }}
""")
self._stacked.addWidget(scroll)
self._stacked.setFixedWidth(400)
root_layout.addWidget(self._stacked)
self.video_widget = VideoWidget(device_index=-1)
self.video_widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
root_layout.addWidget(self.video_widget, 1)
self._controller = None
def set_controller(self, controller):
"""Attach the CameraController after construction."""
self._controller = controller
controller.status_message.connect(self.statusBar().showMessage)
controller.connection_changed.connect(self._on_connection_changed)
QTimer.singleShot(500, controller.connect_camera)
def _build_menu_bar(self):
menu_bar = self.menuBar()
app_menu = menu_bar.addMenu("YoloCam")
self._connect_action = app_menu.addAction("Connect to Camera")
self._connect_action.setShortcut(QKeySequence("Ctrl+Shift+C"))
self._connect_action.triggered.connect(self._toggle_connection)
app_menu.addSeparator()
quit_action = app_menu.addAction("Quit")
quit_action.setShortcut(QKeySequence.StandardKey.Quit)
quit_action.triggered.connect(self.close)
view_menu = menu_bar.addMenu("View")
for i, (label, key) in enumerate([
("Camera", "1"), ("Color", "2"), ("Console", "3"),
("Stream", "4"), ("Settings", "5"),
]):
action = view_menu.addAction(label)
action.setShortcut(QKeySequence(f"Ctrl+{key}"))
action.triggered.connect(lambda checked, idx=i: self._switch_panel(idx))
view_menu.addSeparator()
fullscreen_action = view_menu.addAction("Toggle Fullscreen")
fullscreen_action.setShortcut(QKeySequence.StandardKey.FullScreen)
fullscreen_action.triggered.connect(self._toggle_fullscreen)
help_menu = menu_bar.addMenu("Help")
help_menu.addAction("Documentation")
def _switch_panel(self, index: int):
if 0 <= index < self._stacked.count():
self._stacked.setCurrentIndex(index)
self.sidebar.set_active(index)
def _toggle_fullscreen(self):
if self.isFullScreen():
self.showNormal()
else:
self.showFullScreen()
def _on_page_changed(self, index: int):
if 0 <= index < self._stacked.count():
self._stacked.setCurrentIndex(index)
def _toggle_connection(self):
if self._controller is None:
return
if self._controller.client.connection_state == "connected":
self._controller.disconnect_camera()
else:
self._controller.connect_camera()
def _on_connection_changed(self, state: str):
if state == "connected":
self._connect_action.setText("Disconnect")
else:
self._connect_action.setText("Connect to Camera")
def closeEvent(self, event):
if self._controller:
self._controller.disconnect_camera()
self.video_widget.stop()
super().closeEvent(event)
@@ -0,0 +1,28 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
from .image_params import ImageParamsPanel
from .color_panel import ColorPanel
from .console_panel import ConsolePanel
from .stream_panel import StreamPanel
from .settings_panel import SettingsPanel
__all__ = [
"ImageParamsPanel",
"ColorPanel",
"ConsolePanel",
"StreamPanel",
"SettingsPanel",
]
@@ -0,0 +1,106 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Audio settings section."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QComboBox
from ..widgets import CollapsibleSection, ParamSlider, ToggleSwitch
NOISE_LEVELS = ["Close", "Weak", "Middle", "Strong"]
REVERB_LEVELS = ["Close", "Weak", "Middle", "Strong"]
class AudioSection(CollapsibleSection):
"""Collapsible panel for audio settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Audio Settings", parent)
self.volume_slider = ParamSlider("Volume", min_val=0, max_val=100, default=50, step=1)
self.volume_slider.value_changed.connect(lambda v: self.param_changed.emit("au-volume", v))
self.add_widget(self.volume_slider)
self.noise_combo = QComboBox()
self.noise_combo.addItems(NOISE_LEVELS)
self.noise_combo.setCurrentIndex(2)
self.noise_combo.currentIndexChanged.connect(
lambda idx: self.param_changed.emit("au-denoise", idx)
)
self.add_widget(self._labeled("Noise Reduction", self.noise_combo))
self.delay_slider = ParamSlider("Audio Delay", min_val=0, max_val=400, default=0, step=1, suffix="ms")
self.delay_slider.value_changed.connect(lambda v: self.param_changed.emit("au-delay", v))
self.add_widget(self.delay_slider)
self.auto_gain_toggle = ToggleSwitch(checked=True)
self.auto_gain_toggle.toggled.connect(lambda v: self.param_changed.emit("au-gain", v))
self._auto_gain_row = self._toggle_row("Auto Gain", self.auto_gain_toggle)
self.add_widget(self._auto_gain_row)
self.reverb_combo = QComboBox()
self.reverb_combo.addItems(REVERB_LEVELS)
self.reverb_combo.currentIndexChanged.connect(
lambda idx: self.param_changed.emit("au-reverb", idx)
)
self.add_widget(self._labeled("Reverb", self.reverb_combo))
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def set_volume(self, value: int):
self.volume_slider.set_value(float(value), emit=False)
def set_noise_reduction(self, value: int):
self.noise_combo.blockSignals(True)
self.noise_combo.setCurrentIndex(value)
self.noise_combo.blockSignals(False)
def set_delay(self, value: int):
self.delay_slider.set_value(float(value), emit=False)
def set_auto_gain(self, enabled: bool):
self.auto_gain_toggle.set_checked(enabled, emit=False)
def set_reverb(self, value: int):
self.reverb_combo.blockSignals(True)
self.reverb_combo.setCurrentIndex(value)
self.reverb_combo.blockSignals(False)
@@ -0,0 +1,215 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Color correction panel with HSV color wheel, sliders, and CLUT controls."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QSizePolicy,
)
from PySide6.QtGui import QFont
from ..theme import COLOR_ACCENT, COLOR_BG_PANEL, COLOR_TEXT_SECONDARY
from ..widgets import CollapsibleSection, ColorWheel, ParamSlider, ToggleSwitch, SegmentButton
class ColorPanel(QWidget):
"""Panel for HSV color grading and CLUT control.
Provides a visual color wheel for hue/saturation selection,
sliders for fine control, and CLUT enable/disable toggle.
"""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("colorPanel")
self.setStyleSheet(f"#colorPanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Color")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
outer.addWidget(header)
self._mode = SegmentButton(["Fast", "Professional"])
mode_row = QWidget()
mode_layout = QHBoxLayout(mode_row)
mode_layout.setContentsMargins(12, 4, 12, 4)
mode_layout.setSpacing(8)
mode_layout.addWidget(self._mode)
outer.addWidget(mode_row)
wheel_container = QWidget()
wheel_layout = QVBoxLayout(wheel_container)
wheel_layout.setContentsMargins(0, 8, 0, 4)
wheel_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self._wheel = ColorWheel()
wheel_layout.addWidget(self._wheel, 0, Qt.AlignmentFlag.AlignCenter)
self._grid_reset_btn = QPushButton("Reset Grid")
self._grid_reset_btn.setFixedHeight(28)
self._grid_reset_btn.setFixedWidth(self._wheel.WHEEL_SIZE)
wheel_layout.addWidget(self._grid_reset_btn, 0, Qt.AlignmentFlag.AlignCenter)
outer.addWidget(wheel_container)
slider_section = CollapsibleSection("HSV Controls")
self._hue_slider = ParamSlider("Hue", min_val=0, max_val=360, default=0, step=1)
slider_section.add_widget(self._hue_slider)
self._sat_slider = ParamSlider("Saturation", min_val=0, max_val=100, default=0, step=1)
slider_section.add_widget(self._sat_slider)
self._bright_slider = ParamSlider("Brightness", min_val=0, max_val=100, default=100, step=1)
slider_section.add_widget(self._bright_slider)
outer.addWidget(slider_section)
clut_section = CollapsibleSection("Color LUT")
self._clut_toggle = ToggleSwitch()
clut_section.add_widget(self._toggle_row("Enable CLUT", self._clut_toggle))
self._clut_attr = ParamSlider("Intensity", min_val=0, max_val=255, default=0, step=1)
clut_section.add_widget(self._clut_attr)
self._clut_reset_btn = QPushButton("Reset Color Grading")
self._clut_reset_btn.setProperty("accent", True)
self._clut_reset_btn.setFixedHeight(32)
clut_section.add_widget(self._clut_reset_btn)
outer.addWidget(clut_section)
tuning_section = CollapsibleSection("Tuning", expanded=False)
self._tuning_brightness = ParamSlider("Brightness", min_val=0, max_val=100, default=50, step=1)
tuning_section.add_widget(self._tuning_brightness)
self._tuning_color_temp = ParamSlider("Color Temp", min_val=2000, max_val=10000, default=5500, step=50)
tuning_section.add_widget(self._tuning_color_temp)
outer.addWidget(tuning_section)
outer.addStretch()
self._wire_signals()
def _wire_signals(self):
self._wheel.hue_changed.connect(self._on_wheel_hue)
self._wheel.saturation_changed.connect(self._on_wheel_sat)
self._hue_slider.value_changed.connect(self._on_slider_hue)
self._sat_slider.value_changed.connect(self._on_slider_sat)
self._bright_slider.value_changed.connect(self._on_slider_bright)
self._clut_toggle.toggled.connect(
lambda v: self.param_changed.emit("clut-enable", v)
)
self._clut_attr.value_changed.connect(
lambda v: self.param_changed.emit("clut-attr", int(v))
)
self._clut_reset_btn.clicked.connect(
lambda: self.param_changed.emit("clut-reset", True)
)
self._grid_reset_btn.clicked.connect(self._on_grid_reset)
self._mode.selection_changed.connect(self._on_mode_changed)
self._wheel.grid_changed.connect(
lambda data: self.param_changed.emit("clut-grid-changed", data)
)
self._tuning_brightness.value_changed.connect(
lambda v: self.param_changed.emit("tuning-brightness", v)
)
self._tuning_color_temp.value_changed.connect(
lambda v: self.param_changed.emit("tuning-color-temp", v)
)
def _on_wheel_hue(self, hue: int):
self._hue_slider.set_value(float(hue), emit=False)
self.param_changed.emit("color-hue", hue)
def _on_wheel_sat(self, sat: int):
self._sat_slider.set_value(float(sat), emit=False)
self.param_changed.emit("color-saturation", sat)
def _on_slider_hue(self, val: float):
self._wheel.set_hue(int(val))
self.param_changed.emit("color-hue", int(val))
def _on_slider_sat(self, val: float):
self._wheel.set_saturation(int(val))
self.param_changed.emit("color-saturation", int(val))
def _on_slider_bright(self, val: float):
self._wheel.set_brightness(int(val))
self.param_changed.emit("color-brightness", int(val))
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def set_hue(self, value: int):
self._wheel.set_hue(value)
self._hue_slider.set_value(float(value), emit=False)
def set_saturation(self, value: int):
self._wheel.set_saturation(value)
self._sat_slider.set_value(float(value), emit=False)
def set_brightness(self, value: int):
self._wheel.set_brightness(value)
self._bright_slider.set_value(float(value), emit=False)
def set_clut_enabled(self, enabled: bool):
self._clut_toggle.set_checked(enabled, emit=False)
def set_clut_attr(self, value: int):
self._clut_attr.set_value(float(value), emit=False)
def set_grid_data(self, data: dict):
self._wheel.set_grid_data(data)
def _on_grid_reset(self):
self._wheel.reset_grid()
self.param_changed.emit("clut-reset", True)
def _on_mode_changed(self, index: int):
mode = "fast" if index == 0 else "professional"
self._wheel.set_mode(mode)
@@ -0,0 +1,306 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Console panel with recording, AI tracking, and zoom controls."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
)
from PySide6.QtGui import QFont, QPainter, QColor
from ..theme import (
COLOR_ACCENT, COLOR_BG_PANEL, COLOR_BG_INPUT, COLOR_BORDER,
COLOR_TEXT_PRIMARY, COLOR_TEXT_SECONDARY,
)
from ..widgets import CollapsibleSection, SegmentButton
AI_TRACKING_MAP = {0: 2, 1: 0, 2: 1}
class _RecordButton(QPushButton):
"""Circular record button that toggles between ready and recording states."""
def __init__(self, parent=None):
super().__init__(parent)
self._recording = False
self.setFixedSize(60, 60)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setStyleSheet("QPushButton { background: transparent; border: none; }")
@property
def recording(self) -> bool:
return self._recording
@recording.setter
def recording(self, value: bool):
self._recording = value
self.update()
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor(COLOR_ACCENT))
p.drawEllipse(2, 2, 56, 56)
p.setBrush(QColor(COLOR_TEXT_PRIMARY))
if self._recording:
# White square (stop icon)
p.drawRoundedRect(20, 20, 20, 20, 3, 3)
else:
# White circle (record icon)
p.drawEllipse(17, 17, 26, 26)
p.end()
class _RecordingSection(CollapsibleSection):
"""Recording controls with record button, duration, and status."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Recording", parent)
self._recording = False
btn_container = QWidget()
btn_layout = QVBoxLayout(btn_container)
btn_layout.setContentsMargins(0, 4, 0, 4)
btn_layout.setSpacing(6)
btn_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.record_btn = _RecordButton()
self.record_btn.clicked.connect(self._toggle_recording)
btn_layout.addWidget(self.record_btn, 0, Qt.AlignmentFlag.AlignCenter)
self.duration_label = QLabel("00:00:00")
duration_font = QFont("monospace", 14)
self.duration_label.setFont(duration_font)
self.duration_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
btn_layout.addWidget(self.duration_label)
self.status_label = QLabel("Ready")
self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.status_label.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
btn_layout.addWidget(self.status_label)
self.add_widget(btn_container)
def _toggle_recording(self):
self._recording = not self._recording
self.record_btn.recording = self._recording
if self._recording:
self.status_label.setText("Recording")
self.status_label.setStyleSheet(f"color: {COLOR_ACCENT};")
self.param_changed.emit("recording-start", True)
else:
self.status_label.setText("Ready")
self.status_label.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
self.param_changed.emit("recording-stop", True)
def set_recording_state(self, recording: bool):
self._recording = recording
self.record_btn.recording = recording
if recording:
self.status_label.setText("Recording")
self.status_label.setStyleSheet(f"color: {COLOR_ACCENT};")
else:
self.status_label.setText("Ready")
self.status_label.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
self.duration_label.setText("00:00:00")
def set_recording_duration(self, seconds: int):
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
self.duration_label.setText(f"{h:02d}:{m:02d}:{s:02d}")
class _AITrackingSection(CollapsibleSection):
"""AI tracking mode selection."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("AI Tracking", parent)
self.mode_btn = SegmentButton(["Off", "Portrait", "Thing"])
self.mode_btn.selection_changed.connect(self._mode_changed)
self.add_widget(self._labeled("Mode", self.mode_btn))
def _mode_changed(self, index: int):
self.param_changed.emit("ai-tracking", AI_TRACKING_MAP[index])
def set_ai_tracking_mode(self, wire_value: int):
"""Set mode by wire protocol value (0=Portrait, 1=Thing, 2=Close)."""
reverse_map = {2: 0, 0: 1, 1: 2}
ui_index = reverse_map.get(wire_value, 0)
self.mode_btn.set_selected(ui_index, emit=False)
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
class _ZoomSection(CollapsibleSection):
"""Zoom controls with +/- buttons and quick presets."""
ZOOM_MIN = 1.0
ZOOM_MAX = 4.0
ZOOM_STEP = 0.5
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Zoom Controls", parent)
self._zoom = 1.0
self.zoom_display = QLabel("1.0x")
display_font = QFont()
display_font.setPointSize(18)
display_font.setBold(True)
self.zoom_display.setFont(display_font)
self.zoom_display.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.add_widget(self.zoom_display)
step_row = QWidget()
step_layout = QHBoxLayout(step_row)
step_layout.setContentsMargins(0, 4, 0, 4)
step_layout.setSpacing(8)
step_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.zoom_minus = QPushButton("\u2212")
self.zoom_minus.setFixedSize(40, 40)
self.zoom_minus.setCursor(Qt.CursorShape.PointingHandCursor)
self.zoom_minus.setStyleSheet(f"""
QPushButton {{ font-size: 20px; font-weight: bold; background-color: {COLOR_BG_INPUT};
border: 1px solid {COLOR_BORDER}; border-radius: 20px; }}
QPushButton:hover {{ background-color: {COLOR_BORDER}; }}
""")
self.zoom_minus.clicked.connect(self._zoom_out)
step_layout.addWidget(self.zoom_minus)
self.zoom_plus = QPushButton("+")
self.zoom_plus.setFixedSize(40, 40)
self.zoom_plus.setCursor(Qt.CursorShape.PointingHandCursor)
self.zoom_plus.setStyleSheet(f"""
QPushButton {{ font-size: 20px; font-weight: bold; background-color: {COLOR_BG_INPUT};
border: 1px solid {COLOR_BORDER}; border-radius: 20px; }}
QPushButton:hover {{ background-color: {COLOR_BORDER}; }}
""")
self.zoom_plus.clicked.connect(self._zoom_in)
step_layout.addWidget(self.zoom_plus)
self.add_widget(step_row)
preset_row = QWidget()
preset_layout = QHBoxLayout(preset_row)
preset_layout.setContentsMargins(0, 2, 0, 2)
preset_layout.setSpacing(6)
for zoom_val in [1.0, 2.0, 3.0, 4.0]:
btn = QPushButton(f"{int(zoom_val)}x")
btn.setFixedSize(48, 28)
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.clicked.connect(lambda checked, v=zoom_val: self._preset_clicked(v))
preset_layout.addWidget(btn)
preset_layout.addStretch()
self.add_widget(preset_row)
def _apply_zoom(self, value: float):
self._zoom = max(self.ZOOM_MIN, min(self.ZOOM_MAX, round(value, 1)))
self.zoom_display.setText(f"{self._zoom:.1f}x")
self.param_changed.emit("zoom", self._zoom)
def _zoom_in(self):
self._apply_zoom(self._zoom + self.ZOOM_STEP)
def _zoom_out(self):
self._apply_zoom(self._zoom - self.ZOOM_STEP)
def _preset_clicked(self, value: float):
self._apply_zoom(value)
def set_zoom(self, value: float):
self._zoom = max(self.ZOOM_MIN, min(self.ZOOM_MAX, round(value, 1)))
self.zoom_display.setText(f"{self._zoom:.1f}x")
class ConsolePanel(QWidget):
"""Panel with recording, AI tracking, and zoom controls."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("consolePanel")
self.setStyleSheet(f"#consolePanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Console")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
outer.addWidget(header)
self.recording = _RecordingSection()
self.ai_tracking = _AITrackingSection()
self.zoom = _ZoomSection()
for section in [self.recording, self.ai_tracking, self.zoom]:
section.param_changed.connect(self.param_changed.emit)
outer.addWidget(section)
outer.addStretch()
def set_recording_state(self, recording: bool):
self.recording.set_recording_state(recording)
def set_recording_duration(self, seconds: int):
self.recording.set_recording_duration(seconds)
def set_zoom(self, value: float):
self.zoom.set_zoom(value)
def set_ai_tracking_mode(self, wire_value: int):
self.ai_tracking.set_ai_tracking_mode(wire_value)
@@ -0,0 +1,182 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Exposure settings section with mode-dependent controls."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QComboBox
from ..widgets import CollapsibleSection, SegmentButton, ParamSlider, ToggleSwitch
S3_ISO_VALUES = [
100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250,
1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 9600, 12800,
]
SHUTTER_LABELS = [
("1/25", 40000), ("1/30", 33333), ("1/50", 20000), ("1/60", 16666),
("1/80", 12500), ("1/100", 10000), ("1/125", 8000), ("1/160", 6250),
("1/200", 5000), ("1/250", 4000), ("1/320", 3125), ("1/400", 2500),
("1/500", 2000), ("1/640", 1562), ("1/800", 1250), ("1/1000", 1000),
("1/1250", 800), ("1/1600", 625), ("1/2000", 500), ("1/2500", 400),
("1/3200", 312), ("1/4000", 250), ("1/5000", 200), ("1/6400", 156),
("1/8000", 125),
]
EV_LABELS = [
"-8", "-7", "-6", "-5", "-4", "-3", "-2", "-1",
"0", "+1", "+2", "+3", "+4", "+5", "+6", "+7", "+8",
]
class ExposureSection(CollapsibleSection):
"""Collapsible panel for exposure with auto/manual mode switching."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Exposure", parent)
self.exposure_mode = SegmentButton(["Auto", "Manual"])
self.exposure_mode.selection_changed.connect(self._mode_changed)
self.add_widget(self._labeled("Mode", self.exposure_mode))
self.hdr_toggle = ToggleSwitch()
self.hdr_toggle.toggled.connect(lambda v: self.param_changed.emit("hdr", v))
self._hdr_row = self._toggle_row("HDR", self.hdr_toggle)
self.add_widget(self._hdr_row)
self.anti_flicker = SegmentButton(["Close", "50Hz", "60Hz"])
self.anti_flicker.selection_changed.connect(
lambda idx: self.param_changed.emit("anti-flicker", idx)
)
self._anti_flicker_row = self._labeled("Anti-Flicker", self.anti_flicker)
self.add_widget(self._anti_flicker_row)
self.ev_slider = ParamSlider("EV Comp", min_val=0, max_val=16, default=8, step=1)
self.ev_slider.value_changed.connect(lambda v: self.param_changed.emit("exposure-ev", v))
self.add_widget(self.ev_slider)
self.iso_combo = QComboBox()
for iso in S3_ISO_VALUES:
self.iso_combo.addItem(str(iso), iso)
self.iso_combo.currentIndexChanged.connect(self._iso_changed)
self._iso_row = self._labeled("ISO", self.iso_combo)
self.add_widget(self._iso_row)
self.shutter_combo = QComboBox()
for label, us in SHUTTER_LABELS:
self.shutter_combo.addItem(label, us)
self.shutter_combo.setCurrentIndex(3)
self.shutter_combo.currentIndexChanged.connect(self._shutter_changed)
self._shutter_row = self._labeled("Shutter", self.shutter_combo)
self.add_widget(self._shutter_row)
self.exposure_lock_toggle = ToggleSwitch()
self.exposure_lock_toggle.toggled.connect(
lambda v: self.param_changed.emit("exposure-lock", v)
)
self._exp_lock_row = self._toggle_row("Exposure Lock", self.exposure_lock_toggle)
self.add_widget(self._exp_lock_row)
self._apply_mode_visibility(auto=True)
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def _mode_changed(self, index: int):
auto = (index == 0)
self.param_changed.emit("exposure-mode", index)
self._apply_mode_visibility(auto)
def _apply_mode_visibility(self, auto: bool):
self._anti_flicker_row.setVisible(auto)
self.ev_slider.setVisible(auto)
self._exp_lock_row.setVisible(auto)
self._iso_row.setVisible(not auto)
self._shutter_row.setVisible(not auto)
def _iso_changed(self, index: int):
if index >= 0:
iso_val = self.iso_combo.itemData(index)
self.param_changed.emit("exposure-iso", iso_val)
def _shutter_changed(self, index: int):
if index >= 0:
us_val = self.shutter_combo.itemData(index)
self.param_changed.emit("exposure-time", us_val)
def set_exposure_mode(self, value: int):
self.exposure_mode.set_selected(value, emit=False)
self._apply_mode_visibility(value == 0)
def set_hdr(self, enabled: bool):
self.hdr_toggle.set_checked(enabled, emit=False)
def set_anti_flicker(self, value: int):
self.anti_flicker.set_selected(value, emit=False)
def set_ev(self, raw: int):
self.ev_slider.set_value(float(raw), emit=False)
def set_iso(self, value: int):
"""Set ISO by raw protocol value."""
self.iso_combo.blockSignals(True)
for i in range(self.iso_combo.count()):
if self.iso_combo.itemData(i) == value:
self.iso_combo.setCurrentIndex(i)
break
self.iso_combo.blockSignals(False)
def set_shutter(self, us: int):
"""Set shutter by microsecond value."""
self.shutter_combo.blockSignals(True)
for i in range(self.shutter_combo.count()):
if self.shutter_combo.itemData(i) == us:
self.shutter_combo.setCurrentIndex(i)
break
self.shutter_combo.blockSignals(False)
def set_exposure_lock(self, enabled: bool):
self.exposure_lock_toggle.set_checked(enabled, emit=False)
@@ -0,0 +1,134 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Focus settings section."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QComboBox
from ..widgets import CollapsibleSection, SegmentButton, ToggleSwitch, ParamSlider
class FocusSection(CollapsibleSection):
"""Collapsible panel for focus settings with mode-dependent controls."""
param_changed = Signal(str, object)
MODES = ["AF-S", "Manual", "AF-C", "Face"]
MODE_VALUES = {"AF-S": 1, "Manual": 2, "AF-C": 3, "Face": 4}
def __init__(self, parent=None):
super().__init__("Focus", parent)
self.focus_mode = SegmentButton(self.MODES)
self.focus_mode.set_selected(2, emit=False)
self.focus_mode.selection_changed_text.connect(self._mode_changed)
self.add_widget(self._labeled("Mode", self.focus_mode))
self.focus_area_combo = QComboBox()
self.focus_area_combo.addItems(["Large", "Middle", "Small"])
self.focus_area_combo.currentIndexChanged.connect(
lambda idx: self.param_changed.emit("focus-level", idx)
)
self._focus_area_row = self._labeled("Focus Area", self.focus_area_combo)
self.add_widget(self._focus_area_row)
self.manual_focus = ParamSlider("Manual Focus", min_val=0, max_val=100, default=50, step=1)
self.manual_focus.value_changed.connect(
lambda v: self.param_changed.emit("focus-manual", v)
)
self._manual_focus_row = self.manual_focus
self.add_widget(self._manual_focus_row)
self.focus_power_toggle = ToggleSwitch(checked=True)
self.focus_power_toggle.toggled.connect(
lambda v: self.param_changed.emit("focus-caf", v)
)
self._focus_power_row = self._toggle_row("Focus Power", self.focus_power_toggle)
self.add_widget(self._focus_power_row)
self.focus_speed = SegmentButton(["Basic", "Quick"])
self.focus_speed.selection_changed.connect(
lambda idx: self.param_changed.emit("focus-trigger", idx)
)
self._focus_speed_row = self._labeled("Speed", self.focus_speed)
self.add_widget(self._focus_speed_row)
self._apply_mode_visibility("AF-C")
@staticmethod
def _labeled(text: str, widget: QWidget, stretch: bool = False) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
if stretch:
layout.addStretch()
layout.addWidget(widget)
if not stretch:
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def _mode_changed(self, mode_text: str):
value = self.MODE_VALUES.get(mode_text, 3)
self.param_changed.emit("focus-mode", value)
self._apply_mode_visibility(mode_text)
def _apply_mode_visibility(self, mode_text: str):
self._focus_area_row.setVisible(mode_text in ("AF-S", "AF-C"))
self._manual_focus_row.setVisible(mode_text == "Manual")
self._focus_power_row.setVisible(mode_text in ("AF-C", "Face"))
self._focus_speed_row.setVisible(mode_text == "AF-C")
def set_focus_mode(self, value: int):
"""Set focus mode by raw protocol value (1=AFS, 2=Manual, 3=AFC, 4=Face)."""
value_to_index = {1: 0, 2: 1, 3: 2, 4: 3}
idx = value_to_index.get(value, 2)
self.focus_mode.set_selected(idx, emit=False)
self._apply_mode_visibility(self.MODES[idx])
def set_focus_area(self, value: int):
self.focus_area_combo.blockSignals(True)
self.focus_area_combo.setCurrentIndex(value)
self.focus_area_combo.blockSignals(False)
def set_focus_power(self, enabled: bool):
self.focus_power_toggle.set_checked(enabled, emit=False)
def set_focus_speed(self, value: int):
self.focus_speed.set_selected(value, emit=False)
def set_manual_focus(self, value: int):
self.manual_focus.set_value(float(value), emit=False)
@@ -0,0 +1,78 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Graphics settings section (frame rate, lens shading)."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QComboBox
from ..widgets import CollapsibleSection, ToggleSwitch
class GraphicsSection(CollapsibleSection):
"""Collapsible panel for graphics/output settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Graphics Settings", parent)
self.framerate_combo = QComboBox()
self.framerate_combo.addItems(["25", "30", "50", "60"])
self.framerate_combo.setCurrentText("30")
self.framerate_combo.currentTextChanged.connect(
lambda v: self.param_changed.emit("frame-rate", int(v))
)
self.add_widget(self._labeled("Frame Rate", self.framerate_combo))
self.shading_toggle = ToggleSwitch(checked=True)
self.shading_toggle.toggled.connect(
lambda v: self.param_changed.emit("shading", v)
)
self.add_widget(self._toggle_row("Lens Shading", self.shading_toggle))
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def set_frame_rate(self, value: int):
self.framerate_combo.blockSignals(True)
self.framerate_combo.setCurrentText(str(value))
self.framerate_combo.blockSignals(False)
def set_shading(self, enabled: bool):
self.shading_toggle.set_checked(enabled, emit=False)
@@ -0,0 +1,108 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Image parameters panel that contains all collapsible settings sections."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QComboBox, QSizePolicy,
)
from PySide6.QtGui import QFont
from ..theme import COLOR_ACCENT, COLOR_BG_PANEL, COLOR_BORDER, COLOR_TEXT_SECONDARY
from ..widgets import PresetBar
from .graphics_section import GraphicsSection
from .image_section import ImageSection
from .focus_section import FocusSection
from .zoom_section import ZoomSection
from .exposure_section import ExposureSection
from .white_balance_section import WhiteBalanceSection
from .audio_section import AudioSection
class ImageParamsPanel(QWidget):
"""Scrollable panel containing all camera parameter sections."""
param_changed = Signal(str, object)
save_scene_requested = Signal()
refresh_requested = Signal()
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("imageParamsPanel")
self.setStyleSheet(f"#imageParamsPanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
top_bar = QWidget()
top_bar.setFixedHeight(44)
top_layout = QHBoxLayout(top_bar)
top_layout.setContentsMargins(12, 6, 12, 6)
top_layout.setSpacing(8)
self.camera_combo = QComboBox()
self.camera_combo.addItem("Y-CAM (disconnected)")
self.camera_combo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
top_layout.addWidget(self.camera_combo)
self.capture_btn = QPushButton()
self.capture_btn.setText("\u25cf")
self.capture_btn.setFixedSize(32, 32)
self.capture_btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_ACCENT}; color: white; border: none;
border-radius: 16px; font-size: 18px; }}
QPushButton:hover {{ background-color: #f02574; }}
""")
top_layout.addWidget(self.capture_btn)
outer.addWidget(top_bar)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Image Parameters")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
self.refresh_btn = QPushButton("\u21bb")
self.refresh_btn.setFixedSize(28, 28)
self.refresh_btn.setToolTip("Refresh parameters from camera")
self.refresh_btn.setStyleSheet(f"""
QPushButton {{ background: transparent; color: {COLOR_TEXT_SECONDARY}; border: none; font-size: 16px; }}
QPushButton:hover {{ color: white; }}
""")
self.refresh_btn.clicked.connect(self.refresh_requested.emit)
header_layout.addWidget(self.refresh_btn)
self.save_scene_btn = QPushButton("Save Scene")
self.save_scene_btn.setProperty("accent", True)
self.save_scene_btn.setFixedHeight(28)
self.save_scene_btn.clicked.connect(self.save_scene_requested.emit)
header_layout.addWidget(self.save_scene_btn)
outer.addWidget(header)
self.preset_bar = PresetBar()
outer.addWidget(self.preset_bar)
self.graphics = GraphicsSection()
self.image = ImageSection()
self.focus = FocusSection()
self.zoom = ZoomSection()
self.exposure = ExposureSection()
self.white_balance = WhiteBalanceSection()
self.audio = AudioSection()
for section in [self.graphics, self.image, self.focus, self.zoom,
self.exposure, self.white_balance, self.audio]:
section.param_changed.connect(self.param_changed.emit)
outer.addWidget(section)
outer.addStretch()
@@ -0,0 +1,57 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Image settings section (sharpness, contrast, saturation, dynamic range)."""
from PySide6.QtCore import Signal
from ..widgets import CollapsibleSection, ParamSlider
class ImageSection(CollapsibleSection):
"""Collapsible panel for image quality settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Image Settings", parent)
self.sharpness = ParamSlider("Sharpness", min_val=-10, max_val=30, default=5, step=1)
self.sharpness.value_changed.connect(lambda v: self.param_changed.emit("sharpness", v))
self.add_widget(self.sharpness)
self.contrast = ParamSlider("Contrast", min_val=0, max_val=100, default=50, step=1)
self.contrast.value_changed.connect(lambda v: self.param_changed.emit("contrast", v))
self.add_widget(self.contrast)
self.saturation = ParamSlider("Saturation", min_val=0, max_val=100, default=50, step=1)
self.saturation.value_changed.connect(lambda v: self.param_changed.emit("saturation", v))
self.add_widget(self.saturation)
self.dynamic_range = ParamSlider("Dynamic Range", min_val=0, max_val=100, default=50, step=1)
self.dynamic_range.value_changed.connect(lambda v: self.param_changed.emit("dynamic-range", v))
self.add_widget(self.dynamic_range)
def set_sharpness(self, value: int):
self.sharpness.set_value(float(value), emit=False)
def set_contrast(self, value: int):
self.contrast.set_value(float(value), emit=False)
def set_saturation(self, value: int):
self.saturation.set_value(float(value), emit=False)
def set_dynamic_range(self, value: int):
self.dynamic_range.set_value(float(value), emit=False)
@@ -0,0 +1,159 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Settings panel with device info and SD card management."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QMessageBox
from PySide6.QtGui import QFont
from ..theme import COLOR_BG_PANEL, COLOR_TEXT_SECONDARY
from ..widgets import CollapsibleSection
class _DeviceInfoSection(CollapsibleSection):
"""Read-only device information display."""
def __init__(self, parent=None):
super().__init__("Device Info", parent)
self.firmware_label = QLabel("--")
self.add_widget(self._info_row("Firmware", self.firmware_label))
self.serial_label = QLabel("--")
self.add_widget(self._info_row("Serial Number", self.serial_label))
self.lens_label = QLabel("--")
self.add_widget(self._info_row("Lens Info", self.lens_label))
def set_firmware_info(self, text: str):
self.firmware_label.setText(text)
def set_serial(self, text: str):
self.serial_label.setText(text)
def set_lens_info(self, text: str):
self.lens_label.setText(text)
@staticmethod
def _info_row(label_text: str, value_label: QLabel) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(label_text)
lbl.setFixedWidth(110)
lbl.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
layout.addWidget(lbl)
layout.addWidget(value_label)
layout.addStretch()
return row
class _SDCardSection(CollapsibleSection):
"""SD card storage info and format action."""
format_sd_requested = Signal()
def __init__(self, parent=None):
super().__init__("SD Card", parent)
self.storage_label = QLabel("-- / -- MB")
self.add_widget(self._info_row("Storage", self.storage_label))
self.format_btn = QPushButton("Format SD Card")
self.format_btn.setProperty("accent", True)
self.format_btn.setFixedHeight(32)
self.format_btn.clicked.connect(self._confirm_format)
self.add_widget(self.format_btn)
def _confirm_format(self):
result = QMessageBox.warning(
self, "Format SD Card",
"All data on the SD card will be erased. Continue?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No,
)
if result == QMessageBox.StandardButton.Yes:
self.format_sd_requested.emit()
def set_disk_info(self, available: int, total: int):
self.storage_label.setText(f"{available} / {total} MB")
@staticmethod
def _info_row(label_text: str, value_label: QLabel) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(label_text)
lbl.setFixedWidth(110)
lbl.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY};")
layout.addWidget(lbl)
layout.addWidget(value_label)
layout.addStretch()
return row
class SettingsPanel(QWidget):
"""Panel with device information and SD card management."""
param_changed = Signal(str, object)
format_sd_requested = Signal()
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("settingsPanel")
self.setStyleSheet(f"#settingsPanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Settings")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
outer.addWidget(header)
self.device_info = _DeviceInfoSection()
outer.addWidget(self.device_info)
self.sd_card = _SDCardSection()
self.sd_card.format_sd_requested.connect(self.format_sd_requested.emit)
outer.addWidget(self.sd_card)
outer.addStretch()
def set_firmware_info(self, text: str):
self.device_info.set_firmware_info(text)
def set_serial(self, text: str):
self.device_info.set_serial(text)
def set_lens_info(self, text: str):
self.device_info.set_lens_info(text)
def set_disk_info(self, available: int, total: int):
self.sd_card.set_disk_info(available, total)
@@ -0,0 +1,165 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Stream output panel with HDMI and UVC settings."""
from PySide6.QtCore import Signal
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QComboBox
from PySide6.QtGui import QFont
from ..theme import COLOR_BG_PANEL
from ..widgets import CollapsibleSection, ToggleSwitch
class _HDMISection(CollapsibleSection):
"""HDMI output format and color space settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("HDMI Output", parent)
self.format_combo = QComboBox()
for label, data in [("Auto", 0), ("4K", 1), ("1080p", 2), ("720p", 3)]:
self.format_combo.addItem(label, data)
self.format_combo.currentIndexChanged.connect(self._format_changed)
self.add_widget(self._labeled("Format", self.format_combo))
self.color_combo = QComboBox()
for label, data in [("Auto", 0), ("RGB", 1), ("YUV422", 2)]:
self.color_combo.addItem(label, data)
self.color_combo.currentIndexChanged.connect(self._color_changed)
self.add_widget(self._labeled("Color Space", self.color_combo))
def _format_changed(self, index: int):
if index >= 0:
self.param_changed.emit("hdmi-format", self.format_combo.itemData(index))
def _color_changed(self, index: int):
if index >= 0:
self.param_changed.emit("hdmi-color", self.color_combo.itemData(index))
def set_hdmi_format(self, value: int):
self.format_combo.blockSignals(True)
for i in range(self.format_combo.count()):
if self.format_combo.itemData(i) == value:
self.format_combo.setCurrentIndex(i)
break
self.format_combo.blockSignals(False)
def set_hdmi_color(self, value: int):
self.color_combo.blockSignals(True)
for i in range(self.color_combo.count()):
if self.color_combo.itemData(i) == value:
self.color_combo.setCurrentIndex(i)
break
self.color_combo.blockSignals(False)
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
class _UVCSection(CollapsibleSection):
"""UVC output enable/disable toggle."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("UVC Output", parent)
self.uvc_toggle = ToggleSwitch()
self.uvc_toggle.toggled.connect(lambda v: self.param_changed.emit("uvc", v))
self.add_widget(self._toggle_row("Enable", self.uvc_toggle))
def set_uvc_enabled(self, enabled: bool):
self.uvc_toggle.set_checked(enabled, emit=False)
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
class StreamPanel(QWidget):
"""Panel with HDMI and UVC output settings."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("streamPanel")
self.setStyleSheet(f"#streamPanel {{ background-color: {COLOR_BG_PANEL}; }}")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
header = QWidget()
header.setFixedHeight(36)
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(12, 4, 12, 4)
header_layout.setSpacing(8)
title = QLabel("Stream")
title_font = QFont()
title_font.setBold(True)
title_font.setPointSize(11)
title.setFont(title_font)
header_layout.addWidget(title)
header_layout.addStretch()
outer.addWidget(header)
self.hdmi = _HDMISection()
self.uvc = _UVCSection()
for section in [self.hdmi, self.uvc]:
section.param_changed.connect(self.param_changed.emit)
outer.addWidget(section)
outer.addStretch()
def set_hdmi_format(self, value: int):
self.hdmi.set_hdmi_format(value)
def set_hdmi_color(self, value: int):
self.hdmi.set_hdmi_color(value)
def set_uvc_enabled(self, enabled: bool):
self.uvc.set_uvc_enabled(enabled)
@@ -0,0 +1,158 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""White balance settings section with mode-dependent controls."""
from PySide6.QtCore import Signal
from PySide6.QtGui import QFont
from PySide6.QtWidgets import QWidget, QHBoxLayout, QLabel, QToolButton
from ..widgets import CollapsibleSection, SegmentButton, ParamSlider, ToggleSwitch
class WhiteBalanceSection(CollapsibleSection):
"""Collapsible panel for white balance with auto/manual mode switching."""
param_changed = Signal(str, object)
eyedropper_requested = Signal()
def __init__(self, parent=None):
super().__init__("White Balance", parent)
self.wb_mode = SegmentButton(["Auto", "Manual"])
self.wb_mode.selection_changed_text.connect(self._mode_changed)
self._eyedropper_btn = QToolButton()
self._eyedropper_btn.setText("\u2316")
self._eyedropper_btn.setToolTip("Pick White Balance from Video")
self._eyedropper_btn.setCheckable(True)
btn_font = QFont()
btn_font.setPointSize(14)
self._eyedropper_btn.setFont(btn_font)
self._eyedropper_btn.setFixedSize(28, 28)
self._eyedropper_btn.toggled.connect(self._on_eyedropper_toggled)
mode_row = self._labeled("Mode", self.wb_mode)
mode_row.layout().addWidget(self._eyedropper_btn)
self.add_widget(mode_row)
self.wb_lock_toggle = ToggleSwitch()
self.wb_lock_toggle.toggled.connect(lambda v: self.param_changed.emit("wb-lock", v))
self._lock_row = self._toggle_row("WB Lock", self.wb_lock_toggle)
self.add_widget(self._lock_row)
self.temperature_slider = ParamSlider(
"Temperature", min_val=2000, max_val=10000, default=5000, step=50, suffix="K"
)
self.temperature_slider.value_changed.connect(
lambda v: self.param_changed.emit("wb-temp", v)
)
self.add_widget(self.temperature_slider)
self.temp_shift_slider = ParamSlider(
"Temp Shift", min_val=0, max_val=128, default=64, step=1
)
self.temp_shift_slider.value_changed.connect(
lambda v: self.param_changed.emit("wb-temp-shift", v)
)
self.add_widget(self.temp_shift_slider)
self.blue_offset_slider = ParamSlider(
"Blue Offset", min_val=0, max_val=20, default=10, step=1
)
self.blue_offset_slider.value_changed.connect(
lambda v: self.param_changed.emit("wb-blue-offset", v)
)
self.add_widget(self.blue_offset_slider)
self.red_offset_slider = ParamSlider(
"Red Offset", min_val=0, max_val=20, default=10, step=1
)
self.red_offset_slider.value_changed.connect(
lambda v: self.param_changed.emit("wb-red-offset", v)
)
self.add_widget(self.red_offset_slider)
self._apply_mode_visibility(auto=True)
@staticmethod
def _labeled(text: str, widget: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(110)
layout.addWidget(lbl)
layout.addWidget(widget)
layout.addStretch()
return row
@staticmethod
def _toggle_row(text: str, toggle: ToggleSwitch) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
lbl = QLabel(text)
lbl.setFixedWidth(170)
layout.addWidget(lbl)
layout.addStretch()
layout.addWidget(toggle)
return row
def _mode_changed(self, mode: str):
auto = (mode == "Auto")
value = 1 if auto else 0
self.param_changed.emit("wb-mode", value)
self._apply_mode_visibility(auto)
def _apply_mode_visibility(self, auto: bool):
self._lock_row.setVisible(auto)
self.temperature_slider.setVisible(not auto)
self.temp_shift_slider.setVisible(not auto)
self.blue_offset_slider.setVisible(not auto)
self.red_offset_slider.setVisible(not auto)
def _on_eyedropper_toggled(self, checked: bool):
if checked:
self.eyedropper_requested.emit()
def set_eyedropper_active(self, active: bool):
"""Set the eyedropper button check state without emitting signals."""
self._eyedropper_btn.blockSignals(True)
self._eyedropper_btn.setChecked(active)
self._eyedropper_btn.blockSignals(False)
def set_wb_mode(self, value: int):
"""Set WB mode by raw value (0=Manual, 1=Auto)."""
idx = 0 if value == 1 else 1
self.wb_mode.set_selected(idx, emit=False)
self._apply_mode_visibility(value == 1)
def set_wb_lock(self, enabled: bool):
self.wb_lock_toggle.set_checked(enabled, emit=False)
def set_temperature(self, value: int):
self.temperature_slider.set_value(float(value), emit=False)
def set_temp_shift(self, value: int):
self.temp_shift_slider.set_value(float(value), emit=False)
def set_blue_offset(self, value: int):
self.blue_offset_slider.set_value(float(value), emit=False)
def set_red_offset(self, value: int):
self.red_offset_slider.set_value(float(value), emit=False)
@@ -0,0 +1,38 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Zoom settings section."""
from PySide6.QtCore import Signal
from ..widgets import CollapsibleSection, ParamSlider
class ZoomSection(CollapsibleSection):
"""Collapsible panel for zoom control."""
param_changed = Signal(str, object)
def __init__(self, parent=None):
super().__init__("Zoom", parent)
self.zoom_slider = ParamSlider(
"Zoom", min_val=1.0, max_val=4.0, default=1.0, step=0.1, decimals=1, suffix="x"
)
self.zoom_slider.value_changed.connect(lambda v: self.param_changed.emit("zoom", v))
self.add_widget(self.zoom_slider)
def set_zoom(self, mult: float):
self.zoom_slider.set_value(mult, emit=False)
+76
View File
@@ -0,0 +1,76 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Left icon sidebar for navigation."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QWidget, QVBoxLayout, QToolButton, QSizePolicy
from PySide6.QtGui import QFont
from .theme import COLOR_BG_SIDEBAR, COLOR_BORDER
class Sidebar(QWidget):
"""48px-wide vertical icon sidebar."""
page_changed = Signal(int)
ICONS = [
("\u2699", "Parameters"),
("\U0001F3A8", "Color"),
("\u2328", "Console"),
("\U0001F4E1", "Stream"),
("\u2638", "Settings"),
]
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedWidth(48)
self.setObjectName("sidebar")
self.setStyleSheet(f"""
#sidebar {{ background-color: {COLOR_BG_SIDEBAR}; border-right: 1px solid {COLOR_BORDER}; }}
""")
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 8, 0, 8)
layout.setSpacing(4)
layout.setAlignment(Qt.AlignmentFlag.AlignTop)
self._buttons: list[QToolButton] = []
icon_font = QFont()
icon_font.setPointSize(16)
for i, (icon, tooltip) in enumerate(self.ICONS):
btn = QToolButton()
btn.setText(icon)
btn.setFont(icon_font)
btn.setToolTip(tooltip)
btn.setCheckable(True)
btn.setFixedSize(40, 40)
btn.clicked.connect(lambda checked, idx=i: self._on_click(idx))
self._buttons.append(btn)
layout.addWidget(btn, alignment=Qt.AlignmentFlag.AlignCenter)
layout.addStretch()
if self._buttons:
self._buttons[0].setChecked(True)
def set_active(self, index: int):
"""Set the active button without emitting page_changed."""
for i, btn in enumerate(self._buttons):
btn.setChecked(i == index)
def _on_click(self, index: int):
self.set_active(index)
self.page_changed.emit(index)
+236
View File
@@ -0,0 +1,236 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Dark theme stylesheet for YoloCam."""
# Palette constants used throughout the application
COLOR_BG_DARK = "#181818"
COLOR_BG_PANEL = "#242424"
COLOR_BG_SECTION_HEADER = "#2d2d2d"
COLOR_BG_INPUT = "#333333"
COLOR_BG_SIDEBAR = "#1e1e1e"
COLOR_ACCENT = "#e91e63"
COLOR_ACCENT_LIGHT = "#ff5252"
COLOR_SLIDER_EMPTY = "#444444"
COLOR_TOGGLE_OFF = "#555555"
COLOR_TEXT_PRIMARY = "#ffffff"
COLOR_TEXT_SECONDARY = "#aaaaaa"
COLOR_BORDER = "#3a3a3a"
def build_stylesheet() -> str:
return f"""
/* Global defaults */
QWidget {{
background-color: {COLOR_BG_DARK};
color: {COLOR_TEXT_PRIMARY};
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
font-size: 13px;
}}
/* Main window */
QMainWindow {{
background-color: {COLOR_BG_DARK};
}}
/* Scroll area used for the parameter panel */
QScrollArea {{
border: none;
background-color: {COLOR_BG_PANEL};
}}
QScrollArea > QWidget > QWidget {{
background-color: {COLOR_BG_PANEL};
}}
QScrollBar:vertical {{
background: {COLOR_BG_PANEL};
width: 8px;
margin: 0;
}}
QScrollBar::handle:vertical {{
background: {COLOR_SLIDER_EMPTY};
min-height: 30px;
border-radius: 4px;
}}
QScrollBar::handle:vertical:hover {{
background: {COLOR_TEXT_SECONDARY};
}}
QScrollBar::add-line:vertical,
QScrollBar::sub-line:vertical {{
height: 0;
}}
QScrollBar:horizontal {{
height: 0;
}}
/* Labels */
QLabel {{
background: transparent;
color: {COLOR_TEXT_PRIMARY};
padding: 0;
}}
/* ComboBox / dropdown */
QComboBox {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
border-radius: 4px;
padding: 4px 8px;
min-height: 24px;
}}
QComboBox:hover {{
border-color: {COLOR_ACCENT};
}}
QComboBox::drop-down {{
border: none;
width: 20px;
}}
QComboBox::down-arrow {{
image: none;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 5px solid {COLOR_TEXT_SECONDARY};
margin-right: 6px;
}}
QComboBox QAbstractItemView {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
selection-background-color: {COLOR_ACCENT};
selection-color: {COLOR_TEXT_PRIMARY};
}}
/* SpinBox */
QSpinBox, QDoubleSpinBox {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
border-radius: 4px;
padding: 2px 4px;
min-height: 22px;
}}
QSpinBox::up-button, QDoubleSpinBox::up-button {{
subcontrol-origin: border;
subcontrol-position: top right;
width: 16px;
border-left: 1px solid {COLOR_BORDER};
background: {COLOR_BG_SECTION_HEADER};
}}
QSpinBox::down-button, QDoubleSpinBox::down-button {{
subcontrol-origin: border;
subcontrol-position: bottom right;
width: 16px;
border-left: 1px solid {COLOR_BORDER};
background: {COLOR_BG_SECTION_HEADER};
}}
QSpinBox::up-arrow, QDoubleSpinBox::up-arrow {{
border-left: 3px solid transparent;
border-right: 3px solid transparent;
border-bottom: 4px solid {COLOR_TEXT_SECONDARY};
width: 0; height: 0;
}}
QSpinBox::down-arrow, QDoubleSpinBox::down-arrow {{
border-left: 3px solid transparent;
border-right: 3px solid transparent;
border-top: 4px solid {COLOR_TEXT_SECONDARY};
width: 0; height: 0;
}}
/* Push buttons */
QPushButton {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
border-radius: 4px;
padding: 5px 12px;
min-height: 24px;
}}
QPushButton:hover {{
background-color: {COLOR_SLIDER_EMPTY};
}}
QPushButton:pressed {{
background-color: {COLOR_BG_SECTION_HEADER};
}}
QPushButton[accent="true"] {{
background-color: {COLOR_ACCENT};
border: none;
font-weight: bold;
}}
QPushButton[accent="true"]:hover {{
background-color: #f02574;
}}
/* Tool buttons (sidebar icons) */
QToolButton {{
background: transparent;
border: none;
padding: 8px;
border-radius: 4px;
color: {COLOR_TEXT_SECONDARY};
}}
QToolButton:hover {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
}}
QToolButton:checked {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_ACCENT};
}}
/* Slider (default Qt slider, overridden by ParamSlider painting) */
QSlider::groove:horizontal {{
background: {COLOR_SLIDER_EMPTY};
height: 4px;
border-radius: 2px;
}}
QSlider::handle:horizontal {{
background: {COLOR_TEXT_PRIMARY};
width: 14px;
height: 14px;
margin: -5px 0;
border-radius: 7px;
}}
QSlider::sub-page:horizontal {{
background: qlineargradient(
x1:0, y1:0, x2:1, y2:0,
stop:0 {COLOR_ACCENT}, stop:1 {COLOR_ACCENT_LIGHT}
);
border-radius: 2px;
}}
/* Menu bar */
QMenuBar {{
background-color: {COLOR_BG_SIDEBAR};
color: {COLOR_TEXT_PRIMARY};
border-bottom: 1px solid {COLOR_BORDER};
}}
QMenuBar::item:selected {{
background-color: {COLOR_BG_INPUT};
}}
QMenu {{
background-color: {COLOR_BG_INPUT};
color: {COLOR_TEXT_PRIMARY};
border: 1px solid {COLOR_BORDER};
}}
QMenu::item:selected {{
background-color: {COLOR_ACCENT};
}}
/* Frame separators */
QFrame[frameShape="4"] {{
color: {COLOR_BORDER};
max-height: 1px;
}}
"""
+232
View File
@@ -0,0 +1,232 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Video preview widget using OpenCV capture."""
import logging
import os
import re
import numpy as np
from PySide6.QtCore import Qt, QTimer, Signal, Slot
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy
from PySide6.QtGui import QImage, QPixmap, QFont
from .theme import COLOR_BG_DARK, COLOR_TEXT_SECONDARY
log = logging.getLogger(__name__)
YOLOCAM_VID = "46f8"
YOLOCAM_PID = "0855"
try:
import cv2
_HAS_CV2 = True
except ImportError:
_HAS_CV2 = False
log.warning("opencv-python not installed, video preview will be disabled")
def find_yolocam_device() -> int:
"""Scan /sys/class/video4linux for the YoloCam S3 UVC device.
Returns the lowest /dev/videoN index matching VID:PID 46f8:0855,
or -1 if not found.
"""
v4l_path = "/sys/class/video4linux"
if not os.path.isdir(v4l_path):
return -1
candidates = []
for entry in sorted(os.listdir(v4l_path)):
dev_path = os.path.join(v4l_path, entry, "device")
if not os.path.isdir(dev_path):
continue
try:
vid_path = os.path.join(dev_path, "..", "idVendor")
pid_path = os.path.join(dev_path, "..", "idProduct")
vid = open(os.path.realpath(vid_path)).read().strip()
pid = open(os.path.realpath(pid_path)).read().strip()
except (OSError, IOError):
continue
if vid == YOLOCAM_VID and pid == YOLOCAM_PID:
m = re.search(r"(\d+)$", entry)
if m:
candidates.append(int(m.group(1)))
if candidates:
return min(candidates)
return -1
class VideoWidget(QWidget):
"""Displays live camera feed from a UVC device, or a placeholder if disconnected."""
color_sampled = Signal(int, int, int)
eyedropper_deactivated = Signal()
def __init__(self, device_index: int = -1, parent=None):
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.setMinimumSize(320, 240)
self.setStyleSheet(f"background-color: {COLOR_BG_DARK};")
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
self._label = QLabel()
self._label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self._label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
layout.addWidget(self._label)
self._cap = None
self._timer = QTimer(self)
self._timer.timeout.connect(self._grab_frame)
self._last_frame = None
self._eyedropper_active = False
if device_index >= 0:
self.start(device_index)
else:
self._show_placeholder()
def auto_start(self):
"""Auto-detect the YoloCam UVC device and start capture."""
idx = find_yolocam_device()
if idx < 0:
log.info("YoloCam UVC device not found")
self._show_placeholder("YoloCam not detected")
return
log.info("YoloCam UVC device found at /dev/video%d", idx)
self.start(idx)
def start(self, device_index: int = 0):
"""Open the video device and begin grabbing frames."""
if not _HAS_CV2:
self._show_placeholder("OpenCV not available")
return
self.stop()
self._cap = cv2.VideoCapture(device_index)
self._cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
if not self._cap.isOpened():
log.warning("Could not open video device %d", device_index)
self._cap = None
self._show_placeholder()
return
self._timer.start(33)
def stop(self):
"""Stop capturing and release the device."""
self._timer.stop()
if self._cap is not None:
self._cap.release()
self._cap = None
@Slot()
def _grab_frame(self):
if self._cap is None:
return
ret, frame = self._cap.read()
if not ret:
return
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
self._last_frame = rgb
h, w, ch = rgb.shape
bytes_per_line = ch * w
qimg = QImage(rgb.data, w, h, bytes_per_line, QImage.Format.Format_RGB888)
scaled = qimg.scaled(
self._label.size(),
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
self._label.setPixmap(QPixmap.fromImage(scaled))
def set_eyedropper_mode(self, enabled: bool):
"""Activate or deactivate eyedropper sampling mode."""
self._eyedropper_active = enabled
if enabled:
self.setCursor(Qt.CursorShape.CrossCursor)
else:
self.unsetCursor()
def mousePressEvent(self, event):
if not self._eyedropper_active:
super().mousePressEvent(event)
return
self._eyedropper_active = False
self.unsetCursor()
if self._last_frame is None:
self.eyedropper_deactivated.emit()
return
# Map click position to frame coordinates
click_pos = self._label.mapFromParent(event.position().toPoint())
frame_h, frame_w = self._last_frame.shape[:2]
label_w = self._label.width()
label_h = self._label.height()
scale = min(label_w / frame_w, label_h / frame_h)
scaled_w = frame_w * scale
scaled_h = frame_h * scale
offset_x = (label_w - scaled_w) / 2
offset_y = (label_h - scaled_h) / 2
fx = (click_pos.x() - offset_x) * frame_w / scaled_w
fy = (click_pos.y() - offset_y) * frame_h / scaled_h
if fx < 0 or fx >= frame_w or fy < 0 or fy >= frame_h:
self.eyedropper_deactivated.emit()
return
# Average an 11x11 neighborhood
cx, cy = int(fx), int(fy)
half = 5
x0, x1 = max(0, cx - half), min(frame_w, cx + half + 1)
y0, y1 = max(0, cy - half), min(frame_h, cy + half + 1)
patch = self._last_frame[y0:y1, x0:x1]
avg = patch.mean(axis=(0, 1))
r, g, b = int(avg[0]), int(avg[1]), int(avg[2])
self.color_sampled.emit(r, g, b)
self.eyedropper_deactivated.emit()
def _show_placeholder(self, text: str = "No camera connected"):
self._label.setPixmap(QPixmap())
self._label.setText(text)
placeholder_font = QFont()
placeholder_font.setPointSize(14)
self._label.setFont(placeholder_font)
self._label.setStyleSheet(f"color: {COLOR_TEXT_SECONDARY}; background: transparent;")
def closeEvent(self, event):
self.stop()
super().closeEvent(event)
@@ -0,0 +1,30 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
from .collapsible_section import CollapsibleSection
from .param_slider import ParamSlider
from .toggle_switch import ToggleSwitch
from .segment_button import SegmentButton
from .preset_bar import PresetBar
from .color_wheel import ColorWheel
__all__ = [
"CollapsibleSection",
"ParamSlider",
"ToggleSwitch",
"SegmentButton",
"PresetBar",
"ColorWheel",
]
@@ -0,0 +1,162 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Collapsible section widget with animated expand/collapse."""
from PySide6.QtCore import Qt, QPropertyAnimation, QEasingCurve, Property, QPointF
from PySide6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QLabel, QFrame, QSizePolicy,
)
from PySide6.QtGui import QPainter, QColor, QFont
from ..theme import COLOR_BG_SECTION_HEADER, COLOR_TEXT_PRIMARY, COLOR_BORDER
class _HeaderBar(QWidget):
"""Clickable header bar with triangle arrow and title."""
def __init__(self, title: str, parent=None):
super().__init__(parent)
self.title = title
self._expanded = True
self.setFixedHeight(32)
self.setCursor(Qt.CursorShape.PointingHandCursor)
@property
def expanded(self) -> bool:
return self._expanded
@expanded.setter
def expanded(self, value: bool):
self._expanded = value
self.update()
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.fillRect(self.rect(), QColor(COLOR_BG_SECTION_HEADER))
arrow_x = 12
arrow_y = self.height() // 2
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor(COLOR_TEXT_PRIMARY))
if self._expanded:
p.drawPolygon([
QPointF(arrow_x - 4, arrow_y - 2),
QPointF(arrow_x + 4, arrow_y - 2),
QPointF(arrow_x, arrow_y + 3),
])
else:
p.drawPolygon([
QPointF(arrow_x - 2, arrow_y - 4),
QPointF(arrow_x + 3, arrow_y),
QPointF(arrow_x - 2, arrow_y + 4),
])
p.setPen(QColor(COLOR_TEXT_PRIMARY))
font = QFont()
font.setBold(True)
font.setPointSize(10)
p.setFont(font)
p.drawText(
28, 0, self.width() - 32, self.height(),
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
self.title,
)
p.end()
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.parent().toggle()
class CollapsibleSection(QWidget):
"""A section with a clickable header that expands and collapses its content area."""
def __init__(self, title: str, parent=None, expanded: bool = False):
super().__init__(parent)
self._expanded = expanded
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self._header = _HeaderBar(title, self)
layout.addWidget(self._header)
self._content = QWidget()
self._content.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
self._content_layout = QVBoxLayout(self._content)
self._content_layout.setContentsMargins(8, 6, 8, 6)
self._content_layout.setSpacing(6)
layout.addWidget(self._content)
self._animation = QPropertyAnimation(self, b"content_height")
self._animation.setDuration(200)
self._animation.setEasingCurve(QEasingCurve.Type.InOutQuad)
if not expanded:
self._content.setMaximumHeight(0)
self._header.expanded = False
@property
def content_layout(self) -> QVBoxLayout:
return self._content_layout
def add_widget(self, widget: QWidget):
self._content_layout.addWidget(widget)
def add_layout(self, layout):
self._content_layout.addLayout(layout)
def _get_content_height(self) -> int:
return self._content.maximumHeight()
def _set_content_height(self, h: int):
self._content.setMaximumHeight(h)
content_height = Property(int, _get_content_height, _set_content_height)
def toggle(self):
self._expanded = not self._expanded
self._header.expanded = self._expanded
target_height = self._content.sizeHint().height() if self._expanded else 0
self._animation.stop()
self._animation.setStartValue(self._content.maximumHeight())
self._animation.setEndValue(target_height)
if self._expanded:
self._animation.finished.connect(self._unlock_height)
self._animation.start()
def _unlock_height(self):
"""Remove height cap after expansion so content can resize freely."""
if self._expanded:
self._content.setMaximumHeight(16777215)
try:
self._animation.finished.disconnect(self._unlock_height)
except TypeError:
pass
def is_expanded(self) -> bool:
return self._expanded
@@ -0,0 +1,798 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""HSV color wheel widget with Fast and Professional modes.
Fast mode provides a two-point color remapping interface: the user clicks to
select a source color region, then drags to a destination. The shift is
propagated across the internal polar grid with linear falloff and sent as a
CLUT to the camera.
Professional mode overlays a polar grid of draggable control points for
per-region color grading adjustments.
"""
import copy
import math
from PySide6.QtCore import Qt, Signal, QPointF, QRectF
from PySide6.QtWidgets import QWidget
from PySide6.QtGui import (
QPainter, QColor, QImage, QPen, QBrush,
QConicalGradient, QRadialGradient, QPixmap,
)
from ..theme import COLOR_BG_PANEL, COLOR_ACCENT
from yolocam.clut import (
HUE_SECTORS, SAT_COLUMNS, FULL_R_VALUE, INTERVAL_THETA, INTERVAL_R_NORM,
init_fast_grid, init_luma_grid, calc_rows_data,
)
_TWO_PI = 2.0 * math.pi
_SAT_RINGS = SAT_COLUMNS
_HUE_STEP_DEG = INTERVAL_THETA
_GRID_POINT_RADIUS = 3.5
_GRID_HIT_RADIUS = 8.0
_GRID_LINE_COLOR = QColor(255, 255, 255, 64)
_ACCENT_COLOR = QColor(COLOR_ACCENT)
_HOME_LINE_COLOR = QColor(255, 255, 255, 40)
_SOURCE_COLOR = QColor(255, 0, 67, 200)
_DEST_COLOR = QColor(255, 255, 255, 200)
_ARROW_COLOR = QColor(255, 255, 255, 160)
def _polar_to_xy(center_x, center_y, radius, angle_rad):
"""Convert polar coordinates to pixel position (math convention, y-up)."""
return (
center_x + radius * math.cos(angle_rad),
center_y - radius * math.sin(angle_rad),
)
def _xy_to_polar(cx, cy, px, py):
"""Convert pixel position to (angle_rad, distance) from center."""
dx = px - cx
dy = py - cy
dist = math.sqrt(dx * dx + dy * dy)
angle = math.atan2(-dy, dx)
if angle < 0:
angle += _TWO_PI
return angle, dist
class ColorWheel(QWidget):
"""Circular HSV color wheel with click/drag selection.
Supports two modes:
- "fast" (default): two-point color remapping via CLUT
- "professional": polar grid of draggable control points for
per-region color grading
Hue maps to angle around the circumference, saturation maps to
distance from center. Brightness (value) is controlled externally.
"""
hue_changed = Signal(int)
saturation_changed = Signal(int)
brightness_changed = Signal(int)
color_changed = Signal(int, int, int)
grid_changed = Signal(object)
WHEEL_SIZE = 280
INDICATOR_RADIUS = 6
def __init__(self, parent=None):
super().__init__(parent)
self._hue = 0
self._saturation = 0
self._brightness = 100
self._dragging = False
self._mode = "fast"
self._wheel_pixmap = None
self._wheel_center = QPointF(self.WHEEL_SIZE / 2.0, self.WHEEL_SIZE / 2.0)
self._wheel_radius = self.WHEEL_SIZE / 2.0 - 2.0
# Professional mode state: displacement (dx, dy) per grid point
self._grid_disp = [[(0.0, 0.0) for _ in range(_SAT_RINGS)] for _ in range(HUE_SECTORS)]
self._grid_drag_idx = None
self._grid_hover_idx = None
# Fast mode state
self._fast_grid = init_fast_grid()
self._fast_luma = init_luma_grid()
self._fast_drags = [] # persistent drag ops: [{"line","col","dest_theta","dest_r"}, ...]
self._fast_active_idx = None # index of drag being edited, or None
self._fast_new_source = None # (line, col) for new drag being created
self._fast_dest_px = None # pixel coords during drag
self._fast_hover_idx = None # index of hovered drag source, or None
self.setFixedSize(self.WHEEL_SIZE, self.WHEEL_SIZE)
self.setMouseTracking(True)
self._rebuild_wheel()
# -- Public API --
def hue(self) -> int:
return self._hue
def saturation(self) -> int:
return self._saturation
def brightness(self) -> int:
return self._brightness
def set_hue(self, value: int):
value = max(0, min(360, value))
if self._hue == value:
return
self._hue = value
self.update()
def set_saturation(self, value: int):
value = max(0, min(100, value))
if self._saturation == value:
return
self._saturation = value
self.update()
def set_brightness(self, value: int):
value = max(0, min(100, value))
if self._brightness == value:
return
self._brightness = value
self.brightness_changed.emit(self._brightness)
self.color_changed.emit(self._hue, self._saturation, self._brightness)
self.update()
def mode(self) -> str:
return self._mode
def set_mode(self, mode: str):
if mode not in ("fast", "professional"):
return
if self._mode == mode:
return
old_mode = self._mode
self._mode = mode
self._grid_drag_idx = None
self._grid_hover_idx = None
self._fast_active_idx = None
self._fast_new_source = None
self._fast_dest_px = None
self._dragging = False
if old_mode == "fast" and mode == "professional":
self._sync_fast_to_professional()
self.grid_changed.emit(self.grid_data())
self.update()
def grid_data(self) -> dict:
"""Return the current grid displacement state as HSV adjustment dicts.
Format: {"hue": 25x12, "sat": 25x12, "luma": 25x12}
Row 24 wraps to row 0 for interpolation continuity.
"""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
hue_grid = []
sat_grid = []
luma_grid = []
for h in range(HUE_SECTORS + 1):
h_idx = h % HUE_SECTORS
hue_row = []
sat_row = []
luma_row = []
for s in range(_SAT_RINGS):
dx, dy = self._grid_disp[h_idx][s]
hx, hy = self._grid_home_pos(h_idx, s)
if abs(dx) < 0.01 and abs(dy) < 0.01:
hue_row.append(0.0)
sat_row.append(0.0)
else:
home_angle, home_dist = _xy_to_polar(cx, cy, hx, hy)
cur_angle, cur_dist = _xy_to_polar(cx, cy, hx + dx, hy + dy)
angle_delta = math.degrees(cur_angle - home_angle)
if angle_delta > 180:
angle_delta -= 360
if angle_delta < -180:
angle_delta += 360
sat_delta = ((cur_dist - home_dist) / self._wheel_radius) * 100.0
hue_row.append(round(angle_delta, 2))
sat_row.append(round(sat_delta, 2))
luma_row.append(0.0)
hue_grid.append(hue_row)
sat_grid.append(sat_row)
luma_grid.append(luma_row)
return {"hue": hue_grid, "sat": sat_grid, "luma": luma_grid}
def fast_grid_data(self) -> dict:
"""Return the Fast mode grid state for CLUT computation."""
return {
"mode": "fast",
"grid": copy.deepcopy(self._fast_grid),
"luma": copy.deepcopy(self._fast_luma),
}
def set_grid_data(self, data: dict):
"""Load grid state from a dict (inverse of grid_data)."""
hue_grid = data.get("hue", [])
sat_grid = data.get("sat", [])
cx = self._wheel_center.x()
cy = self._wheel_center.y()
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
hue_delta = 0.0
sat_delta = 0.0
if h < len(hue_grid) and s < len(hue_grid[h]):
hue_delta = hue_grid[h][s]
if h < len(sat_grid) and s < len(sat_grid[h]):
sat_delta = sat_grid[h][s]
if abs(hue_delta) < 0.01 and abs(sat_delta) < 0.01:
self._grid_disp[h][s] = (0.0, 0.0)
continue
hx, hy = self._grid_home_pos(h, s)
home_angle, home_dist = _xy_to_polar(cx, cy, hx, hy)
new_angle = home_angle + math.radians(hue_delta)
new_dist = home_dist + (sat_delta / 100.0) * self._wheel_radius
new_dist = max(0, min(self._wheel_radius, new_dist))
nx, ny = _polar_to_xy(cx, cy, new_dist, new_angle)
self._grid_disp[h][s] = (nx - hx, ny - hy)
self.update()
def reset_grid(self):
"""Reset all grid points to home positions (both modes)."""
self._grid_disp = [[(0.0, 0.0) for _ in range(_SAT_RINGS)] for _ in range(HUE_SECTORS)]
self._grid_drag_idx = None
self._fast_grid = init_fast_grid()
self._fast_luma = init_luma_grid()
self._fast_drags = []
self._fast_active_idx = None
self._fast_new_source = None
self._fast_dest_px = None
if self._mode == "fast":
self.grid_changed.emit(self.fast_grid_data())
else:
self.grid_changed.emit(self.grid_data())
self.update()
# -- Painting --
def _rebuild_wheel(self):
"""Pre-render the HSV wheel as a QPixmap.
Always renders at full brightness so the color spectrum is visible regardless
of the camera's brightness parameter value.
"""
size = self.WHEEL_SIZE
pixmap = QPixmap(size, size)
pixmap.fill(Qt.GlobalColor.transparent)
p = QPainter(pixmap)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
cx = size / 2.0
cy = size / 2.0
radius = self._wheel_radius
hue_gradient = QConicalGradient(cx, cy, 0)
num_stops = 12
for i in range(num_stops + 1):
frac = i / num_stops
hue_val = frac * 360.0
if hue_val >= 360.0:
hue_val = 0.0
color = QColor.fromHsvF(hue_val / 360.0, 1.0, 1.0)
hue_gradient.setColorAt(frac, color)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QBrush(hue_gradient))
p.drawEllipse(QPointF(cx, cy), radius, radius)
sat_gradient = QRadialGradient(cx, cy, radius)
center_color = QColor(255, 255, 255, 255)
edge_color = QColor(255, 255, 255, 0)
sat_gradient.setColorAt(0.0, center_color)
sat_gradient.setColorAt(1.0, edge_color)
p.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceOver)
p.setBrush(QBrush(sat_gradient))
p.drawEllipse(QPointF(cx, cy), radius, radius)
p.end()
self._wheel_pixmap = pixmap
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(QColor(COLOR_BG_PANEL))
p.drawEllipse(self._wheel_center, self._wheel_radius + 2, self._wheel_radius + 2)
if self._wheel_pixmap:
p.drawPixmap(0, 0, self._wheel_pixmap)
if self._mode == "fast":
self._paint_fast_mode(p)
else:
self._paint_grid(p)
p.end()
def _paint_fast_mode(self, p: QPainter):
"""Draw Fast mode persistent drag arrows and active drag."""
half = 5.0
for i, drag in enumerate(self._fast_drags):
sx, sy = self._grid_pos_to_pixel(drag["line"], drag["col"])
dx, dy = self._polar_norm_to_pixel(drag["dest_theta"], drag["dest_r"])
active = (i == self._fast_active_idx)
hovered = (i == self._fast_hover_idx) and not self._dragging
alpha = 220 if (active or hovered) else 140
src_half = half + 2.0 if hovered else half
p.setPen(QPen(QColor(255, 0, 67, alpha), 2.5 if hovered else 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRect(QRectF(sx - src_half, sy - src_half, src_half * 2, src_half * 2))
p.setPen(QPen(QColor(255, 255, 255, alpha), 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawEllipse(QPointF(dx, dy), self.INDICATOR_RADIUS, self.INDICATOR_RADIUS)
self._paint_arrow(p, sx, sy, dx, dy, alpha)
if self._fast_dest_px is not None:
source = self._fast_new_source
if self._fast_active_idx is not None and self._fast_active_idx < len(self._fast_drags):
d = self._fast_drags[self._fast_active_idx]
source = (d["line"], d["col"])
if source is not None:
sx, sy = self._grid_pos_to_pixel(*source)
dx, dy = self._fast_dest_px
p.setPen(QPen(_SOURCE_COLOR, 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRect(QRectF(sx - half, sy - half, half * 2, half * 2))
p.setPen(QPen(_DEST_COLOR, 2.0))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawEllipse(QPointF(dx, dy), self.INDICATOR_RADIUS, self.INDICATOR_RADIUS)
self._paint_arrow(p, sx, sy, dx, dy)
def _paint_arrow(self, p: QPainter, x1, y1, x2, y2, alpha=160):
"""Draw an arrow from (x1,y1) to (x2,y2)."""
dx = x2 - x1
dy = y2 - y1
length = math.sqrt(dx * dx + dy * dy)
if length < 5:
return
p.setPen(QPen(QColor(255, 255, 255, alpha), 1.5))
# Shaft
p.drawLine(QPointF(x1, y1), QPointF(x2, y2))
# Arrowhead
angle = math.atan2(dy, dx)
head_len = 8.0
spread = math.pi / 6.0
p.drawLine(
QPointF(x2, y2),
QPointF(x2 - head_len * math.cos(angle - spread), y2 - head_len * math.sin(angle - spread)),
)
p.drawLine(
QPointF(x2, y2),
QPointF(x2 - head_len * math.cos(angle + spread), y2 - head_len * math.sin(angle + spread)),
)
def _paint_grid(self, p: QPainter):
"""Draw the polar grid mesh and control points over the wheel."""
grid_pen = QPen(_GRID_LINE_COLOR, 0.75)
p.setPen(grid_pen)
p.setBrush(Qt.BrushStyle.NoBrush)
for s in range(_SAT_RINGS):
points = []
for h in range(HUE_SECTORS):
hx, hy = self._grid_home_pos(h, s)
dx, dy = self._grid_disp[h][s]
points.append(QPointF(hx + dx, hy + dy))
for i in range(HUE_SECTORS):
next_i = (i + 1) % HUE_SECTORS
p.drawLine(points[i], points[next_i])
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS - 1):
hx1, hy1 = self._grid_home_pos(h, s)
dx1, dy1 = self._grid_disp[h][s]
hx2, hy2 = self._grid_home_pos(h, s + 1)
dx2, dy2 = self._grid_disp[h][s + 1]
p.drawLine(QPointF(hx1 + dx1, hy1 + dy1), QPointF(hx2 + dx2, hy2 + dy2))
home_pen = QPen(_HOME_LINE_COLOR, 0.5, Qt.PenStyle.DotLine)
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
dx, dy = self._grid_disp[h][s]
if abs(dx) < 0.5 and abs(dy) < 0.5:
continue
hx, hy = self._grid_home_pos(h, s)
p.setPen(home_pen)
p.drawLine(QPointF(hx, hy), QPointF(hx + dx, hy + dy))
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
hx, hy = self._grid_home_pos(h, s)
dx, dy = self._grid_disp[h][s]
px, py = hx + dx, hy + dy
displaced = abs(dx) > 0.5 or abs(dy) > 0.5
hovered = self._grid_hover_idx == (h, s)
r = _GRID_POINT_RADIUS + (1.0 if hovered else 0.0)
if displaced:
p.setPen(QPen(QColor(40, 40, 40), 1.0))
p.setBrush(QBrush(_ACCENT_COLOR))
elif hovered:
p.setPen(QPen(QColor(40, 40, 40), 1.0))
p.setBrush(QBrush(QColor(255, 255, 255)))
else:
p.setPen(QPen(QColor(60, 60, 60), 0.75))
p.setBrush(QBrush(QColor(255, 255, 255, 200)))
p.drawEllipse(QPointF(px, py), r, r)
def _grid_home_pos(self, h_idx: int, s_idx: int) -> tuple:
"""Compute the undisplaced pixel position for grid point (h_idx, s_idx).
s_idx 0 is nearest center, s_idx (_SAT_RINGS-1) is at wheel edge.
"""
angle_rad = (h_idx / HUE_SECTORS) * _TWO_PI
frac = (s_idx + 1) / _SAT_RINGS
dist = frac * self._wheel_radius
return _polar_to_xy(self._wheel_center.x(), self._wheel_center.y(), dist, angle_rad)
def _grid_pos_to_pixel(self, line_num: int, col_num: int) -> tuple:
"""Convert a Fast mode grid position to pixel coordinates.
Uses the mathematical grid positions (same coordinate system as the algo).
col_num 0 is center, col_num 11 is outermost.
"""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
theta_deg = line_num * INTERVAL_THETA
r_norm = col_num * INTERVAL_R_NORM
pixel_r = r_norm / FULL_R_VALUE * self._wheel_radius
angle_rad = math.radians(theta_deg)
return (cx + pixel_r * math.cos(angle_rad), cy - pixel_r * math.sin(angle_rad))
def _polar_norm_to_pixel(self, theta_deg: float, r_norm: float) -> tuple:
"""Convert absolute polar coordinates to pixel position."""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
pixel_r = r_norm / FULL_R_VALUE * self._wheel_radius
angle_rad = math.radians(theta_deg)
return (cx + pixel_r * math.cos(angle_rad), cy - pixel_r * math.sin(angle_rad))
def _pixel_to_polar_norm(self, px: float, py: float) -> tuple:
"""Convert pixel position to (theta_degrees, r_normalized)."""
cx = self._wheel_center.x()
cy = self._wheel_center.y()
dx = px - cx
dy = cy - py
r_pixels = math.sqrt(dx * dx + dy * dy)
theta_deg = math.degrees(math.atan2(dy, dx))
if theta_deg < 0:
theta_deg += 360.0
r_norm = r_pixels / self._wheel_radius * FULL_R_VALUE
return theta_deg, r_norm
def _find_nearest_fast_point(self, px: float, py: float) -> tuple:
"""Find the nearest Fast grid point to a pixel position.
Returns (line_num, col_num). Skips center column (col 0).
"""
theta_deg, r_norm = self._pixel_to_polar_norm(px, py)
line = round(theta_deg / INTERVAL_THETA) % HUE_SECTORS
col = round(r_norm / INTERVAL_R_NORM)
col = max(1, min(SAT_COLUMNS - 1, col))
return line, col
def _find_nearest_drag_source(self, px: float, py: float):
"""Find the index of the nearest committed drag source within hit radius, or None."""
best_idx = None
best_dist = _GRID_HIT_RADIUS * 1.5
for i, drag in enumerate(self._fast_drags):
sx, sy = self._grid_pos_to_pixel(drag["line"], drag["col"])
d = math.sqrt((px - sx) ** 2 + (py - sy) ** 2)
if d < best_dist:
best_dist = d
best_idx = i
return best_idx
def _rebuild_fast_grid(self):
"""Recompute fast grid from scratch by replaying all committed drags."""
self._fast_grid = init_fast_grid()
self._fast_luma = init_luma_grid()
for drag in self._fast_drags:
calc_rows_data(
drag["line"], drag["col"],
drag["dest_theta"], drag["dest_r"],
self._fast_grid,
)
def _sync_fast_to_professional(self):
"""Update professional grid displacements to reflect fast grid changes."""
identity = init_fast_grid()
cx = self._wheel_center.x()
cy = self._wheel_center.y()
for h in range(HUE_SECTORS):
for s in range(SAT_COLUMNS):
id_theta, id_r = identity[h][s]
cur_theta, cur_r = self._fast_grid[h][s]
theta_delta = cur_theta - id_theta
if theta_delta > 180:
theta_delta -= 360
if theta_delta < -180:
theta_delta += 360
r_delta = cur_r - id_r
if abs(theta_delta) < 0.01 and abs(r_delta) < 0.001:
self._grid_disp[h][s] = (0.0, 0.0)
continue
hx, hy = self._grid_home_pos(h, s)
home_angle, home_dist = _xy_to_polar(cx, cy, hx, hy)
new_angle = home_angle + math.radians(theta_delta)
r_delta_px = (r_delta / FULL_R_VALUE) * self._wheel_radius
new_dist = max(0, min(self._wheel_radius, home_dist + r_delta_px))
nx, ny = _polar_to_xy(cx, cy, new_dist, new_angle)
self._grid_disp[h][s] = (nx - hx, ny - hy)
def _indicator_pos(self) -> tuple:
"""Compute pixel position of the current hue/saturation indicator."""
angle_rad = (self._hue / 360.0) * _TWO_PI
dist = (self._saturation / 100.0) * self._wheel_radius
x = self._wheel_center.x() + dist * math.cos(angle_rad)
y = self._wheel_center.y() - dist * math.sin(angle_rad)
return x, y
# -- Mouse interaction --
def mousePressEvent(self, event):
if self._mode == "fast":
pos = event.position()
if event.button() == Qt.MouseButton.LeftButton:
idx = self._find_nearest_drag_source(pos.x(), pos.y())
if idx is not None:
self._fast_active_idx = idx
self._fast_new_source = None
else:
line, col = self._find_nearest_fast_point(pos.x(), pos.y())
self._fast_new_source = (line, col)
self._fast_active_idx = None
self._fast_dest_px = None
self._fast_hover_idx = None
self._dragging = True
self.setCursor(Qt.CursorShape.ClosedHandCursor)
self.update()
elif event.button() == Qt.MouseButton.RightButton:
idx = self._find_nearest_drag_source(pos.x(), pos.y())
if idx is not None:
del self._fast_drags[idx]
self._rebuild_fast_grid()
self.grid_changed.emit(self.fast_grid_data())
self.update()
return
pos = event.position()
if event.button() == Qt.MouseButton.RightButton:
hit = self._hit_test_grid(pos)
if hit is not None:
self._grid_disp[hit[0]][hit[1]] = (0.0, 0.0)
else:
self.reset_grid()
return
self.grid_changed.emit(self.grid_data())
self.update()
return
if event.button() == Qt.MouseButton.LeftButton:
hit = self._hit_test_grid(pos)
if hit is not None:
self._grid_drag_idx = hit
self._dragging = True
def mouseMoveEvent(self, event):
pos = event.position()
if self._mode == "fast":
if self._dragging and (self._fast_new_source is not None or self._fast_active_idx is not None):
cx = self._wheel_center.x()
cy = self._wheel_center.y()
dx = pos.x() - cx
dy = pos.y() - cy
dist = math.sqrt(dx * dx + dy * dy)
if dist > self._wheel_radius:
scale = self._wheel_radius / dist
px = cx + dx * scale
py = cy + dy * scale
else:
px, py = pos.x(), pos.y()
self._fast_dest_px = (px, py)
self.update()
else:
hover = self._find_nearest_drag_source(pos.x(), pos.y())
if hover != self._fast_hover_idx:
self._fast_hover_idx = hover
self.setCursor(
Qt.CursorShape.OpenHandCursor if hover is not None
else Qt.CursorShape.CrossCursor
)
self.update()
return
if self._dragging and self._grid_drag_idx is not None:
self._drag_grid_point(pos)
return
hit = self._hit_test_grid(pos)
if hit != self._grid_hover_idx:
self._grid_hover_idx = hit
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
if self._mode == "fast" and self._fast_dest_px is not None:
dest_theta, dest_r = self._pixel_to_polar_norm(*self._fast_dest_px)
if self._fast_active_idx is not None and self._fast_active_idx < len(self._fast_drags):
d = self._fast_drags[self._fast_active_idx]
d["dest_theta"] = dest_theta
d["dest_r"] = dest_r
elif self._fast_new_source is not None:
line, col = self._fast_new_source
self._fast_drags.append({
"line": line, "col": col,
"dest_theta": dest_theta, "dest_r": dest_r,
})
self._rebuild_fast_grid()
self._fast_active_idx = None
self._fast_new_source = None
self._fast_dest_px = None
self.grid_changed.emit(self.fast_grid_data())
self.update()
elif self._mode == "professional" and self._grid_drag_idx is not None:
self.grid_changed.emit(self.grid_data())
self._dragging = False
self._grid_drag_idx = None
self.setCursor(Qt.CursorShape.CrossCursor)
def _hit_test_grid(self, pos: QPointF):
"""Find the nearest grid point within hit radius, or None."""
px, py = pos.x(), pos.y()
best = None
best_dist = _GRID_HIT_RADIUS
for h in range(HUE_SECTORS):
for s in range(_SAT_RINGS):
hx, hy = self._grid_home_pos(h, s)
dx, dy = self._grid_disp[h][s]
gx, gy = hx + dx, hy + dy
d = math.sqrt((px - gx) ** 2 + (py - gy) ** 2)
if d < best_dist:
best_dist = d
best = (h, s)
return best
def _drag_grid_point(self, pos: QPointF):
"""Update the displacement of the currently dragged grid point."""
h, s = self._grid_drag_idx
hx, hy = self._grid_home_pos(h, s)
px, py = pos.x(), pos.y()
cx = self._wheel_center.x()
cy = self._wheel_center.y()
dx = px - cx
dy = py - cy
dist = math.sqrt(dx * dx + dy * dy)
if dist > self._wheel_radius:
scale = self._wheel_radius / dist
px = cx + dx * scale
py = cy + dy * scale
self._grid_disp[h][s] = (px - hx, py - hy)
self.update()
@@ -0,0 +1,140 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Parameter slider widget with label, slider, and spinbox."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QHBoxLayout, QLabel, QSlider, QSpinBox, QDoubleSpinBox, QSizePolicy,
)
class ParamSlider(QWidget):
"""Row layout with label, slider, and spinbox for adjusting a parameter."""
value_changed = Signal(float)
def __init__(self, label: str, min_val: float = 0, max_val: float = 100,
default: float = 50, step: float = 1, decimals: int = 0,
suffix: str = "", parent=None):
super().__init__(parent)
self._min = min_val
self._max = max_val
self._step = step
self._decimals = decimals
self._block_signals = False
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 2, 0, 2)
layout.setSpacing(8)
self._label = QLabel(label)
self._label.setFixedWidth(110)
self._label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
layout.addWidget(self._label)
self._slider = QSlider(Qt.Orientation.Horizontal)
self._slider.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
if decimals > 0:
self._scale = 10 ** decimals
self._slider.setMinimum(int(min_val * self._scale))
self._slider.setMaximum(int(max_val * self._scale))
self._slider.setSingleStep(int(step * self._scale))
self._slider.setValue(int(default * self._scale))
self._spin = QDoubleSpinBox()
self._spin.setDecimals(decimals)
self._spin.setMinimum(min_val)
self._spin.setMaximum(max_val)
self._spin.setSingleStep(step)
self._spin.setValue(default)
if suffix:
self._spin.setSuffix(suffix)
self._slider.valueChanged.connect(self._slider_moved_float)
self._spin.valueChanged.connect(self._spin_changed_float)
else:
self._scale = 1
self._slider.setMinimum(int(min_val))
self._slider.setMaximum(int(max_val))
self._slider.setSingleStep(int(step))
self._slider.setValue(int(default))
self._spin = QSpinBox()
self._spin.setMinimum(int(min_val))
self._spin.setMaximum(int(max_val))
self._spin.setSingleStep(int(step))
self._spin.setValue(int(default))
if suffix:
self._spin.setSuffix(suffix)
self._slider.valueChanged.connect(self._slider_moved_int)
self._spin.valueChanged.connect(self._spin_changed_int)
layout.addWidget(self._slider, 1)
self._spin.setFixedWidth(70)
self._spin.setAlignment(Qt.AlignmentFlag.AlignRight)
layout.addWidget(self._spin)
def _slider_moved_int(self, val: int):
if self._block_signals:
return
self._block_signals = True
self._spin.setValue(val)
self._block_signals = False
self.value_changed.emit(float(val))
def _spin_changed_int(self, val: int):
if self._block_signals:
return
self._block_signals = True
self._slider.setValue(val)
self._block_signals = False
self.value_changed.emit(float(val))
def _slider_moved_float(self, val: int):
if self._block_signals:
return
fval = val / self._scale
self._block_signals = True
self._spin.setValue(fval)
self._block_signals = False
self.value_changed.emit(fval)
def _spin_changed_float(self, val: float):
if self._block_signals:
return
self._block_signals = True
self._slider.setValue(int(val * self._scale))
self._block_signals = False
self.value_changed.emit(val)
def value(self) -> float:
if self._decimals > 0:
return self._spin.value()
return float(self._spin.value())
def set_value(self, val: float, emit: bool = True):
self._block_signals = True
if self._decimals > 0:
self._spin.setValue(val)
self._slider.setValue(int(val * self._scale))
else:
self._spin.setValue(int(val))
self._slider.setValue(int(val))
self._block_signals = False
if emit:
self.value_changed.emit(val)
def set_enabled(self, enabled: bool):
self._slider.setEnabled(enabled)
self._spin.setEnabled(enabled)
@@ -0,0 +1,109 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Preset bar for quick scene switching."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
QWidget, QHBoxLayout, QPushButton, QSizePolicy, QMenu, QInputDialog,
)
from ..theme import COLOR_ACCENT, COLOR_BG_INPUT, COLOR_BORDER, COLOR_TEXT_PRIMARY, COLOR_TEXT_SECONDARY
class PresetBar(QWidget):
"""Horizontal bar with preset buttons and an add button."""
preset_selected = Signal(str)
save_requested = Signal()
preset_deleted = Signal(str)
preset_renamed = Signal(str, str)
def __init__(self, parent=None):
super().__init__(parent)
self._presets: list[str] = []
self._active: str | None = None
self._buttons: dict[str, QPushButton] = {}
self._layout = QHBoxLayout(self)
self._layout.setContentsMargins(0, 4, 0, 4)
self._layout.setSpacing(4)
self._add_btn = QPushButton("+")
self._add_btn.setFixedSize(28, 28)
self._add_btn.setCursor(Qt.CursorShape.PointingHandCursor)
self._add_btn.setToolTip("Save new preset")
self._add_btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_BG_INPUT}; color: {COLOR_TEXT_SECONDARY};
border: 1px solid {COLOR_BORDER}; border-radius: 4px; font-size: 16px; font-weight: bold; }}
QPushButton:hover {{ color: {COLOR_TEXT_PRIMARY}; border-color: {COLOR_ACCENT}; }}
""")
self._add_btn.clicked.connect(self.save_requested.emit)
self._layout.addStretch()
self._layout.addWidget(self._add_btn)
def set_presets(self, names: list[str], active: str | None = None):
for btn in self._buttons.values():
self._layout.removeWidget(btn)
btn.deleteLater()
self._buttons.clear()
self._presets = list(names)
self._active = active
insert_pos = 0
for name in names:
btn = self._make_button(name)
self._layout.insertWidget(insert_pos, btn)
self._buttons[name] = btn
insert_pos += 1
self._apply_styles()
def _make_button(self, name: str) -> QPushButton:
btn = QPushButton(name)
btn.setFixedHeight(28)
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
btn.clicked.connect(lambda: self._select(name))
btn.customContextMenuRequested.connect(lambda pos, n=name: self._context_menu(n, pos))
return btn
def _select(self, name: str):
self._active = name
self._apply_styles()
self.preset_selected.emit(name)
def _context_menu(self, name: str, pos):
menu = QMenu(self)
rename_action = menu.addAction("Rename")
delete_action = menu.addAction("Delete")
action = menu.exec(self._buttons[name].mapToGlobal(pos))
if action == rename_action:
new_name, ok = QInputDialog.getText(self, "Rename Preset", "New name:", text=name)
if ok and new_name and new_name != name:
self.preset_renamed.emit(name, new_name)
elif action == delete_action:
self.preset_deleted.emit(name)
def _apply_styles(self):
for name, btn in self._buttons.items():
active = (name == self._active)
if active:
btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_ACCENT}; color: {COLOR_TEXT_PRIMARY};
border: none; border-radius: 4px; font-weight: bold; padding: 2px 10px; }}
""")
else:
btn.setStyleSheet(f"""
QPushButton {{ background-color: {COLOR_BG_INPUT}; color: {COLOR_TEXT_SECONDARY};
border: 1px solid {COLOR_BORDER}; border-radius: 4px; padding: 2px 10px; }}
QPushButton:hover {{ color: {COLOR_TEXT_PRIMARY}; border-color: {COLOR_ACCENT}; }}
""")
@@ -0,0 +1,126 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""Segmented button control for mutually exclusive options."""
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QWidget, QHBoxLayout, QPushButton, QSizePolicy
from PySide6.QtGui import QFont
from ..theme import COLOR_ACCENT, COLOR_BG_INPUT, COLOR_BORDER, COLOR_TEXT_PRIMARY, COLOR_TEXT_SECONDARY
class SegmentButton(QWidget):
"""Row of exclusive buttons styled as a segmented control."""
selection_changed = Signal(int)
selection_changed_text = Signal(str)
def __init__(self, options: list[str], parent=None):
super().__init__(parent)
self._options = options
self._buttons: list[QPushButton] = []
self._selected = 0
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setStyleSheet(f"""
SegmentButton {{
background: {COLOR_BG_INPUT};
border: 1px solid {COLOR_BORDER};
border-radius: 6px;
}}
""")
for i, label in enumerate(options):
btn = QPushButton(label)
btn.setCheckable(True)
btn.setCursor(Qt.CursorShape.PointingHandCursor)
btn.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
btn.setFixedHeight(28)
btn.clicked.connect(lambda checked, idx=i: self._on_click(idx))
self._buttons.append(btn)
layout.addWidget(btn)
self._apply_styles()
def _apply_styles(self):
for i, btn in enumerate(self._buttons):
active = (i == self._selected)
radius_left = "6px" if i == 0 else "0px"
radius_right = "6px" if i == len(self._buttons) - 1 else "0px"
if active:
btn.setStyleSheet(f"""
QPushButton {{
background-color: {COLOR_ACCENT};
color: {COLOR_TEXT_PRIMARY};
border: none;
border-radius: 0px;
border-top-left-radius: {radius_left};
border-bottom-left-radius: {radius_left};
border-top-right-radius: {radius_right};
border-bottom-right-radius: {radius_right};
font-weight: bold;
font-size: 12px;
padding: 2px 8px;
}}
""")
else:
btn.setStyleSheet(f"""
QPushButton {{
background-color: transparent;
color: {COLOR_TEXT_SECONDARY};
border: none;
border-radius: 0px;
border-top-left-radius: {radius_left};
border-bottom-left-radius: {radius_left};
border-top-right-radius: {radius_right};
border-bottom-right-radius: {radius_right};
font-size: 12px;
padding: 2px 8px;
}}
QPushButton:hover {{
color: {COLOR_TEXT_PRIMARY};
background-color: rgba(255,255,255,0.05);
}}
""")
btn.setChecked(active)
def _on_click(self, index: int):
if index == self._selected:
return
self._selected = index
self._apply_styles()
self.selection_changed.emit(index)
self.selection_changed_text.emit(self._options[index])
def selected_index(self) -> int:
return self._selected
def selected_text(self) -> str:
return self._options[self._selected]
def set_selected(self, index: int, emit: bool = True):
if index < 0 or index >= len(self._options):
return
if index == self._selected:
return
self._selected = index
self._apply_styles()
if emit:
self.selection_changed.emit(index)
self.selection_changed_text.emit(self._options[index])
@@ -0,0 +1,95 @@
# Copyright (C) 2026 Seth Hillbrand
#
# 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/>.
"""iOS-style toggle switch widget."""
from PySide6.QtCore import Qt, Signal, QPropertyAnimation, QEasingCurve, Property, QRectF
from PySide6.QtWidgets import QWidget
from PySide6.QtGui import QPainter, QColor
from ..theme import COLOR_ACCENT, COLOR_TOGGLE_OFF
class ToggleSwitch(QWidget):
"""Custom painted toggle switch. Pink when on, gray when off."""
toggled = Signal(bool)
TRACK_W = 44
TRACK_H = 22
THUMB_RADIUS = 8
THUMB_MARGIN = 3
def __init__(self, checked: bool = False, parent=None):
super().__init__(parent)
self._checked = checked
self._thumb_pos = float(self.TRACK_W - self.THUMB_MARGIN - self.THUMB_RADIUS
if checked
else self.THUMB_MARGIN + self.THUMB_RADIUS)
self.setFixedSize(self.TRACK_W, self.TRACK_H)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self._anim = QPropertyAnimation(self, b"thumb_pos")
self._anim.setDuration(150)
self._anim.setEasingCurve(QEasingCurve.Type.InOutQuad)
def _get_thumb_pos(self) -> float:
return self._thumb_pos
def _set_thumb_pos(self, val: float):
self._thumb_pos = val
self.update()
thumb_pos = Property(float, _get_thumb_pos, _set_thumb_pos)
def is_checked(self) -> bool:
return self._checked
def set_checked(self, checked: bool, emit: bool = True):
if self._checked == checked:
return
self._checked = checked
target = (self.TRACK_W - self.THUMB_MARGIN - self.THUMB_RADIUS
if checked
else self.THUMB_MARGIN + self.THUMB_RADIUS)
self._anim.stop()
self._anim.setStartValue(self._thumb_pos)
self._anim.setEndValue(float(target))
self._anim.start()
if emit:
self.toggled.emit(checked)
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.set_checked(not self._checked)
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
track_color = QColor(COLOR_ACCENT) if self._checked else QColor(COLOR_TOGGLE_OFF)
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(track_color)
p.drawRoundedRect(QRectF(0, 0, self.TRACK_W, self.TRACK_H),
self.TRACK_H / 2, self.TRACK_H / 2)
p.setBrush(QColor("#ffffff"))
p.drawEllipse(QRectF(self._thumb_pos - self.THUMB_RADIUS,
(self.TRACK_H - 2 * self.THUMB_RADIUS) / 2,
2 * self.THUMB_RADIUS, 2 * self.THUMB_RADIUS))
p.end()