Commit 56baad3a by PLN (Algolia)

midiviz: the MIDI stream as a picture, not a transcript

A lens over a live MIDI control surface: position is identity, glyph class is
type, bar+hex is value, brightness is recency — zero English words on canvas.
Born watching a Novation Launch Control XL 3 in ParVagues' livecoding rig;
watches any ALSA MIDI source, three themes, optional spectrum backdrop and
Tidal HL feed, resting-state layer over an atomically-published driver state
file, branding overridable by env (MIDIVIZ_BRAND / _WORDMARK / _BRAND_SLUG /
_WAVE), headless selftest with PNG proof, GPL-3.0-or-later.
parents
__pycache__/
*.py[cod]
*.egg-info/
.pytest_cache/
build/
dist/
.venv/
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>.
# midiviz
**Live MIDI as a picture, not a transcript.**
`midimon` prints one line per event ("14:0 Control change ch0, controller 29,
value 15"). That is the right shape for a debugger and the wrong shape for a
performer: during a set nobody reads sentences, and a fader sweep emits ~400
events a second, so the words scroll past faster than an eye can land on them.
midiviz is a *lens*, not a log. Zero English words render: an event's identity
is its **position**, its type is a **glyph class**, its value is a **bar plus
two hex digits**, and its recency is **brightness**. The layout is the authored
control surface itself — rows A..F down, columns 1..8 across — so a glance
answers "which orbit did I just touch" without decoding anything. Only what the
grid cannot place (foreign CCs, notes, bend, program) falls as rain in the
right-hand gutter, which is itself the signal: *that came from somewhere else*.
It was born in ParVagues' livecoding rig, watching
a Novation **Launch Control XL 3** — but it watches any MIDI source, and its
branding is yours to change.
![midiviz, dark theme, mid-performance](screenshots/hero-branded-dark.png)
## Highlights
- **The grid is the surface.** Column *N* is orbit *N*; the picture is the
authored LCXL3 control layout (`lcxl_grid.py`), not an arbitrary CC table.
- **Mapped-but-idle is never black.** Every grid cell keeps a floor tint, so a
connected-but-untouched control never reads as a hardware fault.
- **Resting state, not just events.** MIDI is edge-triggered, so a filter
parked at zero and one parked at the top look identical once the glow fades.
If a driver publishes a state file (last-value-wins, atomically written),
midiviz paints what each control is *resting at* — three zones for the
centre-detented family filters, detent drawn.
- **Three themes**: `dark` (the cockpit), `light` (pale desktop), `sun`
(near-white, heavy ink — for playing outdoors). Colours are data; every
theme is held to the same visibility contract by the test suite.
- **Two frame rates, not a busy loop.** ~30 fps while events arrive, 5 fps two
seconds after the last one, precomputed colour LUTs, zero per-frame
allocation. Built on a machine that performs live audio.
- **Spectrum backdrop** (optional, `s`): the master bus, behind the grid.
- **Tidal HL feed** (optional, `h`): which orbits the music is actually
triggering right now, via a SuperDirt OSC mirror — the answer to "I turned
the knob and nothing happened: is the pattern silent, or is the knob not
wired?"
- **Survives everything**: unplug/replug (clean-exit-proof by design),
restarts (theme + scale persist), tiling WMs (the window's size belongs to
the WM, the type density to the window), duplicate launches (flock, exit 78
— a deliberate close is never a fault).
## The three themes
| dark — the cockpit | light — pale desktop | sun — outdoors |
|---|---|---|
| ![](screenshots/theme-dark.png) | ![](screenshots/theme-light.png) | ![](screenshots/theme-sun.png) |
## Install & run
Needs Python ≥ 3.10, [PySide6](https://pypi.org/project/PySide6/), and
`aseqdump` (Debian/Ubuntu: `sudo apt install alsa-utils`).
```sh
git clone https://github.com/PLNech/midiviz.git
cd midiviz
python3 midiviz.py
```
```sh
python3 midiviz.py -l # list MIDI ports, show what it would watch
python3 midiviz.py -p 28:0 # pin a source port
python3 midiviz.py --theme sun # near-white, for playing outdoors
python3 midiviz.py --spectro # + master-bus spectrum, behind the grid
python3 midiviz.py --selftest # 3 s of synthetic events, headless
```
Keys: `q`/`Esc` quit · `p` pause · `c` clear · `s` spectrum · `t` pin ·
`d` theme · `+`/`-` type density · `0` birth size · `w` wave · `l` lettering.
Drag the body to move, the edges and corners to resize (the type follows the
window); right-click for the menu (also in the system tray).
Tested on Linux/ALSA (Wayland and X11). Ports are resolved automatically —
a translated/virtual surface port is preferred over raw hardware ports.
## Make it yours (branding)
midiviz ships wearing **ParVagues** and changes nothing about how it works:
```sh
MIDIVIZ_BRAND="Coolnaut" \
MIDIVIZ_WORDMARK="COOLNAUT" \
MIDIVIZ_BRAND_SLUG="coolnaut" \
MIDIVIZ_WAVE=$HOME/pictures/coolnaut-wave.png \
python3 midiviz.py
```
- `MIDIVIZ_BRAND` — spoken name, menu labels
- `MIDIVIZ_WORDMARK` — the block lettering drawn over row D
- `MIDIVIZ_BRAND_SLUG` — directory under `$XDG_CONFIG_HOME` / `$XDG_RUNTIME_DIR`
for saved theme, scale, close latch and instance lock (one per brand)
- `MIDIVIZ_WAVE` — any transparent PNG, watermarked faintly behind the grid
## The wire
State has a single legitimate owner, and it is not the viewer. midiviz *reads*
two optional producers, and both are plain files — `cat` is the debugger:
| path | producer | shape |
|---|---|---|
| `~/.cache/parvagues/surface-state.json` | any driver that integrates relative encoders and owns the absolute values | 32 values, last-value-wins, monotonic `seq`, written atomically |
| `~/.cache/parvagues/eval-events.jsonl` | an editor publishing which orbits the loaded track triggers | one JSON object per line: `{"t":…, "path":…, "d":["d1",…]}` |
Missing files are fine — those layers simply stay dark. The parvagues paths are
the wire contract midiviz was born on, not branding; point your own producer at
the same paths, or run everything under your own `MIDIVIZ_BRAND_SLUG` and write
the state file there.
A reference producer for the LCXL3 (delta integration, translated CC corpus)
lives in the ParVagues rig repository and is not required to run midiviz:
on a raw LCXL3 the event grid, gutter, spectrum and themes all work standalone.
## Development
```sh
python3 -m pytest tests/ # the non-drawing contracts (no Qt needed to fail fast)
python3 midiviz.py --selftest --screenshot shots/
# real paint path, headless; PNGs per theme
```
`--selftest` is the drawing prover: it renders synthetic events through the
real parser, cycles every theme, resizes through the tiling-WM shapes and
checks the paint output — green tests on pure functions prove nothing about a
window, so this drives the window itself.
Layout, one screenful:
| file | role |
|---|---|
| `midiviz.py` | the lens: reader, widget, themes, state layer, selftest |
| `midimon.py` | the one parser (`parse_line` / `enrich` / port resolution) |
| `midistream.py` | threaded `aseqdump` reader |
| `lcxl_grid.py` | THE grid, authored once; everything derives from it |
| `oscfeed.py` | the Tidal HL feed (SuperDirt OSC mirror) |
| `ui/` | vendored brand assets: wave PNG, display font (Syne 800) |
| `packaging/` | example systemd user unit + desktop entry |
## License
GPL-3.0-or-later — see [LICENSE](LICENSE).
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""lcxl_grid — THE grid. Authored once here; everything else derives or is generated.
WHY THIS FILE EXISTS
--------------------
PLN, 2026-07-29, loading bombe_dj after the remap: "i see the hud shows d9 on A8
so didnt we migrate parvagues HUD to new convention? why 2 sources of truth tbh"
It was three. The mapping from a MIDI CC to a physical control, and from a
physical control to the orbit that owns it, was hardcoded independently in:
tools/surface-columns.py GRID: cc -> (column, row)
tools/migrate-columns.py KNOB_A/B/C, BUTTONS, label(), slots
tools/lcxl-leds.py ROW_BASE + per-orbit binding logic
tools/pvlint/rules.py PV008's BT_CCS / BL_CCS / FAMILY_CCS
<hud>/lib/lcxl-map.js + lib/render.js TABLE + ORBIT_CONVENTION
After the 2026-07-29 remap the Python copies moved and the HUD's did not, so the
topbar showed d9 on A8 while the file and the LED board both said A1 — the
display contradicted the hardware under his hands, mid-test. That is the worst
failure mode for a glance-instrument, and it was structurally guaranteed to
happen again on the next remap.
So: this module is the only place the grid is WRITTEN. Python consumers import
it. The HUD (JavaScript, separate repo) consumes a GENERATED artifact, and a test
regenerates and compares, so editing one copy fails the suite instead of shipping.
Pattern borrowed from the fleet colour language (armada/tide-table/models.py ->
gen_tokens -> tokens.css/json): author the ontology once in Python, generate for
every other language.
THE GRID — one sentence: COLUMN N IS ORBIT N, all the way down.
col 1 2 3 4 5 6 7 8
A 13-20 d9 lvl d10 lvl d11 lvl d12 lvl d9 fx d10 fx d11 fx d12 fx
B 29-36 d1 fx d2 fx d3 fx d4 fx d5 fx d6 fx d7 fx d8 fx
C 49-56 gF1 gF2 gF3 d4 fx2 d5 fx2 d6 fx2 d7 fx2 d8 fx2
D 77-84 d1 lvl d2 lvl d3 lvl d4 lvl d5 lvl d6 lvl d7 lvl d8 lvl
E 41-44 d1 gate d2 gate d3 gate d4 gate
57-60 d5 gate d6 gate d7 gate d8 gate
F 73-76 gMute1 gMute2 gMute3 d4 gate2
89-92 d5 gate2 d6 gate2 d7 gate2 d8 gate2
Rows E and F are NON-CONTIGUOUS (41-44 then 57-60): the two halves are eight
columns of one row on the hardware, and treating them as two rows is what put
d6's second button in column 5 in the old map.
C1-C3 and F1-F3 are the FAMILY controls, not per-orbit. That is measured, not
assumed — across all 13 setlist tracks:
gF1 -> d1x13 d2x13 d3x13 d8x12 drums / core rhythm
gF2 -> d4x14 bass, almost exclusively
gF3 -> d5x12 d7x9 + d9-d12 leads / melodic / extras
Which is why d1-d3 own exactly ONE knob and ONE button each, and why an orbit
with two button gestures (bombe_dj's 3-state kick) is over budget BY DESIGN.
ROW NAME ALIASES exist because the three consumers each invented their own:
`D`/`fader`, `E`/`btn1`/`BT`, `F`/`btn2`/`BL`. Rather than force a rename across
five files and a live muscle-memory, every row carries all its names.
USAGE
python3 tools/lcxl_grid.py --check # self-consistency, prints the grid
python3 tools/lcxl_grid.py --generate # write the JSON + the HUD's JS
"""
from __future__ import annotations
import argparse
import json
import pathlib
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
JSON_OUT = ROOT / "tools" / "lcxl_grid.json"
HUD_OUT = ROOT.parent.parent / "Tools" / "pulsar-parvagues-hud" / "lib" / "lcxl-grid.generated.js"
# --------------------------------------------------------------------------
# THE AUTHORED FACTS. Everything below this block is derived.
# --------------------------------------------------------------------------
# row id -> (aliases, [(column, cc), ...])
# Segments are listed so a non-contiguous row stays ONE row of eight columns.
_ROWS: dict[str, tuple[tuple[str, ...], list[tuple[int, int]]]] = {
"A": (("A", "knobA", "top"), [(n, 12 + n) for n in range(1, 9)]),
"B": (("B", "knobB", "mid"), [(n, 28 + n) for n in range(1, 9)]),
"C": (("C", "knobC", "bot"), [(n, 48 + n) for n in range(1, 9)]),
"D": (("D", "fader"), [(n, 76 + n) for n in range(1, 9)]),
"E": (("E", "btn1", "BT"), [(n, 40 + n) for n in range(1, 5)]
+ [(n, 52 + n) for n in range(5, 9)]),
"F": (("F", "btn2", "BL"), [(n, 72 + n) for n in range(1, 5)]
+ [(n, 84 + n) for n in range(5, 9)]),
}
# Physical row order as PLN corrected it: the faders sit BETWEEN the knobs and
# the buttons. Any UI that lays the surface out vertically must use this order.
PHYSICAL_ORDER = ("A", "B", "C", "D", "E", "F")
# What each (row, column) is FOR. `orbit` means "column N belongs to orbit N";
# a literal int pins it. Roles:
# level fader/knob setting an orbit's volume (Ardour-owned, see below)
# fx an orbit's primary effect knob
# fx2 an orbit's second effect knob
# gate an orbit's primary on/off button
# gate2 an orbit's second button
# family_filter / family_mute shared across a stem family, NOT per-orbit
_ROLES: dict[str, list[tuple[int, str, object]]] = {
# d9-d12 live on row A: levels in columns 1-4, effects in columns 5-8.
"A": [(n, "level", 8 + n) for n in range(1, 5)]
+ [(n, "fx", 8 + (n - 4)) for n in range(5, 9)],
"B": [(n, "fx", "orbit") for n in range(1, 9)],
"C": [(1, "family_filter", 1), (2, "family_filter", 2), (3, "family_filter", 3)]
+ [(n, "fx2", "orbit") for n in range(4, 9)],
"D": [(n, "level", "orbit") for n in range(1, 9)],
"E": [(n, "gate", "orbit") for n in range(1, 9)],
"F": [(1, "family_mute", 1), (2, "family_mute", 2), (3, "family_mute", 3)]
+ [(n, "gate2", "orbit") for n in range(4, 9)],
}
# Ardour MIDI-learned these to the Tidal 01-12 strip gains. Writing or seeding
# them from Tidal is the CC77-goes-to-silence footgun; a track referencing one is
# a CONFLICT, not a column question.
ARDOUR_ROWS = ("D",) # all 8 faders
ARDOUR_EXTRA = tuple(12 + n for n in range(1, 5)) # A1-A4 = d9-d12 levels
# gPanic is a global kill; never sweep or seed it.
PANIC_CC = 93
# --------------------------------------------------------------------------
# Which FAMILY an orbit belongs to. Filters and mutes group DIFFERENTLY —
# that asymmetry is deliberate, authored by PLN 2026-07-30 settling #105:
#
# "I want the kick, now on d1/fader1, to have its mute on F1 botrow button.
# I want the C1 knob to djf all percs, C2 only bass djf, C3 melodies DJF.
# however i want the mutes consistent across all all tracks:
# m1 d1 / m2 other percs / m3 all bass+melodics"
#
# So the DJ filters treat the whole rhythm section as one bloc (you sweep the
# drums together, which is the gesture), while the mutes split the kick out on
# its own button (you drop the kick alone, which is the other gesture). Both
# maps are three-wide because columns 4-8 of rows C and F are already spent as
# d4-d8's fx2/gate2 slots — see _ROLES above. There is no fourth family.
#
# Note the kick ALSO has its own per-orbit gate at E1 (^41), freed when gMask
# was retired. "Mute the kick alone" is served twice over: F1 as the family
# mute, E1 as its own gate.
_FILTER_FAMILY = {1: 1, 2: 1, 3: 1, 8: 1, # all percs -> C1
4: 2, # bass only -> C2
5: 3, 6: 3, 7: 3, 9: 3, 10: 3, 11: 3, 12: 3} # melodies -> C3
_MUTE_FAMILY = {1: 1, # the kick, alone -> F1
2: 2, 3: 2, 8: 2, # other percs -> F2
4: 3, 5: 3, 6: 3, 7: 3, 9: 3, 10: 3, 11: 3, 12: 3} # bass+mels -> F3
# Orbits past 12 (d13/d14 exist on the 14-orbit boot) are melodic/FX by
# default. A fallback, not a claim — if one of them ever becomes a drum,
# author it above rather than letting the default decide.
_FAMILY_FALLBACK = 3
def filter_family(orbit: int) -> int:
"""Which gF<N> / row-C knob this orbit's DJ filter belongs to."""
return _FILTER_FAMILY.get(orbit, _FAMILY_FALLBACK)
def mute_family(orbit: int) -> int:
"""Which gM<N> / row-F button this orbit's mute belongs to."""
return _MUTE_FAMILY.get(orbit, _FAMILY_FALLBACK)
# --------------------------------------------------------------------------
# Derived views. Import these; do not re-derive them in a consumer.
# --------------------------------------------------------------------------
CC_TO_CELL: dict[int, tuple[str, int]] = {} # cc -> (row, column)
CELL_TO_CC: dict[tuple[str, int], int] = {} # (row, column) -> cc
ROW_CCS: dict[str, list[int]] = {} # row -> ccs in column order
ALIAS_TO_ROW: dict[str, str] = {}
CC_ROLE: dict[int, tuple[str, int]] = {} # cc -> (role, orbit-or-family-n)
for _row, (_aliases, _cells) in _ROWS.items():
for _alias in _aliases:
ALIAS_TO_ROW[_alias] = _row
ROW_CCS[_row] = [cc for _c, cc in sorted(_cells)]
for _col, _cc in _cells:
CC_TO_CELL[_cc] = (_row, _col)
CELL_TO_CC[(_row, _col)] = _cc
for _row, _specs in _ROLES.items():
for _col, _role, _who in _specs:
_cc = CELL_TO_CC[(_row, _col)]
CC_ROLE[_cc] = (_role, _col if _who == "orbit" else int(_who))
ARDOUR_CCS: set[int] = {cc for r in ARDOUR_ROWS for cc in ROW_CCS[r]} | set(ARDOUR_EXTRA)
KNOB_CCS: set[int] = set(ROW_CCS["A"]) | set(ROW_CCS["B"]) | set(ROW_CCS["C"])
BUTTON_CCS: set[int] = set(ROW_CCS["E"]) | set(ROW_CCS["F"])
# ── the v3 DAW-mode surface, positionally ──────────────────────────────────
# The LCXL3 in DAW mode speaks its OWN fixed CC numbering, which is not the
# corpus's. `lcxl3-driver.py` translates it on the way through and publishes the
# result as the virtual port 'ParVagues LCXL3'. The table lived only inside the
# driver, so anything ELSE reading the board direct saw v3 numbers land in v2 cells:
# midiviz drew row C's knobs into row B, row D into nothing at all, and E5-E8
# into E1-E4 -- a coherent, confident, wrong picture, for as long as the driver
# was down (2026-09-22; the driver had in fact failed 1077 times).
#
# So the table belongs to the GRID, not to one of its readers. Verified against
# the hardware by moving one control per row and reading what arrived
# (fader1->cc5 ch16, A1->13 ch16, B1->21 ch16, C1->29 ch16, E1->37 ch1,
# F1->45 ch1).
V3_ROWS: dict[str, list[int]] = {
"A": list(range(13, 21)),
"B": list(range(21, 29)),
"C": list(range(29, 37)),
"D": list(range(5, 13)),
"E": list(range(37, 45)),
"F": list(range(45, 53)),
}
def build_v3_map() -> dict[int, int]:
"""v3 DAW CC -> v2 corpus CC, positionally, straight out of the grid.
Raises rather than guesses: a row whose hardware width disagrees with the
authored width is exactly what must not be papered over, because the result
would be a silently shifted row rather than an error.
"""
out: dict[int, int] = {}
for row, v3ccs in V3_ROWS.items():
v2ccs = ROW_CCS.get(row)
if not v2ccs:
raise KeyError(f"lcxl_grid has no row {row!r}")
if len(v2ccs) != len(v3ccs):
raise ValueError(
f"row {row} has {len(v2ccs)} v2 cells but {len(v3ccs)} v3 "
"indices -- the grid and the hardware disagree"
)
out.update(zip(v3ccs, v2ccs))
return out
V3_TO_V2: dict[int, int] = build_v3_map()
FAMILY_CCS: set[int] = {cc for cc, (role, _n) in CC_ROLE.items()
if role.startswith("family_")} | {PANIC_CC}
def label(cc: int) -> str:
"""44 -> 'E4'. The canonical short name of a physical control."""
cell = CC_TO_CELL.get(int(cc))
return f"{cell[0]}{cell[1]}" if cell else f"cc{cc}"
def label_as(cc: int, style: str) -> str:
"""Same, in a consumer's own row vocabulary — e.g. label_as(44,'BT') -> 'BT4'."""
cell = CC_TO_CELL.get(int(cc))
if not cell:
return f"cc{cc}"
row, col = cell
for alias, target in ALIAS_TO_ROW.items():
if target == row and alias.startswith(style):
return f"{alias}{col}"
return f"{row}{col}"
def slots(orbit: int, kind: str) -> list[int]:
"""The CCs `orbit` owns of one kind, most-reachable first.
kind='knob' -> its fx then fx2; kind='button' -> its gate then gate2.
Returns ONE entry for d1-d3, because C1-3 and F1-3 are the family controls.
Derived from CC_ROLE, so it cannot drift from the table above — the previous
version hardcoded `28 + orbit` / `48 + orbit` in migrate-columns.py.
"""
want = ("fx", "fx2") if kind == "knob" else ("gate", "gate2")
out = []
for role in want:
for cc, (r, who) in CC_ROLE.items():
if r == role and who == orbit and cc not in ARDOUR_CCS:
out.append(cc)
return out
def orbit_home(orbit: int) -> dict[str, int]:
"""Where an orbit lives: {'level': cc, 'fx': cc, ...}. Empty roles omitted."""
out: dict[str, int] = {}
for cc, (role, who) in CC_ROLE.items():
if who == orbit and not role.startswith("family_"):
out.setdefault(role, cc)
return out
def as_dict() -> dict:
"""The whole grid, JSON-ready. This is what non-Python consumers get."""
return {
"_generated_by": "tools/lcxl_grid.py — do not edit; run --generate",
"physical_order": list(PHYSICAL_ORDER),
"rows": {
row: {
"aliases": list(_ROWS[row][0]),
"columns": {str(col): CELL_TO_CC[(row, col)]
for _c, _cc in _ROWS[row][1]
for col in [_c]},
}
for row in PHYSICAL_ORDER
},
"cc": {
str(cc): {
"row": CC_TO_CELL[cc][0],
"column": CC_TO_CELL[cc][1],
"label": label(cc),
"role": CC_ROLE.get(cc, ("unassigned", 0))[0],
"owner": CC_ROLE.get(cc, ("unassigned", 0))[1],
"ardour_owned": cc in ARDOUR_CCS,
}
for cc in sorted(CC_TO_CELL)
},
"orbit_home": {str(o): orbit_home(o) for o in range(1, 13)},
# Filters and mutes group differently on purpose — see _FILTER_FAMILY.
# The HUD needs both to say which knob and which button own an orbit.
"orbit_family": {str(o): {"filter": filter_family(o), "mute": mute_family(o)}
for o in range(1, 13)},
"ardour_ccs": sorted(ARDOUR_CCS),
"family_ccs": sorted(FAMILY_CCS),
"panic_cc": PANIC_CC,
}
# --------------------------------------------------------------------------
# Self-check. These are invariants of the SURFACE, so a violation means the
# authored table above is wrong — not that a consumer is out of date.
# --------------------------------------------------------------------------
def problems() -> list[str]:
out = []
if len(CC_TO_CELL) != 48:
out.append(f"expected 48 controls (6 rows x 8), got {len(CC_TO_CELL)}")
if len(CELL_TO_CC) != len(CC_TO_CELL):
out.append("a CC appears in two cells, or two CCs share one cell")
for row in PHYSICAL_ORDER:
cols = sorted(c for r, c in CC_TO_CELL.values() if r == row)
if cols != list(range(1, 9)):
out.append(f"row {row} does not cover columns 1-8: {cols}")
missing = sorted(set(CC_TO_CELL) - set(CC_ROLE))
if missing:
out.append(f"controls with no role: {[label(c) for c in missing]}")
# Every orbit must have somewhere to live, or the migrator has nowhere to aim.
for o in range(1, 9):
home = orbit_home(o)
if "level" not in home or "fx" not in home or "gate" not in home:
out.append(f"d{o} is missing a level/fx/gate slot: {home}")
for o in range(9, 13):
if "level" not in orbit_home(o) or "fx" not in orbit_home(o):
out.append(f"d{o} is missing a level/fx slot")
# d1-d3 must have exactly one of each, d4-d8 two — the family-control budget.
for o in (1, 2, 3):
if len(slots(o, "knob")) != 1 or len(slots(o, "button")) != 1:
out.append(f"d{o} should own exactly one knob and one button "
f"(C{o}/F{o} are family controls)")
for o in range(4, 9):
if len(slots(o, "knob")) != 2 or len(slots(o, "button")) != 2:
out.append(f"d{o} should own two knobs and two buttons")
# A control Ardour learned must never be handed out as a Tidal effect slot.
for o in range(1, 13):
for kind in ("knob", "button"):
for cc in slots(o, kind):
if cc in ARDOUR_CCS:
out.append(f"d{o} {kind} slot {label(cc)} is Ardour-owned")
return out
def generate() -> list[pathlib.Path]:
payload = as_dict()
JSON_OUT.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n")
js = (
"'use babel';\n\n"
"// GENERATED by Sound/Tidal/tools/lcxl_grid.py — DO NOT EDIT.\n"
"// Regenerate: python3 tools/lcxl_grid.py --generate\n"
"// The grid is authored once in Python because it had drifted into three\n"
"// hardcoded copies, and the HUD's was the one that went stale: it showed\n"
"// d9 on A8 after the remap while the LED board and the .tidal files said A1.\n\n"
"export const GRID = " + json.dumps(payload, indent=2, ensure_ascii=False) + ";\n\n"
"// Convenience: orbit -> its physical home, in the row/lane shape render.js uses.\n"
"export const ORBIT_CONVENTION = Object.fromEntries(\n"
" Object.entries(GRID.orbit_home).map(([orbit, home]) => {\n"
" const cc = home.level;\n"
" const cell = GRID.cc[String(cc)];\n"
" return [Number(orbit), { row: cell.row, lane: cell.column }];\n"
" })\n"
");\n"
)
written = [JSON_OUT]
if HUD_OUT.parent.is_dir():
HUD_OUT.write_text(js)
written.append(HUD_OUT)
return written
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--check", action="store_true")
ap.add_argument("--generate", action="store_true")
a = ap.parse_args()
if not (a.check or a.generate):
a.check = True
if a.check:
print(" col 1 2 3 4 5 6 7 8")
for row in PHYSICAL_ORDER:
cells = []
for col in range(1, 9):
cc = CELL_TO_CC[(row, col)]
role, who = CC_ROLE[cc]
if role.startswith("family_"):
tag = f"{'gF' if 'filter' in role else 'gMute'}{who}"
else:
tag = f"d{who}{'' if role == 'level' else ':' + role}"
cells.append(f"{tag:>10}")
print(f" {row} {' '.join(str(c) for c in ROW_CCS[row][:1]):>3} " + "".join(cells))
errs = problems()
if errs:
print("\nPROBLEMS:")
for e in errs:
print(f" !! {e}")
return 1
print(f"\nlcxl_grid: OK — 48 controls, every row 1-8, every orbit housed.")
if a.generate:
for p in generate():
print(f" wrote {p}")
return 0
if __name__ == "__main__":
sys.exit(main())
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""midimon — a clean live MIDI monitor (aseqdump, parsed & rendered right).
`aseqdump | tr -d …` is a hack. This wraps aseqdump, parses each event, and
renders an aligned, colourised stream: note numbers → names (C4…), velocity as a
little bar, events tinted by type. Ctrl-C to stop.
python3 midimon.py # monitor aseqdump's default port
python3 midimon.py -p 28:0 # subscribe to a specific source
python3 midimon.py -l # list ports and exit
python3 midimon.py --raw # passthrough (debug)
Parsing is a pure function (`parse_line`) so it's unit-tested without ALSA.
"""
from __future__ import annotations
import argparse
import re
import subprocess
import sys
NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
# event keyword → ANSI colour
C = {"note on": "92", "note off": "90", "control": "93", "program": "96",
"pitch": "95", "channel": "94", "aftertouch": "94",
"clock": "90", "start": "92", "stop": "91", "continue": "92",
"song": "90", "sysex": "95", "active": "90", "reset": "91"}
RESET, DIM, BOLD = "\033[0m", "\033[2m", "\033[1m"
# " 28:0 Note on 0, note 60, velocity 100"
_ROW = re.compile(r"^\s*(\d+:\d+)\s+(\S.*?\S|\S)\s{2,}(.*?)\s*$")
def note_name(n: int) -> str:
return f"{NOTE_NAMES[n % 12]}{n // 12 - 1}"
def parse_line(line: str) -> dict | None:
"""aseqdump event row → {source, event, data, ch?}. None if not an event."""
m = _ROW.match(line.rstrip("\n"))
if not m:
return None
source, event, data = m.group(1), m.group(2), m.group(3)
ch = None
mc = re.match(r"^(\d+)\b", data) # first int of data is the channel
if mc:
ch = int(mc.group(1))
return {"source": source, "event": event, "data": data, "ch": ch}
def enrich(ev: dict) -> dict:
"""Add structured fields parsed from `data` (note/velocity/controller/…).
One parsing source of truth — used by the CLI renderer and the web stream.
"""
out = dict(ev)
for key, pat in (("note", r"note (\d+)"), ("velocity", r"velocity (\d+)"),
("controller", r"controller (\d+)"), ("value", r"value (-?\d+)"),
("program", r"program (\d+)")):
m = re.search(pat, ev["data"])
if m:
out[key] = int(m.group(1))
if "note" in out:
out["note_name"] = note_name(out["note"])
return out
def _color(event: str) -> str:
e = event.lower()
for kw, code in C.items():
if e.startswith(kw):
return code
return "97"
def _render_data(event: str, data: str) -> str:
"""Friendlier data: note names + a velocity bar where it applies."""
note = re.search(r"note (\d+)", data)
vel = re.search(r"velocity (\d+)", data)
out = data
if note:
n = int(note.group(1))
out = out.replace(f"note {n}", f"note {n} {DIM}({note_name(n)}){RESET}")
if vel:
v = int(vel.group(1))
bars = "▁▂▃▄▅▆▇█"
out += f" {bars[min(v, 127) * (len(bars) - 1) // 127]}"
return out
def render(ev: dict) -> str:
code = _color(ev["event"])
ch = f"ch{ev['ch']:<2}" if ev["ch"] is not None else " "
return (f"{DIM}{ev['source']:>6}{RESET} "
f"\033[{code}m{BOLD}{ev['event']:<18}{RESET} "
f"{DIM}{ch}{RESET} {_render_data(ev['event'], ev['data'])}")
def list_ports():
subprocess.run(["aseqdump", "-l"])
# What to watch, best first. `aseqdump` with no -p subscribes to NOTHING and
# prints "Waiting for data at port ..." — so midimon opened blind and PLN had to
# wire it to Midi Through by hand every time ("had to wire it to midi through
# myself", 2026-08-29). A monitor that does not monitor anything on open is a
# monitor you have to repair before you can use it.
#
# The ORDER encodes what is actually interesting:
# 1. the lcxl3-driver's translated stream — the numbers the CORPUS speaks, i.e.
# what you actually want to verify when a knob does the wrong thing.
# 2. the raw v3 DAW port — the numbers the HARDWARE speaks, for when the
# question is "is the surface even sending".
# 3. the raw v3 custom-mode port, for standalone work.
# 4. Midi Through, the old default, kept last as a catch-all.
WATCH_PREFERENCE = ("ParVagues LCXL3", "LCXL3 1 DAW", "LCXL3", "Launch Control XL",
"Midi Through")
def resolve_port() -> tuple[str | None, str]:
"""(port_id, human_label) of the most interesting source present.
Matches CLIENT *and* PORT names: python-rtmidi registers the driver's client
as 'RtMidiOut Client' and puts 'ParVagues LCXL3' on the port, so a
client-only match misses exactly the stream we most want to watch.
"""
try:
out = subprocess.run(["aseqdump", "-l"], capture_output=True,
text=True, timeout=3).stdout
except (OSError, subprocess.SubprocessError):
return None, "aseqdump unavailable"
# `aseqdump -l` prints: " 20:1 LCXL3 1 LCXL3 1 DAW In"
rows = []
for line in out.splitlines():
tok = line.split()
if tok and ":" in tok[0] and tok[0].split(":")[0].isdigit():
rows.append((tok[0], line))
for want in WATCH_PREFERENCE:
for pid, line in rows:
if want in line:
return pid, f"{pid} · {want}"
return None, "no MIDI source found"
def monitor(port: str | None, raw: bool):
label = ""
if not port:
port, label = resolve_port()
cmd = ["aseqdump"] + (["-p", port] if port else [])
where = label or (f"port {port}" if port else "NOTHING — nothing to watch")
print(f"{DIM}⚓ midimon — {where} · Ctrl-C to stop{RESET}", file=sys.stderr)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True, bufsize=1)
try:
for line in proc.stdout or []:
if raw:
sys.stdout.write(line); continue
ev = parse_line(line)
if ev:
print(render(ev), flush=True)
elif line.strip() and not line.startswith(("Source", "Waiting")):
print(f"{DIM}{line.rstrip()}{RESET}")
except KeyboardInterrupt:
pass
finally:
proc.terminate()
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("-p", "--port",
help="source port (CLIENT:PORT), e.g. 28:0. Default: the most "
"interesting source present — the lcxl3-driver's "
"translated stream if it is up, else the raw surface, "
"else Midi Through.")
ap.add_argument("-l", "--list", action="store_true", help="list ports and exit")
ap.add_argument("--raw", action="store_true", help="passthrough, no parsing")
a = ap.parse_args(argv)
if a.list:
return list_ports()
monitor(a.port, a.raw)
if __name__ == "__main__":
main()
"""midistream — fan live, parsed MIDI events out to web subscribers (SSE).
# SPDX-License-Identifier: GPL-3.0-or-later
One `aseqdump` subprocess feeds N dashboard tabs. Reuses `midimon.parse_line` +
`enrich` (one parsing source of truth). The reader runs only while someone is
watching: started on first subscribe, stopped when the last subscriber leaves —
so we don't hold a MIDI port open for nothing.
`parse_ports` is pure (tested without ALSA).
"""
from __future__ import annotations
import queue
import re
import subprocess
import threading
import midimon
_PORT = re.compile(r"^\s*(\d+:\d+)\s+(.+?)\s{2,}(.+?)\s*$")
# Which events are STATE and which are EVENTS. The distinction is the whole of
# `coalesce`: a controller's older value is worthless the moment a newer one exists, but
# a note you drop never happened. Getting this backwards would make the monitor lie
# about what was played, which is worse than making it slow.
_CONTINUOUS = ("control change", "pitchbend", "pitch bend", "aftertouch",
"channel aftertouch", "poly aftertouch", "control")
def _coalesce_key(ev: dict):
"""A key for events that supersede each other, or None if the event is discrete."""
e = (ev.get("event") or "").lower()
if not e.startswith(_CONTINUOUS):
return None
if e.startswith(("control change", "control")):
return "cc", ev.get("source"), ev.get("ch"), ev.get("controller")
return e.split()[0], ev.get("source"), ev.get("ch")
def coalesce(events: list[dict]) -> list[dict]:
"""Fold a batch: every discrete event survives, continuous ones keep only the last.
Order is preserved by overwriting in place at the first occurrence, so the monitor
still reads chronologically -- a superseded fader value is replaced where it stood,
not moved to the end.
"""
out: list[dict] = []
at: dict = {}
for ev in events:
k = _coalesce_key(ev)
if k is None:
out.append(ev)
elif k in at:
out[at[k]] = ev
else:
at[k] = len(out)
out.append(ev)
return out
def parse_ports(text: str) -> list[dict]:
"""Parse `aseqdump -l` output into [{addr, client, port}] (header skipped)."""
out = []
for line in text.splitlines():
m = _PORT.match(line)
if m and ":" in m.group(1): # header "Port Client name…" has no digits:digits
out.append({"addr": m.group(1), "client": m.group(2).strip(),
"port": m.group(3).strip()})
return out
class MidiStream:
def __init__(self):
self._lock = threading.Lock()
self._subs: set[queue.Queue] = set()
self._proc = None
self._port = None
def list_ports(self) -> list[dict]:
try:
r = subprocess.run(["aseqdump", "-l"], capture_output=True, text=True, timeout=5)
except (OSError, subprocess.SubprocessError):
return []
return parse_ports(r.stdout)
# A live monitor wants the PRESENT, not a complete history. 512 was chosen as
# "generous"; on a real surface it is a LATENCY BUDGET. PLN, 2026-08-21: "when i
# move faders up/down quickly, lags by 500ms+, almost 1s, behind ahah" — a fader
# sweep is ~400 CC/s, so a 512-deep queue is 1.3 s of backlog, and once it fills
# it STAYS full: drop-oldest keeps the buffer at capacity, so every event the
# browser renders is 512 events stale, forever. Deep buffers do not smooth a
# stream the consumer cannot keep up with; they just add a fixed delay to it.
#
# 64 bounds the backlog to ~160 ms at that rate, which is jitter absorption
# rather than a queue. The browser coalesces consecutive same-control events, so
# it now drains far faster than it fills and this should rarely be reached at all.
DEPTH = 64
def subscribe(self, port=None) -> queue.Queue:
q: queue.Queue = queue.Queue(maxsize=self.DEPTH)
with self._lock:
self._subs.add(q)
restart = self._proc is None or (port and port != self._port)
if restart:
self._start(port)
return q
def unsubscribe(self, q: queue.Queue):
with self._lock:
self._subs.discard(q)
stop = not self._subs
if stop:
self._stop()
# ── internals ───────────────────────────────────────────────────────
def _start(self, port):
self._stop()
cmd = ["aseqdump"] + (["-p", port] if port else [])
try:
self._proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True, bufsize=1)
except OSError:
self._proc = None
return
self._port = port
threading.Thread(target=self._reader, args=(self._proc,), daemon=True).start()
def _reader(self, proc):
for line in proc.stdout or []:
ev = midimon.parse_line(line)
if not ev:
continue
self._fanout(midimon.enrich(ev))
def _fanout(self, ev: dict) -> None:
"""Hand one event to every subscriber. Its own method so the drop policy is
testable without ALSA -- green tests on a parser prove nothing about the seam."""
with self._lock:
for q in self._subs:
try:
q.put_nowait(ev)
except queue.Full:
# Drop the OLDEST, not the newest. The original `except Full: pass`
# kept 512 stale events and threw away the one that had just
# happened, so a tab that stalled once showed frozen values forever
# with no error anywhere. For MIDI state the newest event IS truth.
try:
q.get_nowait()
q.put_nowait(ev)
except (queue.Empty, queue.Full):
pass
def _stop(self):
if self._proc:
try:
self._proc.terminate()
except OSError:
pass
self._proc = None
self._port = None
This source diff could not be displayed because it is too large. You can view the blob instead.
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""oscfeed — the Tidal HL feed: SuperDirt's own /play packets, snoopable.
Tidal does not talk to SuperDirt alone. `BootTidal.hs` mirrors every
`superdirtShape` packet to a second target (port `VIZ_PORT`), so anything may
listen to what the music is DOING — which orbit triggered, with which values —
without touching the audio path, the way the Pulsar editor already reads its
own highlight feed. This module is that listener for midiviz.
Two halves, both importable without Qt or ALSA:
* `decode_osc` — the smallest OSC decoder the packets need. Pure function,
unit-tested against hand-built bytes.
* `HLFeed` — a UDP daemon thread with the same shape as midiviz's `Reader`
(bounded deque, drain, close): a live monitor wants the PRESENT, not a
backlog, so the same lesson as `midistream.DEPTH` applies.
"""
from __future__ import annotations
import socket
import struct
import sys
import threading
import time
from collections import deque
# BootTidal.hs sends the mirror here. High enough to dodge everything
# scsynth/sclang grab by default, referenced by nothing else in the repo.
VIZ_PORT = 57130
# Tidal's orbits are 0-based (`orbit: 0` is d1) and the rig runs 14 of them.
MIN_ORBIT, MAX_ORBIT = 1, 14
def _skip_pad(data: bytes, i: int) -> int:
"""OSC blobs are 4-aligned; return the index past the padding."""
return i + ((4 - (i % 4)) % 4)
def _read_string(data: bytes, i: int) -> tuple[str, int]:
end = data.index(b"\0", i)
return data[i:end].decode("utf-8", "replace"), _skip_pad(data, end + 1)
def _read_blob(data: bytes, i: int) -> tuple[bytes, int]:
(n,) = struct.unpack_from(">i", data, i)
i += 4
return data[i:i + n], i + n + ((4 - ((i + n) % 4)) % 4)
def decode_osc(data: bytes) -> list[dict]:
"""One UDP datagram → the OSC messages inside it.
Tidal's Stream sends either bare messages or `#bundle`s (one timetag,
then length-prefixed elements). Returns [{"addr", "args"}] with `args`
the *named* argument pairs a /play carries: Tidal→SuperDirt arguments
are ("gain", 0.8) style name/value runs, so a flat dict is the shape
every consumer wants. Unnamed args land under "0", "1", …
"""
out: list[dict] = []
stack = [data]
while stack:
cur = stack.pop(0)
if not cur:
continue
if cur.startswith(b"#bundle"):
i = 16 # "#bundle\0" + 8-byte timetag
while i + 4 <= len(cur):
(n,) = struct.unpack_from(">i", cur, i)
i += 4
if n:
stack.append(cur[i:i + n])
i = _skip_pad(cur, i + n)
continue
try:
addr, i = _read_string(cur, 0)
tags, i = _read_string(cur, i) # ",ifs…" — the comma is part of it
args: dict = {}
slot = 0
for t in tags[1:]:
if t == "i":
(v,) = struct.unpack_from(">i", cur, i)
i += 4
elif t == "f":
(v,) = struct.unpack_from(">f", cur, i)
i += 4
elif t == "d":
(v,) = struct.unpack_from(">d", cur, i)
i += 8
elif t == "s":
v, i = _read_string(cur, i)
elif t == "b":
v, i = _read_blob(cur, i)
else:
v = None # T/F/I/N… carry no bytes
args[str(slot)] = v
slot += 1
except (ValueError, struct.error, IndexError):
continue # one bad element, not the datagram
# A /play message's named pairs are positional: ("gain", v), ("orbit", v)…
# Re-fold every ("string", value) run into a dict without losing the
# originals — the names ARE the Tidal parameter names.
named: dict = {}
k = 0
while k < len(args):
key = args.get(str(k))
if isinstance(key, str) and str(k + 1) in args:
named[key] = args[str(k + 1)]
k += 2
else:
k += 1
out.append({"addr": addr, "args": named})
return out
def play_orbit(msg: dict) -> int | None:
"""A decoded message → its 1-based orbit number, or None if not a trigger.
Tidal 1.9's superdirtShape addresses its messages `/dirt/play`, not
`/play` — captured off the wire on this rig — and a decoder that only
accepted the documentation's address silently dropped every real packet
while every synthetic test passed. Accept both spellings."""
if msg["addr"] not in ("/play", "/dirt/play"):
return None
o = msg["args"].get("orbit")
if isinstance(o, float) and o == int(o):
o = int(o)
if not isinstance(o, int) or not (0 <= o <= MAX_ORBIT):
return None
return o + 1 # Tidal 0-based → d1-based
class HLFeed:
"""UDP listener on `VIZ_PORT`; a bounded deque the GUI drains each frame.
Same contract as midiviz.Reader — start/drain/close/alive/error — so the
tick can treat the two feeds identically. A missed datagram is a missed
frame of truth, never a queue: bounded like the Reader, for the same
recorded reason.
"""
DEPTH = 512
def __init__(self, port: int = VIZ_PORT):
self.port = port
self.error: str | None = None
self.total = 0
self._q: deque[dict] = deque(maxlen=self.DEPTH)
self._lock = threading.Lock()
self._sock: socket.socket | None = None
self._stop = threading.Event()
def start(self) -> "HLFeed":
threading.Thread(target=self._run, daemon=True,
name="oscfeed").start()
return self
def _run(self) -> None:
try:
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._sock.bind(("127.0.0.1", self.port))
self._sock.settimeout(0.5)
except OSError as exc:
self.error = type(exc).__name__
return
while not self._stop.is_set():
try:
data, _ = self._sock.recvfrom(65535)
except socket.timeout:
continue
except OSError:
if not self._stop.is_set():
self.error = "recv"
break
now = time.monotonic()
# One malformed datagram must not kill the feed the way an
# uncaught exception in a daemon thread dies silently: skip it.
try:
msgs = decode_osc(data)
except (ValueError, struct.error, IndexError):
continue
first = False
for msg in msgs:
o = play_orbit(msg)
if o is None:
continue
with self._lock:
self._q.append({"orbit": o, "t": now,
"params": msg["args"]})
self.total += 1
first = self.total == 1
if first:
# One line, once: the question "is Tidal even sending?" is
# answered by the journal, not by staring at a silent grid.
print("⚓ HL feed: first trigger received (d%d)" % o,
file=sys.stderr, flush=True)
def alive(self) -> bool:
return self._sock is not None and self.error is None
def drain(self) -> list[dict]:
with self._lock:
if not self._q:
return []
out = list(self._q)
self._q.clear()
return out
def close(self) -> None:
self._stop.set()
if self._sock is not None:
try:
self._sock.close()
except OSError:
pass
self._sock = None
[Desktop Entry]
Type=Application
Name=midiviz
GenericName=MIDI lens
Comment=Live MIDI as glyph-rain — your control surface, watched
Exec=/usr/bin/python3 /PATH/TO/YOUR/CHECKOUT/midiviz.py
Icon=audio-midi
Terminal=false
Categories=AudioVideo;Audio;
StartupWMClass=midiviz
NoDisplay=false
[Unit]
Description=midiviz (MIDI lens: the control surface, watched)
# GUI unit: it must start only once the compositor's env (WAYLAND_DISPLAY,
# XDG_RUNTIME_DIR) has been imported into the user manager, which is what
# graphical-session.target marks. Bound to default.target instead, it would
# race the session and fail with "could not connect to display".
After=graphical-session.target
PartOf=graphical-session.target
# StartLimitIntervalSec=0 belongs in [Unit], not [Service] -- systemd silently
# ignores it in the wrong section. 0 = no rate-limit window can ever
# accumulate a start count and refuse to restart; paired with Restart=always.
StartLimitIntervalSec=0
[Service]
Environment=PYTHONUNBUFFERED=1
# Point this at YOUR checkout. No --spectro here on purpose: the spectrum
# backdrop is an AUDIO consumer (a tap on the master bus), and this unit is
# Restart=always -- putting the flag here would make the tap permanent at
# login. It is a runtime choice: `s` in the window, or a hand-launched
# --spectro.
ExecStart=/usr/bin/python3 %h/where/you/cloned/midiviz/midiviz.py
Restart=always
# ...EXCEPT when the human closed it. Restart=always cannot distinguish "the
# aseqdump pipe hit EOF" from "the user clicked the X", and treating the
# second as the first makes the lens feel welded on: the window goes away and
# comes back five seconds later. midiviz.py exits USER_CLOSE_EXIT=78 for a
# deliberate close only (the X, Q, Esc), so this keeps the restart for every
# failure mode while letting a person actually close the thing.
# SuccessExitStatus keeps the deliberate close from showing the unit red.
SuccessExitStatus=78
RestartPreventExitStatus=78
RestartSec=5
[Install]
WantedBy=graphical-session.target
[project]
name = "midiviz"
version = "1.0.0"
description = "Live MIDI as a picture, not a transcript — a lens over your MIDI control surface"
readme = "README.md"
license = { text = "GPL-3.0-or-later" }
authors = [{ name = "Paul-Louis NECH" }]
requires-python = ">=3.10"
dependencies = [
"PySide6>=6.5",
]
keywords = ["midi", "visualization", "alsa", "launch-control-xl", "livecoding"]
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: X11 Applications :: Qt",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3",
"Topic :: Multimedia :: Sound/Audio :: MIDI",
]
[project.urls]
Homepage = "https://git.nech.pl/pln/midiviz"
GitHub = "https://github.com/PLNech/midiviz"
# The app is a single-module, sibling-import design (midiviz.py imports
# midimon/midistream/lcxl_grid as top-level names), so it is not installed as
# a library — run it from the checkout: `python3 midiviz.py`.
[tool.pytest.ini_options]
testpaths = ["tests"]
"""Pure-parser tests for midimon (no ALSA needed)."""
# SPDX-License-Identifier: GPL-3.0-or-later
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import midimon as M
def test_note_name():
assert M.note_name(60) == "C4"
assert M.note_name(69) == "A4"
assert M.note_name(72) == "C5"
assert M.note_name(61) == "C#4"
def test_parse_note_on():
ev = M.parse_line(" 28:0 Note on 0, note 60, velocity 100")
assert ev["source"] == "28:0"
assert ev["event"] == "Note on"
assert ev["ch"] == 0
assert "note 60" in ev["data"]
def test_parse_control_change():
ev = M.parse_line(" 28:0 Control change 5, controller 7, value 99")
assert ev["event"] == "Control change" and ev["ch"] == 5
def test_parse_non_event_returns_none():
assert M.parse_line("Source Event Ch Data") is None
assert M.parse_line("Waiting for data at port 128:0.") is None
assert M.parse_line("") is None
def test_render_contains_event_and_notename():
ev = M.parse_line(" 28:0 Note on 0, note 60, velocity 100")
out = M.render(ev)
assert "Note on" in out and "C4" in out
def test_enrich_note_and_velocity():
ev = M.enrich(M.parse_line(" 28:0 Note on 0, note 60, velocity 100"))
assert ev["note"] == 60 and ev["note_name"] == "C4" and ev["velocity"] == 100
def test_enrich_controller():
ev = M.enrich(M.parse_line(" 28:0 Control change 0, controller 74, value 64"))
assert ev["controller"] == 74 and ev["value"] == 64 and "note" not in ev
"""Pure tests for midistream: port parsing, and the coalescer (no ALSA).
# SPDX-License-Identifier: GPL-3.0-or-later
The coalescer's one rule is the only thing standing between "the monitor is fast" and
"the monitor lies": continuous controls are STATE and may be superseded, notes are
EVENTS and may never be dropped. Get that backwards and a fast monitor silently loses
what was played, which is strictly worse than a slow one.
"""
import queue
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import midistream as MS
SAMPLE = """ Port Client name Port name
0:0 System Timer
0:1 System Announce
14:0 Midi Through Midi Through Port-0
28:0 nanoKONTROL2 nanoKONTROL2 MIDI 1
"""
def test_parse_ports_skips_header_and_parses_rows():
ports = MS.parse_ports(SAMPLE)
assert {"addr": "28:0", "client": "nanoKONTROL2", "port": "nanoKONTROL2 MIDI 1"} in ports
assert all(":" in p["addr"] for p in ports)
assert not any(p["client"] == "Client name" for p in ports) # header skipped
assert len(ports) == 4
def test_parse_ports_empty():
assert MS.parse_ports("") == []
# ------------------------------------------------------------------ coalesce
def cc(controller, value, ch=0, source="24:0"):
return {"source": source, "event": "Control change", "ch": ch,
"controller": controller, "value": value, "data": ""}
def note(n, vel=100, on=True, ch=0, source="24:0"):
return {"source": source, "event": "Note on" if on else "Note off", "ch": ch,
"note": n, "velocity": vel, "data": ""}
def test_a_fader_sweep_collapses_to_its_final_value():
out = MS.coalesce([cc(77, v) for v in range(128)])
assert len(out) == 1 and out[0]["value"] == 127
def test_every_note_survives_even_a_flood_of_controllers():
"""Notes are what was PLAYED. Losing one to a fader sweep is unforgivable."""
batch = [note(60), *(cc(77, v) for v in range(100)), note(64), note(60, on=False)]
out = MS.coalesce(batch)
assert [e for e in out if "note" in e] == [note(60), note(64), note(60, on=False)]
def test_distinct_controllers_do_not_collapse_into_each_other():
out = MS.coalesce([cc(77, 10), cc(78, 20), cc(77, 30)])
assert len(out) == 2
assert {e["controller"]: e["value"] for e in out} == {77: 30, 78: 20}
def test_same_controller_on_a_different_channel_or_device_is_a_different_control():
out = MS.coalesce([cc(77, 1, ch=0), cc(77, 2, ch=1), cc(77, 3, source="28:0")])
assert len(out) == 3
def test_chronological_order_is_preserved():
"""A superseded value is replaced WHERE IT STOOD, so the monitor still reads as a
timeline rather than reshuffling history to the end."""
out = MS.coalesce([cc(77, 1), note(60), cc(77, 2), note(62)])
assert [e.get("controller", e.get("note")) for e in out] == [77, 60, 62]
assert out[0]["value"] == 2
def test_coalesce_is_a_no_op_on_an_already_sparse_batch():
batch = [note(60), cc(77, 5), note(60, on=False)]
assert MS.coalesce(batch) == batch
def test_unknown_event_kinds_are_treated_as_discrete():
"""Unrecognised == keep. A coalescer that guesses wrong should lose nothing."""
weird = {"source": "24:0", "event": "System exclusive", "ch": None, "data": "F0"}
assert MS.coalesce([weird, weird]) == [weird, weird]
# ---------------------------------------------------- the subscriber queue
def test_a_full_queue_drops_the_OLDEST_event_not_the_newest():
"""The original `except queue.Full: pass` kept 512 stale events and threw away the
one that had just happened, so a tab that stalled once froze forever."""
stream = MS.MidiStream()
q: queue.Queue = queue.Queue(maxsize=4)
stream._subs.add(q)
for v in range(10):
stream._fanout(cc(77, v))
got = [q.get_nowait()["value"] for _ in range(q.qsize())]
assert got == [6, 7, 8, 9], f"kept {got}; the newest value must survive"
"""Tests for midiviz's non-drawing parts (no Qt, no ALSA needed).
# SPDX-License-Identifier: GPL-3.0-or-later
The drawing itself is verified by `python3 midiviz.py --selftest`, which renders
synthetic events through the real paint path; green tests on pure functions prove
nothing about a window. What is worth pinning here is the stuff that would fail
*silently*: the port-preference copy drifting from midimon's authored one, and a
word sneaking into the glyph set.
"""
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import midimon # noqa: E402
import midiviz as V # noqa: E402
# ── the copy must never disagree with the original ─────────────────────────
def test_watch_preference_does_not_drift_from_midimon():
"""midiviz keeps a fallback copy of the preference order for trees whose
midimon predates `resolve_port`. Two lists that are supposed to be the same
list are exactly the kind of thing that quietly stops being the same."""
authored = getattr(midimon, "WATCH_PREFERENCE", None)
if authored is None:
return # this tree's midimon has none; nothing to drift from
assert tuple(V.WATCH_PREFERENCE) == tuple(authored)
def test_resolve_delegates_to_midimon_when_it_has_the_helper(monkeypatch):
monkeypatch.setattr(midimon, "resolve_port", lambda: ("99:9", "sentinel"),
raising=False)
assert V.resolve_watch_port() == ("99:9", "sentinel")
# ── the fallback resolver ──────────────────────────────────────────────────
# Real `aseqdump -l` output from this rig, with the LCXL3 and the driver both up.
_PORTS = """ Port Client name Port name
0:0 System Timer
14:0 Midi Through Midi Through Port-0
20:0 LCXL3 1 LCXL3 1 MIDI In
20:1 LCXL3 1 LCXL3 1 DAW In
133:0 RtMidiOut Client ParVagues LCXL3
"""
def _fallback(monkeypatch, text):
monkeypatch.delattr(midimon, "resolve_port", raising=False)
monkeypatch.setattr(V.subprocess, "run",
lambda *a, **k: subprocess.CompletedProcess(a, 0, text, ""))
return V.resolve_watch_port()
def test_the_driver_is_found_by_its_PORT_name_not_its_client(monkeypatch):
"""The whole point. python-rtmidi registers the lcxl3 driver's client as
'RtMidiOut Client' and puts 'ParVagues LCXL3' on the PORT, so matching only
the client column silently falls through to the raw hardware — the monitor
would work, and show the wrong stream."""
pid, label = _fallback(monkeypatch, _PORTS)
assert pid == "133:0"
assert "ParVagues LCXL3" in label
def test_it_falls_back_down_the_preference_order(monkeypatch):
without_driver = "\n".join(l for l in _PORTS.splitlines() if "ParVagues" not in l)
assert _fallback(monkeypatch, without_driver)[0] == "20:1" # raw v3 DAW port
only_thru = "\n".join(l for l in _PORTS.splitlines() if "LCXL3" not in l)
assert _fallback(monkeypatch, only_thru)[0] == "14:0" # the catch-all
assert _fallback(monkeypatch, " Port Client name Port name\n")[0] is None
def test_a_header_only_listing_is_not_mistaken_for_a_port(monkeypatch):
pid, label = _fallback(monkeypatch, "")
assert pid is None and "no MIDI source" in label
# ── the viz is wordless, and every value lands on one scale ────────────────
def test_no_glyph_is_a_word():
"""PLN: 'no word like control change pure viz'. Every rendered glyph is one
character, and none of them is a letter — hex digits are the only alnum."""
glyphs = [g for _kw, g in V.CLASS_GLYPH] + [V.OTHER_GLYPH] + list(V.HEX)
for g in glyphs:
assert len(g) == 1, g
assert not g.isalpha() or g in V.HEX, g
def test_note_on_and_off_are_different_glyph_classes():
on, on_fam = V._glyph_for("Note on")
off, off_fam = V._glyph_for("Note off")
assert on != off and on_fam == off_fam == V.FAM_NOTE
assert V._glyph_for("Some future event")[0] == V.OTHER_GLYPH
def test_every_event_kind_normalises_onto_0_127():
assert V._norm_value({"value": 0}) == 0
assert V._norm_value({"value": 127}) == 127
assert V._norm_value({"velocity": 100}) == 100
assert V._norm_value({"program": 7}) == 7
assert V._norm_value({}) == 64 # no value = mid, not 0
# pitch bend is ±8192, and centre must land mid-scale rather than clamp to 0
assert V._norm_value({"value": 0, "event": "Pitch bend"}) == 0
assert 61 <= V._norm_value({"value": -1}) <= 65
assert V._norm_value({"value": -8192}) == 0
assert V._norm_value({"value": 8191}) == 127
def test_dataless_transport_messages_do_not_parse_at_all():
"""A real gap, pinned here rather than papered over.
`midimon.parse_line`'s row regex is `addr EVENT <2+ spaces> DATA`, so an
aseqdump line with no data column — which is exactly how Start, Stop,
Continue and Clock print — matches nothing and is dropped. midiviz therefore
has glyphs (▶ ■ ▷ ·) that can never light up, and midimon's own console
silently omits transport too. Fixing it belongs in midimon (one parser per
concept); when that lands, this test is what tells you to delete the xfail.
"""
assert midimon.parse_line(" 28:0 Start") is None
assert midimon.parse_line(" 28:0 Stop") is None
# ...while the same event WITH a data column parses fine:
assert midimon.parse_line(" 28:0 Note on 1, note 60, velocity 99") is not None
def test_the_real_parser_feeds_the_real_ingest_path():
"""The selftest's synthetic lines must actually parse — if the fixture drifted
out of aseqdump's shape the selftest would render an empty window and pass."""
lines = V._synthetic_lines()
parsed = [midimon.parse_line(l) for l in lines]
unparsed = [l.split()[1] for l, p in zip(lines, parsed) if p is None]
# the ONLY tolerated failures are the data-less transport lines above
assert set(unparsed) <= {"Start", "Stop"}, unparsed
enriched = [midimon.enrich(p) for p in parsed if p is not None]
ccs = [e["controller"] for e in enriched if "controller" in e]
# every one of the 48 authored grid cells is covered
assert set(V.grid.CC_TO_CELL) <= set(ccs)
assert any(cc not in V.grid.CC_TO_CELL for cc in ccs), "no un-gridded CC to rain"
# ── the close latch ────────────────────────────────────────────────────────
#
# The close-latch tests that assert agreement with the RIG's supervisor
# (rig_units.ensure() and launchers.py) live in the rig's own suite —
# those two files are rig-side and are not part of this project. The
# latch path itself is still exercised below via _latch_close().
# ── the two controls stay hittable ─────────────────────────────────────────
#
# Sizing a hit target to its glyph gave an 8px-wide X: pleasant to look at,
# unhittable during a set, and at 0.6 scale the pin and the X had to either
# overlap or shrink below usable. The layout now derives targets from the
# right edge and centres the glyphs inside them, so this holds by
# construction -- which is worth an assertion at the scales PLN actually
# zooms through, since a regression here is invisible until he reaches for it.
def _widget(scale, width):
import importlib.util
import sys as _sys
from pathlib import Path as _Path
root = _Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("_mv_ctrl",
root / "midiviz.py")
mv = importlib.util.module_from_spec(spec)
_sys.modules["_mv_ctrl"] = mv
spec.loader.exec_module(mv)
try:
_QtCore, _QtGui, QtWidgets = mv._qt()
except Exception:
return None, None
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
w = mv.build_widget("--", None, scale=scale)
w.resize(width, 400)
w.show()
app.processEvents()
return mv, w
def test_controls_are_hittable_and_disjoint_at_every_scale():
import os
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
mv, w0 = _widget(1.0, 900)
if mv is None:
pytest.skip("no Qt available")
for scale in (0.6, 1.0, 1.6, 2.4):
for width in (520, 900, 1920):
_, w = _widget(scale, width)
pin, close = w._ctrl_rects()
assert not pin.intersects(close), (
f"pin and X overlap at scale={scale} width={width}: a click "
f"meant for one would hit the other")
assert close.right() <= w.width(), \
f"the X is off-screen at scale={scale} width={width}"
assert min(pin.width(), pin.height(),
close.width(), close.height()) >= w.MIN_TARGET, (
f"a target fell below MIN_TARGET at scale={scale} "
f"width={width}: pin={pin} close={close}")
# The sparkline must stop before the controls, not run under them.
assert w._ctrl_left() <= pin.left(), \
"the sparkline is allowed to draw over the controls"
w.close()
def test_user_close_exit_code_matches_the_unit():
"""The code's exit status and the unit's guard are one number, twice.
Restart=always cannot distinguish an aseqdump EOF from PLN clicking the X,
so a deliberate close is signalled by exit status and the unit exempts
exactly that status. If these two ever drift, the X closes the window and
systemd puts it back five seconds later — which is the complaint, reported
twice, and it looks like the close is broken rather than the number.
"""
import importlib.util
import re
import sys as _sys
from pathlib import Path as _Path
root = _Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("_mv_exit",
root / "midiviz.py")
mv = importlib.util.module_from_spec(spec)
_sys.modules["_mv_exit"] = mv
spec.loader.exec_module(mv)
unit = (root / "packaging/midiviz.service").read_text()
m = re.search(r"^RestartPreventExitStatus=(\d+)\s*$", unit, re.M)
assert m, ("midiviz.service has no RestartPreventExitStatus, so "
"Restart=always will undo every deliberate close")
assert int(m.group(1)) == mv.USER_CLOSE_EXIT, (
f"the unit exempts exit {m.group(1)} but the code exits "
f"{mv.USER_CLOSE_EXIT} on a user close")
# Must not collide with the codes a normal run or a signal produces.
assert mv.USER_CLOSE_EXIT not in (0, 1), "collides with a normal exit"
assert mv.USER_CLOSE_EXIT < 128, "collides with the 128+N signal range"
# Preventing the restart is only half of it: without SuccessExitStatus,
# systemd files a deliberate close as `failed (result: exit-code)` and the
# unit shows red everywhere the rig is monitored, which sends the next
# person to debug a unit that is behaving perfectly.
ok = re.search(r"^SuccessExitStatus=(.+)$", unit, re.M)
assert ok, ("midiviz.service has no SuccessExitStatus, so a close the "
"human asked for will be reported as a unit failure")
assert str(mv.USER_CLOSE_EXIT) in ok.group(1).split(), (
f"SuccessExitStatus={ok.group(1)!r} does not include "
f"{mv.USER_CLOSE_EXIT}")
# ── the spectrum backdrop ──────────────────────────────────────────────────
#
# PLN asked for a spectro "behind" the rain so the Ardour spectro VSTs could
# go. The whole risk of the feature is that it is an AUDIO consumer on a box
# that performs live, so what is asserted here is mostly about restraint: it
# must not exist until asked, it must genuinely go away when un-asked, and
# its numbers must not be able to paint silence as signal.
def test_the_spectro_does_not_exist_until_it_is_asked_for(monkeypatch):
"""Off by default means NO PROCESS, not a hidden one.
A backdrop that spawned `pw-record` at startup and merely declined to
paint would be exactly the always-on consumer this is not allowed to be,
and nothing on screen would reveal it.
"""
import os
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
mv, w = _widget(1.0, 900)
if mv is None:
pytest.skip("no Qt available")
spawned = []
monkeypatch.setattr(mv.subprocess, "Popen",
lambda *a, **k: spawned.append(a) or (_ for _ in ()).throw(
AssertionError("the backdrop spawned a capture unasked")))
assert w.spectro is False
assert w.spec_src is None
w.tick() # a full frame with nobody asking
w.grab()
assert spawned == []
w.close()
def test_toggling_the_spectro_acquires_and_releases_the_tap():
"""`s` on, `s` off — and off must hand the capture back, not hide it."""
import os
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
mv, w = _widget(1.0, 900)
if mv is None:
pytest.skip("no Qt available")
closed = []
class FakeSource:
hop, rate, err, frames = 256, 48000, "", 0
def latest(self):
return tuple(0.5 for _ in range(mv.SPEC_BANDS))
def close(self):
closed.append(True)
w.set_spectro(True, FakeSource())
assert w.spectro and w.spec_src is not None
w.tick()
assert w._spec_frame is not None, "a published frame never reached the paint state"
w.set_spectro(False)
assert not w.spectro and w.spec_src is None
assert closed == [True], "switching the backdrop off left the capture running"
assert w._spec_frame is None
w.close()
def test_closing_the_window_releases_the_audio_tap():
"""A closed window must not outlive its own switch.
The X writes the close latch and systemd will not restart us, so nothing
would ever come back to turn a leaked `pw-record` off again.
"""
import os
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
mv, w = _widget(1.0, 900)
if mv is None:
pytest.skip("no Qt available")
closed = []
class FakeSource:
err, frames = "", 0
def latest(self):
return None
def close(self):
closed.append(True)
w.set_spectro(True, FakeSource())
w.close()
assert closed == [True], "closeEvent left the capture on the master bus"
def test_band_edges_never_leave_a_band_empty():
"""Strictly increasing, in range, at every width the window can be.
A 2048-point FFT has fewer bins than we have bands below ~750 Hz, so the
naive log ramp produces duplicate edges — and a duplicated edge is a band
that sums zero bins, which paints as a black hole in the bass. "Dark = not
mapped" is the reading a cockpit trains you into (the LED work settled
that), so an empty band is worse than a coarse one.
"""
import importlib.util
import sys as _sys
from pathlib import Path as _Path
root = _Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("_mv_bands",
root / "midiviz.py")
mv = importlib.util.module_from_spec(spec)
_sys.modules["_mv_bands"] = mv
spec.loader.exec_module(mv)
for bands in (12, 24, mv.SPEC_BANDS, 64, 96):
e = mv._spec_band_edges(bands, mv.SPEC_FFT, mv.SPEC_RATE)
assert len(e) == bands + 1
assert all(e[i] < e[i + 1] for i in range(bands)), \
f"an empty band at bands={bands}: {list(e)}"
assert e[0] >= 1 and e[-1] <= mv.SPEC_FFT // 2, \
f"edges ran off the spectrum at bands={bands}: {e[0]}..{e[-1]}"
def test_the_analysis_seam_is_the_only_thing_the_paint_path_needs():
"""`push()` carries the whole feature; the subprocess carries none of it.
This is what lets the backdrop be tested at all on a box with no audio
server, and it is also the honest boundary: green here says nothing about
`pw-record`, only that everything downstream of a block of samples works.
"""
import math
import importlib.util
import sys as _sys
from pathlib import Path as _Path
import pytest
np = pytest.importorskip("numpy")
root = _Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("_mv_push",
root / "midiviz.py")
mv = importlib.util.module_from_spec(spec)
_sys.modules["_mv_push"] = mv
spec.loader.exec_module(mv)
src = mv.SpectrumSource(target="__never__")
t = np.arange(src.fft_n) / float(src.rate)
for _ in range(30):
frame = src.push(0.25 * np.sin(2 * math.pi * 3000.0 * t))
assert len(frame) == mv.SPEC_BANDS
assert all(0.0 <= v <= 1.0 for v in frame), "a band escaped 0..1"
hi = int(np.argmax(frame))
bin_hz = src.rate / float(src.fft_n)
assert src.edges[hi] * bin_hz <= 3000.0 <= src.edges[hi + 1] * bin_hz, \
"a 3 kHz tone did not land in the band that contains 3 kHz"
for _ in range(120):
quiet = src.push(np.zeros(src.fft_n, dtype=np.float32))
assert all(v == v for v in quiet), "silence produced NaN, which paints full-height"
assert max(quiet) < 0.02, f"silence read as signal: {max(quiet):.3f}"
src.close() # never started; must still be safe
def test_the_backdrop_is_painted_behind_everything_else():
"""Ordering IS the feature — "overlay behind a basic spectro"."""
import os
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
mv, w = _widget(1.0, 900)
if mv is None:
pytest.skip("no Qt available")
order = []
for name in ("_paint_spectrum", "_paint_chrome", "_paint_header",
"_paint_matrix", "_paint_gutter", "_paint_stream"):
real = getattr(w, name)
def probe(*a, _n=name, _r=real, **k):
order.append(_n)
return _r(*a, **k)
setattr(w, name, probe)
class FakeSource:
err, frames = "", 0
def latest(self):
return tuple(0.6 for _ in range(mv.SPEC_BANDS))
def close(self):
pass
w.set_spectro(True, FakeSource())
w.tick()
w.grab()
assert order and order[0] == "_paint_spectrum", \
f"the spectrum is not the first layer painted: {order}"
w.set_spectro(False)
w.close()
def test_a_short_pipe_read_is_not_mistaken_for_end_of_stream():
"""The bug that made the whole backdrop dead while the selftest passed.
`Popen(bufsize=0)` hands back a raw `FileIO`: `read(n)` is one `os.read`
and returns whatever the pipe holds, so a hop-sized read is short far more
often than not. Treating that as EOF ended the capture on its first chunk
(`blocks=0`, no error recorded) — and every pure-function test still went
green, because none of them touched the pipe.
"""
import io
import importlib.util
import sys as _sys
from pathlib import Path as _Path
root = _Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("_mv_read",
root / "midiviz.py")
mv = importlib.util.module_from_spec(spec)
_sys.modules["_mv_read"] = mv
spec.loader.exec_module(mv)
class Dribble(io.RawIOBase):
"""A pipe that never gives you as much as you asked for."""
def __init__(self, data, most=7):
self.buf, self.most = bytearray(data), most
def read(self, n=-1):
take = min(n if n and n > 0 else 1, self.most, len(self.buf))
out, self.buf = bytes(self.buf[:take]), self.buf[take:]
return out
payload = bytes(range(256)) * 8 # 2048 bytes
got = mv._read_exact(Dribble(payload), len(payload))
assert got == payload, "a dribbling stream lost or truncated bytes"
# and the real end of stream still reports itself as one
assert mv._read_exact(Dribble(b""), 16) is None
assert mv._read_exact(Dribble(payload[:100]), len(payload)) is None, \
"a stream that ends mid-block must read as EOF, not a partial frame"
# ── themes ─────────────────────────────────────────────────────────────────
#
# The paint loop indexes its palette blind: `self.lut[fam][lv]`,
# `self.tint[fam][0]`, `self.chrome[5]`, `self.spec_lut[lv]`. A theme that
# forgot one of those does not render wrong, it raises KeyError or IndexError
# inside `paintEvent`, at 25 fps, mid-set. That is what these pin: not how the
# themes look (screenshots did that, and the selftest paints every one), but
# that each of them answers every question the painter asks.
def _themed(theme):
"""A built widget on `theme`, or (None, None) where Qt is unavailable."""
import importlib.util
import os
import sys as _sys
from pathlib import Path as _Path
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
root = _Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("_mv_theme",
root / "midiviz.py")
mv = importlib.util.module_from_spec(spec)
_sys.modules["_mv_theme"] = mv
spec.loader.exec_module(mv)
try:
_QtCore, _QtGui, QtWidgets = mv._qt()
except Exception:
return None, None
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
w = mv.build_widget("--", None, scale=1.0, theme=theme, persist=False)
w.show()
app.processEvents()
return mv, w
def test_every_theme_answers_every_colour_the_painter_asks_for():
import pytest
mv, _ = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
for name in mv.THEMES:
_, w = _themed(name)
assert len(w.lut) == 8, f"{name}: a family lost its ink ramp"
for fam in range(8):
assert len(w.lut[fam]) == mv.LEVELS, \
f"{name}: lut[{fam}] is not {mv.LEVELS} deep — _lv() indexes it blind"
assert len(w.tint[fam]) == 4, \
f"{name}: tint[{fam}] must hold 4 surfaces (idle + 3 heat steps)"
assert len(w.chrome) == mv.LEVELS, \
f"{name}: chrome is read at index 12 on hover; a short ramp raises there"
assert len(w.spec_lut) == mv.SPEC_LEVELS, f"{name}: spectrum ramp is short"
for probe in (w.bg, w.spec_peak_col, w.chrome[12], w.tint[0][0]):
assert probe.isValid(), f"{name}: an invalid QColor reached the palette"
def test_no_theme_leaves_a_field_unset():
"""A Theme built by copying another one and editing is how a None gets in;
`scan` and `chrome` are the only two fields allowed to be one."""
import pytest
if not hasattr(V, "THEMES"):
pytest.skip("no themes in this tree")
optional = {"chrome", "scan"}
for name, th in V.THEMES.items():
assert th.name == name, f"{name}: the key and the theme's own name differ"
for field in th._fields:
if field in optional:
continue
assert getattr(th, field) is not None, f"{name}.{field} is None"
assert set(V.THEME_ORDER) <= set(V.THEMES), \
"the cycle order names a theme that does not exist"
assert V.DEFAULT_THEME in V.THEMES
def test_mapped_but_idle_is_visible_on_every_theme():
"""The design invariant, generalised.
On dark it reads "must not be black"; on a light page the same rule is
"must not be invisible against the page". Either way the floor tint of a
mapped cell has to differ from the background by enough that an eye lands
on it — a cell you cannot see reads as a control that is not wired, which
is the hardware-fault misreading the LED work already paid for once.
"""
import pytest
mv, _ = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
for name in mv.THEMES:
_, w = _themed(name)
bg = w.bg
for fam in range(8):
floor = w.tint[fam][0]
dist = (abs(floor.red() - bg.red()) + abs(floor.green() - bg.green())
+ abs(floor.blue() - bg.blue()))
assert dist >= 9, (
f"{name}: the idle floor tint of family {fam} is "
f"{floor.name()} against a {bg.name()} page — invisible, so "
f"48 wired controls would read as unwired")
# and it must never be the page itself
assert floor.rgba() != bg.rgba(), f"{name}: floor tint IS the background"
def test_dark_stays_the_look_pln_trained_his_eye_on():
"""A ratchet, not a design statement.
`dark` is the palette a dozen sets were played on. It was proven
pixel-identical to the pre-theme render when themes landed; these few rgba
values keep it that way, so a tweak aimed at `light` cannot quietly warm
the cockpit by one step.
"""
import pytest
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
assert w.bg.rgba() == 0xff0a0612
assert w.lut[0][0].rgba() == 0xff08010e
assert w.lut[0][8].rgba() == 0xff541c7c
assert w.lut[0][15].rgba() == 0xffce8aff
assert w.chrome[6].rgba() == w.lut[mv.FAM_OTHER][6].rgba(), \
"on dark, chrome IS the FAM_OTHER ink ramp"
for fam in range(8):
for i in range(4):
assert w.tint[fam][i].rgba() == w.lut[fam][1 + i].rgba(), (
"on dark the surface ramp is the ink ramp at levels 1..4; that "
"identity is what made the theme split invisible")
def test_switching_theme_drops_the_cached_scanline_pixmap():
"""The bug this prevents renders perfectly and looks broken anyway.
The CRT texture is one cached pixmap, drawn in the theme's own colours and
blitted whole every frame. Keep it across a theme change and a violet haze
from the cockpit stays painted over a white page for the rest of the set.
"""
import pytest
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
w._scanlines()
assert w._scan is not None, "the texture did not cache at all"
w.set_theme("light", save=False)
assert w._scan is None, "a stale scanline pixmap survived the theme change"
w.set_theme("sun", save=False)
assert w.theme.scan is None and w._scanlines_blit is not None
# sun has no texture: the blit must be a no-op, not a crash
_QtCore, QtGui, _QtWidgets = mv._qt()
pm = QtGui.QPixmap(w.width(), w.height())
pm.fill(w.bg)
p = QtGui.QPainter(pm)
try:
w._scanlines_blit(p)
finally:
p.end()
def test_the_menu_only_mirrors_actions_the_keyboard_already_had():
"""The menu is discoverability, not a second code path.
Both faces call the same method, so this drives the KEYS and asserts the
menu's checkmarks followed. If the menu ever grows its own copy of an
action, this is where the two stop agreeing.
"""
import pytest
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
_QtCore, QtGui, _QtWidgets = mv._qt()
def press(key):
w.keyPressEvent(QtGui.QKeyEvent(_QtCore.QEvent.Type.KeyPress,
getattr(_QtCore.Qt.Key, key),
_QtCore.Qt.KeyboardModifier.NoModifier))
press("Key_P")
assert w.paused and w._act_pause.isChecked(), "p paused but the menu says running"
press("Key_P")
assert not w.paused and not w._act_pause.isChecked()
press("Key_T")
assert w.on_top is False and w._act_pin.isChecked() is False
press("Key_T")
assert w.on_top is True and w._act_pin.isChecked() is True
before = w.theme.name
press("Key_D")
assert w.theme.name != before, "d did not cycle the theme"
assert w._theme_acts[w.theme.name].isChecked(), \
"the theme cycled and the menu's radio did not follow"
w.cc[13] = [64, 0.0, 0]
press("Key_C")
assert not w.cc, "c did not clear"
s0 = w.scale
size0 = (w.width(), w.height())
press("Key_Plus")
assert w.scale > s0, "+ did not grow the type"
assert (w.width(), w.height()) == size0, \
"+ resized the window: the size belongs to the WM now"
press("Key_Minus")
assert abs(w.scale - s0) < 1e-9, "+ then - did not return to the same scale"
assert w._scale_acts[s0].isChecked(), \
"the scale came back to 1.0 and the menu's radio did not"
# The pin from the tray must not un-hide a window that was dismissed.
w.set_window_shown(False)
assert not w.isVisible()
w._set_on_top(not w.on_top)
assert not w.isVisible(), \
"toggling always-on-top brought back a window hidden to the tray"
w.set_window_shown(True)
# every menu entry that names a key must have a handler wired
labels = [a.text() for a in w.menu.actions() if a.text()]
assert any("Quit" in t for t in labels)
assert any("Pause" in t for t in labels)
assert any("Clear" in t for t in labels)
assert any("Spectrum" in t for t in labels)
assert any("Always on top" in t for t in labels)
def test_quit_from_the_menu_records_a_deliberate_close(monkeypatch, tmp_path):
"""The tray's Quit must latch exactly like `q` does, or systemd's converge
puts the window straight back and PLN reports "too sticky" a third time.
XDG_RUNTIME_DIR is redirected because this drives a REAL deliberate close:
without it, every suite run wrote `midiviz.closed` into the live runtime
dir, which is the one file that tells rig_units.ensure() not to bring the
monitor back. A test is not allowed to have an opinion about that.
"""
import pytest
monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path))
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
quit_act = [a for a in w.menu.actions() if a.text().startswith("Quit")]
assert quit_act, "the menu has no Quit"
assert not w._user_closed
quit_act[0].trigger()
assert w._user_closed, \
"menu Quit closed the window without recording that a human asked"
def test_the_tray_degrades_silently_where_there_is_no_status_area():
"""Headless is the guard's own test case: no tray, and the window still
builds and paints. Never failing to start is the point."""
import pytest
import importlib.util
import os
import sys as _sys
from pathlib import Path as _Path
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
root = _Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("_mv_tray",
root / "midiviz.py")
mv = importlib.util.module_from_spec(spec)
_sys.modules["_mv_tray"] = mv
spec.loader.exec_module(mv)
try:
_QtCore, _QtGui, QtWidgets = mv._qt()
except Exception:
pytest.skip("no Qt available")
app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([])
if QtWidgets.QSystemTrayIcon.isSystemTrayAvailable():
pytest.skip("this session HAS a tray; the degrade path is not reachable")
w = mv.build_widget("--", None, scale=1.0, tray=True, persist=False)
w.show()
app.processEvents()
assert w.tray is None, "a tray was constructed where the platform has none"
assert w.grab().width() > 0, "the window did not paint without a tray"
# hide/show is still available: it is the window's own state, not the tray's
w.set_window_shown(False)
assert not w.isVisible()
w.set_window_shown(True)
assert w.isVisible()
# ── the remembered choice ──────────────────────────────────────────────────
#
# This is the part most likely to be done carelessly, so it gets the most
# cases. A monitor that will not start because its config file is half-written
# is strictly worse than one with no memory at all — every one of these inputs
# must come back as "use the default", never as a traceback two minutes before
# a set.
def test_config_path_follows_xdg_then_falls_back_to_dot_config(monkeypatch, tmp_path):
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
assert V.config_path() == tmp_path / "xdg" / "parvagues" / "midiviz.json"
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
monkeypatch.setenv("HOME", str(tmp_path / "home"))
assert V.config_path() == tmp_path / "home" / ".config" / "parvagues" / "midiviz.json"
def test_config_round_trips(monkeypatch, tmp_path):
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
assert V.save_config("sun", 1.45) is True
assert V.load_config() == {"theme": "sun", "scale": 1.45}
def test_a_missing_config_is_not_an_error(monkeypatch, tmp_path):
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "nope"))
assert V.load_config() == {"theme": None, "scale": None}
def test_every_shape_of_bad_config_reads_as_no_config(monkeypatch, tmp_path):
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
path = V.config_path()
path.parent.mkdir(parents=True, exist_ok=True)
cases = {
'{"theme": "sun", "sca': (None, None), # truncated write
"": (None, None), # zero-length file
"not json at all": (None, None),
'["sun", 1.5]': (None, None), # a list, not an object
"42": (None, None), # a bare number
'{"theme": "neon", "scale": 1.0}': (None, 1.0), # a theme that was renamed
'{"theme": 7, "scale": 1.0}': (None, 1.0), # a theme that is not a name
'{"theme": "light", "scale": "abc"}': ("light", None),
'{"theme": "light", "scale": null}': ("light", None),
'{"theme": "light", "scale": NaN}': ("light", None),
'{"theme": "light", "scale": Infinity}': ("light", None),
'{"theme": "light", "scale": 99}': ("light", 2.4), # clamped, not refused
'{"theme": "light", "scale": -3}': ("light", 0.6),
"{}": (None, None),
}
for body, want in cases.items():
path.write_text(body)
got = V.load_config()
assert (got["theme"], got["scale"]) == want, \
f"{body!r} read back as {got}, not {want}"
def test_an_unreadable_config_reads_as_no_config(monkeypatch, tmp_path):
import os
import pytest
if os.getuid() == 0:
pytest.skip("root can read anything; the chmod guard proves nothing")
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
path = V.config_path()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('{"theme": "sun", "scale": 1.2}')
path.chmod(0o000)
try:
assert V.load_config() == {"theme": None, "scale": None}
finally:
path.chmod(0o600)
def test_a_config_directory_that_cannot_exist_fails_without_raising(monkeypatch,
tmp_path):
"""XDG_CONFIG_HOME pointing at a FILE. mkdir cannot succeed, and a window
must not die over being unable to remember a colour."""
wall = tmp_path / "wall"
wall.write_text("not a directory\n")
monkeypatch.setenv("XDG_CONFIG_HOME", str(wall))
assert V.save_config("sun", 1.0) is False
assert V.load_config() == {"theme": None, "scale": None}
def test_a_nan_scale_never_reaches_the_font_code(monkeypatch, tmp_path):
"""The one bad value that survives float(), min() and max() untouched and
only detonates later, inside round() in `_apply_scale`, where the
traceback points at the fonts and not at the config file."""
assert V._clean_scale(float("nan")) is None
assert V._clean_scale(float("inf")) is None
assert V._clean_scale("1.2") == 1.2
assert V._clean_scale(None) is None
assert V._clean_scale([]) is None
def test_a_saved_theme_and_scale_come_back_on_the_next_window(monkeypatch,
tmp_path):
"""The whole point: the second time PLN is in the sun, it is already sunny."""
import pytest
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
w._persist = True
w.set_theme("sun")
w._rescale(+0.15)
cfg = mv.load_config()
assert cfg["theme"] == "sun", "the theme change was not written"
assert cfg["scale"] == w.scale, "the scale change was not written"
# and a widget that was NOT asked to persist must not write at all
(tmp_path / "parvagues" / "midiviz.json").unlink()
_, w2 = _themed("dark")
w2.set_theme("light")
w2._rescale(-0.15)
assert mv.load_config() == {"theme": None, "scale": None}, \
"a widget built with persist=False rewrote the human's saved choice"
# ── the size is the WM's, the density is the window's ──────────────────────
#
# `_apply_scale` used to end in `resize(BASE_W * scale, BASE_H * scale)`, so
# every theme cycle that flipped the bold weight threw away whatever geometry
# the tiling WM had handed out. These pin the two halves of the fix separately,
# because each half is invisible on its own: type that does not follow the
# window looks like a font bug, and a window that snaps back looks like a WM
# bug, and the same line caused both.
def test_the_type_follows_the_window_and_stops_at_the_clamp():
"""Bigger window, bigger glyphs — and a bound at each end, or a 4K tile
would ask for a 90 px face and a 200 px-tall one for a 3 px face."""
import pytest
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
ref = (w._ref_w, w._ref_h)
assert w._fit(*ref) == 1.0, \
"the window is not 1.0× of the size it was born at — the density " \
"reference disagrees with the window, so nothing below means anything"
small = w._density(round(ref[0] * 0.7), round(ref[1] * 0.7))
base = w._density(*ref)
big = w._density(ref[0] * 2, ref[1] * 2)
assert small < base < big, \
f"the type does not follow the window: {small} / {base} / {big}"
# The tight axis decides: a window stretched on ONE axis only must not
# grow the type, or a short/wide tile clips vertically.
assert w._density(ref[0] * 4, ref[1]) == base, \
"a wider-but-not-taller window grew the type — the tight axis has to win"
assert mv.DENS_MIN <= w._density(1, 1) <= mv.DENS_MAX
assert w._density(20_000, 20_000) <= mv.DENS_MAX, "the clamp does not hold"
assert w._density(1, 1) >= mv.DENS_MIN
# The knob is a multiplier ON TOP of the fit, not a replacement for it.
w.scale = 2.0
assert w._density(*ref) > base
def test_neither_the_knob_nor_the_theme_may_resize_the_window():
"""The tiling-WM bug itself. Cycling the theme re-runs `_apply_scale`
whenever the bold weight changes (`sun` is the bold one), and that is what
used to snap a tiled window back to BASE × scale."""
import pytest
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
w.resize(900, 560)
before = (w.width(), w.height())
px_before = w.f_main.pixelSize()
w._rescale(+0.15)
assert (w.width(), w.height()) == before, "the density knob resized the window"
assert w.f_main.pixelSize() > px_before, "the density knob changed nothing"
for name in mv.THEME_ORDER: # including the bold one
w.set_theme(name, save=False)
assert (w.width(), w.height()) == before, \
f"switching to {name} resized the window"
# …and the one action that IS allowed to, is allowed to.
w.reset_size()
assert (w.width(), w.height()) == (w._ref_w, w._ref_h), \
"Reset size did not return the window to the size it was born at"
def test_the_metrics_are_idempotent_and_re_measured_when_the_weight_flips():
"""`resizeEvent` runs the whole re-measure, so it has to be free of
side effects — and it must NOT skip the one case where the pixel size is
unchanged and the FACE is not: `sun` is bold, and the ribbon's run
concatenation assumes a measured advance."""
import pytest
mv, w = _themed("light")
if mv is None:
pytest.skip("no Qt available")
w.resize(880, 540)
w._apply_scale()
first = (w.mw, w.mh, w.uw, w.uh, w.gut_x, w.cw, w.ch)
w._apply_scale()
assert (w.mw, w.mh, w.uw, w.uh, w.gut_x, w.cw, w.ch) == first, \
"re-applying the same size and scale moved the layout"
bold_before = w.f_main.bold()
w.set_theme("sun", save=False)
assert w.f_main.bold() != bold_before, \
"the bold weight did not reach the font: the metrics key skipped it"
def test_a_grab_zone_is_never_the_body():
"""Corner, edge, body — and a press in the BODY must never resize, or
dragging the lens across a screen would reshape it instead of moving it."""
import pytest
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
QtCore, _QtGui, _QtWidgets = mv._qt()
Qt = QtCore.Qt
w.resize(900, 560)
W, H = w.width(), w.height()
P = QtCore.QPoint
def at(x, y):
return w._edges_at(P(x, y))
L, R = Qt.Edge.LeftEdge, Qt.Edge.RightEdge
T, B = Qt.Edge.TopEdge, Qt.Edge.BottomEdge
assert at(0, 0) == L | T
assert at(W - 1, 0) == R | T
assert at(0, H - 1) == L | B
assert at(W - 1, H - 1) == R | B
# an edge, far from any corner, is exactly one edge
assert at(1, H // 2) == L
assert at(W - 1, H // 2) == R
assert at(W // 2, 0) == T
assert at(W // 2, H - 1) == B
for x, y in ((W // 2, H // 2), (mv.GRAB_PX + 2, H // 2),
(W // 2, mv.GRAB_PX + 3), (W - mv.GRAB_PX - 2, H // 2)):
assert not at(x, y), f"({x},{y}) is the body and it reported a resize edge"
# the body's cursor stays the move cursor; a corner gets a diagonal one
assert w._grab_cursor(at(W // 2, H // 2)) == Qt.CursorShape.SizeAllCursor
assert w._grab_cursor(at(0, 0)) == Qt.CursorShape.SizeFDiagCursor
assert w._grab_cursor(at(W - 1, 0)) == Qt.CursorShape.SizeBDiagCursor
assert w._grab_cursor(at(1, H // 2)) == Qt.CursorShape.SizeHorCursor
assert w._grab_cursor(at(W // 2, H - 1)) == Qt.CursorShape.SizeVerCursor
def test_the_close_control_wins_over_the_top_edge(monkeypatch, tmp_path):
"""At the birth size the X's hit rect starts INSIDE the top grab band, so
the order of the two tests in `mousePressEvent` is load-bearing: a click
meant for the close must close, never begin a resize. The latch goes to a
tmp runtime dir — a test must not tell the rig's converge that a human
closed the monitor."""
import pytest
monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path))
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
QtCore, QtGui, _QtWidgets = mv._qt()
Qt = QtCore.Qt
pin, close = w._ctrl_rects()
assert close.top() < mv.GRAB_PX, (
"this test is moot at this size: the X no longer reaches into the top "
"grab band, so it proves nothing about the ordering")
# …and both controls stay clear of the two top CORNERS, which are the
# zones a hand aims at to make the window bigger.
assert pin.left() > mv.CORNER_PX and close.right() < w.width() - mv.CORNER_PX
p = close.center()
w.mousePressEvent(QtGui.QMouseEvent(
QtCore.QEvent.Type.MouseButtonPress,
QtCore.QPointF(p.x(), p.y()), QtCore.QPointF(p.x(), p.y()),
Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton,
Qt.KeyboardModifier.NoModifier))
assert w._user_closed, "a click on the X did not close the window"
assert not w._resize_edges and w._resize_from is None, \
"a click on the X armed a resize instead"
def test_a_body_drag_moves_and_leaves_the_geometry_alone():
"""A manual resize (the fallback path, when the compositor refuses) only
ever runs for a press that grabbed an edge."""
import pytest
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
QtCore, QtGui, _QtWidgets = mv._qt()
Qt = QtCore.Qt
w.resize(900, 560)
w.show()
def press(x, y):
return QtGui.QMouseEvent(
QtCore.QEvent.Type.MouseButtonPress,
QtCore.QPointF(x, y), QtCore.QPointF(x, y),
Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton,
Qt.KeyboardModifier.NoModifier)
w.mousePressEvent(press(w.width() // 2, w.height() // 2))
assert not w._resize_edges and w._resize_from is None, \
"a press in the body armed a resize"
w.mouseReleaseEvent(None)
# and the manual rect respects minimumSize, whichever edge is dragged
w._resize_edges = Qt.Edge.LeftEdge | Qt.Edge.TopEdge
r0 = QtCore.QRect(100, 100, 900, 560)
got = w._resized_rect(r0, QtCore.QPoint(10_000, 10_000))
assert got.width() >= w.minimumWidth() and got.height() >= w.minimumHeight(), \
f"a crushing drag got through the minimum size: {got}"
assert got.right() == r0.right() and got.bottom() == r0.bottom(), \
"dragging the left/top edge moved the opposite edge"
got = w._resized_rect(r0, QtCore.QPoint(-200, -100))
assert got.width() == 1100 and got.height() == 660
w._resize_edges = Qt.Edge.RightEdge | Qt.Edge.BottomEdge
got = w._resized_rect(r0, QtCore.QPoint(60, 40))
assert (got.x(), got.y()) == (100, 100), \
"dragging the right/bottom edge moved the window"
assert (got.width(), got.height()) == (960, 600)
def test_every_theme_gets_a_swatch_in_its_own_colours():
"""The menu's whole point is "make it colour, now", so a swatch that came
out of the CURRENT palette (three identical chips) would be worse than no
swatch at all."""
import pytest
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
pages = {}
for name, th in mv.THEMES.items():
act = w._theme_acts[name]
assert not act.icon().isNull(), f"{name} has no swatch"
img = act.icon().pixmap(36, 36).toImage()
assert img.width() >= 16, f"{name}'s swatch came back empty"
cols = {img.pixel(x, y) for x in range(4, img.width() - 4)
for y in range(4, img.height() - 4)}
assert len(cols) >= 3, \
f"{name}'s swatch is flat ({len(cols)} colours): it says nothing"
pages[name] = img.pixel(img.width() - 3, 3)
assert mv.THEME_MENU[name].split()[0].lower() in act.text().lower()
assert len(set(pages.values())) == len(pages), \
f"two themes painted the same page colour: {pages}"
def test_a_corner_press_really_arms_a_resize():
"""The one call in this file with a binding-type question in it.
`startSystemResize` takes the compositor's word for it and returns a bool;
the manual path only runs when it says no. Nothing else in the suite sends
a press into a grab band, so if PySide6 rejected the flag type, resizing
would be dead on the real desktop with every test still green. Offscreen
there IS no compositor, so the fallback is what gets exercised here —
which is also the X11 path.
"""
import pytest
mv, w = _themed("dark")
if mv is None:
pytest.skip("no Qt available")
QtCore, QtGui, _QtWidgets = mv._qt()
Qt = QtCore.Qt
w.resize(900, 560)
w.show()
def press(x, y):
w.mousePressEvent(QtGui.QMouseEvent(
QtCore.QEvent.Type.MouseButtonPress,
QtCore.QPointF(x, y), QtCore.QPointF(x, y),
Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton,
Qt.KeyboardModifier.NoModifier))
def move(gx, gy):
w.mouseMoveEvent(QtGui.QMouseEvent(
QtCore.QEvent.Type.MouseMove,
QtCore.QPointF(0, 0), QtCore.QPointF(gx, gy),
Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton,
Qt.KeyboardModifier.NoModifier))
for x, y in ((0, 0), (w.width() - 1, w.height() - 1)):
press(x, y)
armed = w._resize_from is not None
assert armed or not w._resize_edges, (
"a corner press neither armed the manual resize nor handed the "
"drag to the compositor — startSystemResize rejected the edges")
w.mouseReleaseEvent(None)
assert w._resize_from is None and not w._resize_edges
# the bottom-right grab, dragged out: bigger, and the top-left corner of
# the window stays exactly where it was
before = w.geometry()
press(w.width() - 1, w.height() - 1)
if w._resize_from is None:
pytest.skip("the platform took the resize; nothing to assert by hand")
g0 = w._resize_from[0]
move(g0.x() + 80, g0.y() + 40)
assert w.width() > before.width() and w.height() > before.height(), \
"dragging the bottom-right corner did not grow the window"
assert (w.x(), w.y()) == (before.x(), before.y()), \
"dragging the bottom-right corner moved the window as well"
# …and the type followed, without anybody calling _apply_scale by hand
assert w.dens == w._density(), "the density did not follow the resize"
w.mouseReleaseEvent(None)
"""Tests for the Tidal HL feed: OSC decode + which cells an orbit relates to.
# SPDX-License-Identifier: GPL-3.0-or-later
No Qt, no ALSA, no network: `decode_osc` is a pure function tested against
hand-built bytes — the exact packets Tidal's Stream sends (a `#bundle`
containing a `/play` message whose arguments are name/value runs) and a couple
of shapes it must survive (bare message, garbage, empty datagram).
The cell relation is tested against `lcxl_grid` itself, so the test dies the
day the grid changes shape instead of lying about it.
"""
import struct
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import oscfeed # noqa: E402
import sys as _sys # noqa: E402
_tools = str(Path(__file__).resolve().parent.parent.parent)
if _tools not in _sys.path:
_sys.path.insert(0, _tools)
import lcxl_grid as grid # noqa: E402 lives in tools/, like midiviz's own import
def _osc_msg(addr: str, pairs: list[tuple[str, int]]) -> bytes:
"""Address + typetags + (string, int) pair args, padded the way OSC does.
A pair is: name padded to 4 (so 'orbit' → 8 bytes) + a 4-byte int."""
msg = addr.encode() + b"\0"
msg += b"\0" * ((4 - len(msg) % 4) % 4)
tags = "," + "si" * len(pairs) # (string, int) runs — /play's shape
t = tags.encode() + b"\0"
msg += t + b"\0" * ((4 - len(t) % 4) % 4)
for name, value in pairs:
n = name.encode() + b"\0"
n += b"\0" * ((4 - len(n) % 4) % 4)
msg += n + struct.pack(">i", value)
return msg
def _bundle(*elements: bytes) -> bytes:
out = b"#bundle\0" + b"\0" * 8 # timetag zero
for el in elements:
out += struct.pack(">i", len(el)) + el
out += b"\0" * ((4 - len(out) % 4) % 4)
return out
def _named_pair(name: str, value: int) -> bytes:
n = name.encode() + b"\0"
n += b"\0" * ((4 - len(n) % 4) % 4)
return n + struct.pack(">i", value)
def test_decode_play_bundle_finds_the_orbit():
# d4 → Tidal says orbit: 3; midiviz speaks d-numbers.
data = _bundle(_osc_msg("/play", [("orbit", 3)]))
msgs = oscfeed.decode_osc(data)
assert len(msgs) == 1
assert msgs[0]["addr"] == "/play"
assert oscfeed.play_orbit(msgs[0]) == 4
def test_decode_bare_message_and_named_args():
data = _osc_msg("/play", [("orbit", 0), ("gain", 1)])
msgs = oscfeed.decode_osc(data)
assert oscfeed.play_orbit(msgs[0]) == 1
assert msgs[0]["args"]["gain"] == 1
def test_non_play_and_garbage_yield_nothing():
assert oscfeed.play_orbit({"addr": "/hush", "args": {}}) is None
assert oscfeed.decode_osc(b"") == []
assert oscfeed.decode_osc(b"\x01\x02\x03") == [] # must not raise
def test_orbit_bounds():
# orbit 14 (0-based 13) is the rig's last; anything past is not ours.
data = _bundle(_osc_msg("/play", [("orbit", 13)]))
assert oscfeed.play_orbit(oscfeed.decode_osc(data)[0]) == 14
data = _bundle(_osc_msg("/play", [("orbit", 99)]))
assert oscfeed.play_orbit(oscfeed.decode_osc(data)[0]) is None
# ── the relation: which cells does a trigger light ─────────────────────────
def _hl_cells(orbit):
"""The widget's relation, re-derived the same way — tested against the
grid's own tables rather than against a copy of the widget's cache."""
ccs = set(grid.orbit_home(orbit).values())
for role, fam_of in (("family_filter", grid.filter_family),
("family_mute", grid.mute_family)):
n = fam_of(orbit)
ccs |= {cc for cc, (r, who) in grid.CC_ROLE.items()
if r == role and who == n}
return ccs
def test_d1_trigger_lights_its_column_and_both_families():
# d1 (the kick): its own fx/level/gate cells, plus C1 (all-percs filter)
# and F1 (kick-alone mute) — the two family controls that act on it.
cells = {_: grid.CC_TO_CELL.get(_) for _ in _hl_cells(1)}
assert cells[grid.CELL_TO_CC[("C", 1)]] == ("C", 1) # gF1, the perc filter
assert cells[grid.CELL_TO_CC[("F", 1)]] == ("F", 1) # gM1, the kick mute
for row, col in (("B", 1), ("D", 1), ("E", 1)): # its own column
assert (row, col) in cells.values()
def test_every_d_orbit_maps_to_at_least_one_control():
# An orbit with NO related cells would make the HL feed a no-op that
# still LOOKS wired — the worst failure shape. d1-d12 own a full column
# plus two family controls; d13/d14 (the 14-orbit boot's tail) own only
# their family bloc, which is still one honest thing to show.
for o in range(1, 15):
assert len(_hl_cells(o)) >= 1, f"d{o} has no related controls"
for o in range(1, 13):
assert len(_hl_cells(o)) >= 3, f"d{o} has too few related controls"
def test_widget_relation_matches_grid_derivation():
"""The widget caches `_hl_cells` — the cache must never drift from a fresh
derivation, which is the same two-copies-one-truth lesson the port
preference already taught."""
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import midiviz as V
# The method hangs off the widget class; derive it without a Qt app.
cls = None
for obj in vars(V).values():
if isinstance(obj, type) and hasattr(obj, "_hl_cells"):
cls = obj
break
if cls is None:
return
holder = object.__new__(cls)
holder._hl_cells_cache = {}
for o in (1, 4, 7, 11):
assert set(holder._hl_cells(o)) == _hl_cells(o)
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
<rect width="128" height="128" rx="28" fill="#0a0a0a"/>
<g fill="none" stroke-linecap="round">
<path d="M10 78 Q 26 52 42 78 T 74 78 T 106 78 T 138 78"
stroke="#7c5cff" stroke-width="6" opacity="0.55"/>
<path d="M10 62 Q 26 34 42 62 T 74 62 T 106 62 T 138 62"
stroke="#d900ff" stroke-width="8"/>
</g>
</svg>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment