Full Code of markjfine/nrsc5-dui for AI

master 81f4822601ba cached
12 files
755.0 KB
150.5k tokens
188 symbols
1 requests
Download .txt
Showing preview only (775K chars total). Download the full file or copy to clipboard to get everything.
Repository: markjfine/nrsc5-dui
Branch: master
Commit: 81f4822601ba
Files: 12
Total size: 755.0 KB

Directory structure:
gitextract_phgrdy1q/

├── .gitignore
├── LICENSE
├── MSYS2/
│   ├── .gitignore
│   └── nrsc5-dui-msys2.py
├── README.md
├── nrsc5-dui.py
├── res/
│   ├── entryForm.glade
│   ├── mainForm-narrow.glade
│   ├── mainForm-wide.glade
│   ├── mainForm.glade
│   └── mapForm.glade
└── setup.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
**/._*
**/.DS_Store
*.txt
*.log
HERE*
here.zip
aas/**
cfg/**
cfg/config.json
cfg/stationLogos.json
map/**
linux_binary
macOS_binary



================================================
FILE: LICENSE
================================================
                    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>.


================================================
FILE: MSYS2/.gitignore
================================================



================================================
FILE: MSYS2/nrsc5-dui-msys2.py
================================================
#!/usr/bin/env python3
#!/usr/bin/python3
# -*- coding: utf-8 -*-

#    NRSC5 DUI - A graphical interface for nrsc5
#    Copyright (C) 2017-2019  Cody Nybo & Clayton Smith, 2019 zefie, 2021-26 Mark J. Fine
#
#    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 <http://www.gnu.org/licenses/>.

#    Updated by zefie for modern nrsc5 ~ 2019
#    Updated and enhanced by markjfine ~ 2021-26
#    Stability and MSYS2 enhancements by ferrellsl ~ 2026

import os, select, sys, shutil, re, json, datetime, numpy, glob, time, platform, io
from subprocess import Popen, PIPE
from threading import Timer, Thread
from dateutil import tz
from PIL import Image, ImageFont, ImageDraw, __version__
import gc

print('Using Pillow v'+__version__)

if (int(__version__[0]) < 9):
    imgLANCZOS = Image.LANCZOS
else:
    imgLANCZOS = Image.Resampling.LANCZOS

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GObject, Gdk, GdkPixbuf, GLib

import urllib3
from OpenSSL import SSL

import musicbrainzngs

# print debug messages to stdout (if debugger is attached)
debugMessages = (sys.gettrace() != None)
debugAutoStart = True

if hasattr(sys, 'frozen'):
    runtimeDir = os.path.dirname(sys.executable)  # for py2exe
else:
    runtimeDir = sys.path[0]

if "NRSC5DUI_DATA" in os.environ:
    userDataDir = os.environ["NRSC5DUI_DATA"]
    os.makedirs(userDataDir, exist_ok=True)
else:
    userDataDir = runtimeDir

aasDir = os.path.join(userDataDir, "aas")  # aas (data from nrsc5) file directory
mapDir = os.path.join(userDataDir, "map")  # map (data we process) file directory
resDir = os.path.join(runtimeDir, "res")   # resource (application dependencies) file directory
cfgDir = os.path.join(userDataDir, "cfg")  # config file directory

class NRSC5_DUI(object):
    def __init__(self):
        global runtimeDir, userDataDir, resDir, imgLANCZOS

        self.windowsOS = False          # save our determination as a var in case we change how we determine.

        self.debugLog("Local path determined as " + runtimeDir)
        self.debugLog("User data base directory: " + userDataDir)

        # Detect MSYS2 environment
        is_msys2 = os.environ.get('MSYSTEM') is not None or 'msys' in sys.platform.lower()
        
        if (platform.system() == 'Windows' and not is_msys2):
            # Native Windows release layout
            self.windowsOS = True
            self.binDir = os.path.join(runtimeDir, "bin")  # windows binaries directory
            self.nrsc5Path = os.path.join(self.binDir,'nrsc5.exe')
        else:
            # Linux/Mac/MSYS2/proper posix
            # if nrsc5 is not in the system path, set the full path here
            arg1 = ""
            if (len(sys.argv[1:]) > 0):
                arg1 = sys.argv[1].strip()
            
            # For MSYS2, try to find nrsc5 in PATH
            if is_msys2:
                import shutil as sh
                nrsc5_in_path = sh.which('nrsc5')
                if nrsc5_in_path:
                    self.nrsc5Path = nrsc5_in_path
                    self.debugLog(f"Found nrsc5 in PATH: {nrsc5_in_path}")
                else:
                    self.nrsc5Path = arg1 + "nrsc5"
            else:
                self.nrsc5Path = arg1 + "nrsc5"
 
        self.debugLog("OS Determination: Windows = {}, MSYS2 = {}".format(self.windowsOS, is_msys2))
        self.debugLog("nrsc5 path: {}".format(self.nrsc5Path))

        self.app_name       = "NRSC5-DUI"
        self.version        = "2.2.6"
        self.web_addr       = "https://github.com/markjfine/nrsc5-dui"
        self.copyright      = "Copyright © 2017-2019 Cody Nybo & Clayton Smith, 2019 zefie, 2021-26 Mark J. Fine"
        musicbrainzngs.set_useragent(self.app_name,self.version,self.web_addr)

        self.width          = 0         # window width
        self.height         = 0         # window height
        self.mapFile        = os.path.join(resDir, "map.png")
        self.defaultSize    = [490,250] # default width,height of main app
        self.nrsc5          = None      # nrsc5 process
        self.nrsc5master    = None      # required for pipe
        self.nrsc5slave     = None      # required for pipe
        self.playerThread   = None      # player thread
        self.playing        = False     # currently playing
        self.statusTimer    = None      # status update timer
        self.imageChanged   = False     # has the album art changed
        self.xhdrChanged    = False     # has the HDDR data changed
        self.nrsc5Args      = []        # arguments for nrsc5
        self.logFile        = None      # nrsc5 log file
        self.lastImage      = ""        # last image file displayed
        self.coverImage     = ""        # cover image to display
        self.id3Changed     = False     # if the track info changed
        self.lastXHDR       = ""        # the last XHDR data received
        self.lastLOT        = ""        # the last LOT received with XHDR
        self.stationStr     = ""        # current station frequency (string)
        self.streamNum      = 0         # current station stream number
        self.nrsc5msg       = ""        # send key command to nrsc5 (streamNum)
        self.update_btns    = True      # whether to update the stream buttons
        self.bookmarks      = []        # station bookmarks
        self.booknames      = ["","","","","","","",""] # station bookmark names
        self.stationLogos   = {}        # station logos
        self.coverMetas     = {}        # cover metadata
        self.bookmarked     = False     # is current station bookmarked
        self.mapViewer      = None      # map viewer window
        self.weatherMaps    = []        # list of current weathermaps sorted by time
        self.waittime       = 10        # time in seconds to wait for file to exist
        self.waitdivider    = 4         # check this many times per second for file
        self.pixbuf         = None      # store image buffer for rescaling on resize
        self.tLat1          = 0.0       # store upper left lat of HERE traffic image
        self.tLat2          = 0.0       # store lower right lat of HERE traffic image
        self.mimeTypes      = {         # as defined by iHeartRadio anyway, defined here for possible future use
            "4F328CA0":["image/png","png"],
            "1E653E9C":["image/jpg","jpg"],
            "BB492AAC":["text/plain","txt"]
        }
        self.mapData        = {
            "mapMode"       : 1,
            "mapTiles"      : [[0,0,0],[0,0,0],[0,0,0]],
            "mapComplete"   : False,
            "weatherTime"   : 0,
            "weatherPos"    : [0,0,0,0],
            "weatherNow"    : "",
            "weatherID"     : "",
            "viewerConfig"  : {
                "mode"           : 1,
                "animate"        : False,
                "scale"          : True,
                "windowPos"      : (0,0),
                "windowSize"     : (764,632),
                "animationSpeed" : 0.5
            }
        }
        self.maxWeatherMaps = 50  # Limit weather map history to prevent unbounded growth

        # Now initialize components in correct order
        self.getControls()              # get controls and windows
        self.set_program_btns()         # set the stream buttons (needs GUI widgets)
        self.initStreamInfo()           # initilize stream info and clear status widgets
        self.initializeData()           # initialize regex patterns and data structures
        self.http = urllib3.PoolManager()
        
        # Now that GUI is set up, load settings and process maps
        self.loadSettings()
        self.proccessWeatherMaps()

    def __del__(self):
        """Destructor to clean up resources and prevent memory leaks"""
        try:
            if hasattr(self, 'http') and self.http is not None:
                self.http.clear()
            if hasattr(self, 'statusTimer') and self.statusTimer is not None:
                self.statusTimer.cancel()
                self.statusTimer = None
        except:
            pass

    def initializeData(self):
        """Initialize regex patterns and data structures"""
        self.slPopup        = None      # entry for external station logo URL
        self.slData = {
        "externalURL"   : ""
        }

        self.ServiceDataType = {
        0 : "Non_Specific",            
        1 : "News",                     
        3 : "Sports",                   
        29 : "Weather",                  
        31 : "Emergency",                
        65 : "Traffic",                  
        66 : "Image Maps",               
        80 : "Text",                     
        256 : "Advertising",              
        257 : "Financial",                
        258 : "Stock Ticker",             
        259 : "Navigation",               
        260 : "Electronic Program Guide", 
        261 : "Audio",                    
        262 : "Private Data Network",     
        263 : "Service Maintenance",      
        264 : "HD Radio System Services", 
        265 : "Audio-Related Objects",       
        511 : "Reserved for Special Tests"               
        }

        self.ProgramType = {
        0 : "None",
        1 : "News",
        2 : "Information",
        3 : "Sports",
        4 : "Talk",
        5 : "Rock",
        6 : "Classic Rock",
        7 : "Adult Hits",
        8 : "Soft Rock",
        9 : "Top 40",
        10 : "Country",
        11 : "Oldies",
        12 : "Soft",
        13 : "Nostalgia",
        14 : "Jazz",
        15 : "Classical",
        16 : "Rhythm and Blues",
        17 : "Soft Rhythm and Blues",
        18 : "Foreign Language",
        19 : "Religious Music",
        20 : "Religious Talk",
        21 : "Personality",
        22 : "Public",
        23 : "College",
        24 : "Spanish Talk",
        25 : "Spanish Music",
        26 : "Hip-Hop",
        29 : "Weather",
        30 : "Emergency Test",
        31 : "Emergency",
        65 : "Traffic",
        76 : "Special Reading Services"
        }

        self.MIMETypes = {
        0x1E653E9C : "JPEG",
        0x2D42AC3E : "NavTeq",
        0x4F328CA0 : "PNG",
        0x4DC66C5A : "HDC",
        0x4EB03469 : "TTN TPEG 2",
        0x52103469 : "TTN TPEG 3",
        0x82F03DFC : "HERE TPEG",
        0xB39EBEB2 : "TTN TPEG 1",
        0xB7F03DFC : "HERE Image",
        0xB81FFAA8 : "Unknown Test",
        0xBB492AAC : "Text",
        0xBE4B7536 : "Primary Image",
        0xD9C72536 : "Station Logo",
        0xEECB55B6 : "HD TMC",
        0xEF042E96 : "TTN STM Weather",
        0xFF8422D7 : "TTN STM Traffic"
        }

        self.pointer_cursor = Gdk.Cursor(Gdk.CursorType.LEFT_PTR)
        #       self.hand_cursor = Gdk.Cursor(Gdk.CursorType.HAND2)

        # set events on info labels
        self.set_tuning_actions(self.btnAudioPrgs0, "btn_prg0", False, False)
        self.set_tuning_actions(self.btnAudioPrgs1, "btn_prg1", False, False)
        self.set_tuning_actions(self.btnAudioPrgs2, "btn_prg2", False, False)
        self.set_tuning_actions(self.btnAudioPrgs3, "btn_prg3", False, False)
        self.set_tuning_actions(self.btnAudioPrgs4, "btn_prg4", False, False)
        self.set_tuning_actions(self.btnAudioPrgs5, "btn_prg5", False, False)
        self.set_tuning_actions(self.btnAudioPrgs6, "btn_prg6", False, False)
        self.set_tuning_actions(self.btnAudioPrgs7, "btn_prg7", False, False)

        self.set_tuning_actions(self.lblAudioPrgs0, "prg0", True, True)
        self.set_tuning_actions(self.lblAudioPrgs1, "prg1", True, True)
        self.set_tuning_actions(self.lblAudioPrgs2, "prg2", True, True)
        self.set_tuning_actions(self.lblAudioPrgs3, "prg3", True, True)
        self.set_tuning_actions(self.lblAudioPrgs4, "prg4", True, True)
        self.set_tuning_actions(self.lblAudioPrgs5, "prg5", True, True)
        self.set_tuning_actions(self.lblAudioPrgs6, "prg6", True, True)
        self.set_tuning_actions(self.lblAudioPrgs7, "prg7", True, True)

        self.set_tuning_actions(self.lblAudioSvcs0, "svc0", True, True)
        self.set_tuning_actions(self.lblAudioSvcs1, "svc1", True, True)
        self.set_tuning_actions(self.lblAudioSvcs2, "svc2", True, True)
        self.set_tuning_actions(self.lblAudioSvcs3, "svc3", True, True)
        self.set_tuning_actions(self.lblAudioSvcs4, "svc4", True, True)
        self.set_tuning_actions(self.lblAudioSvcs5, "svc5", True, True)
        self.set_tuning_actions(self.lblAudioSvcs6, "svc6", True, True)
        self.set_tuning_actions(self.lblAudioSvcs7, "svc7", True, True)

        # setup bookmarks listview
        nameRenderer = Gtk.CellRendererText()
        nameRenderer.set_property("editable", True)
        nameRenderer.connect("edited", self.on_bookmarkNameEdited)
        
        colStation = Gtk.TreeViewColumn("Station", Gtk.CellRendererText(), text=0)
        colName    = Gtk.TreeViewColumn("Name", nameRenderer, text=1)

        colStation.set_resizable(True)
        colStation.set_sort_column_id(2)
        colName.set_resizable(True)
        colName.set_sort_column_id(1)
        
        self.lvBookmarks.append_column(colStation)
        self.lvBookmarks.append_column(colName)
        
        # regex for getting nrsc5 output
        self.regex = [
        re.compile("^[0-9:]{8,8} Station name: (.*)$"),                                                    #  0 match station name
        re.compile("^[0-9:]{8,8} Station location: (-?[0-9.]+), (-?[0-9.]+), ([0-9]+)m$"),                 #  1 match station location
        re.compile("^[0-9:]{8,8} Slogan: (.*)$"),                                                          #  2 match station slogan
        re.compile("^[0-9:]{8,8} Audio bit rate: (.*) kbps$"),                                             #  3 match audio bit rate
        re.compile("^[0-9:]{8,8} Title: (.*)$"),                                                           #  4 match title
        re.compile("^[0-9:]{8,8} Artist: (.*)$"),                                                          #  5 match artist
        re.compile("^[0-9:]{8,8} Album: (.*)$"),                                                           #  6 match album
        re.compile("^[0-9:]{8,8} LOT file: port=([0-9]+) lot=([0-9]+) name=(.*[.](?:jpg|jpeg|png|txt)) size=([0-9]+) mime=([a-zA-Z0-9_]+).*$"), #  7 match file (album art, maps, weather info)
        re.compile("^[0-9:]{8,8} MER: (-?[0-9]+[.][0-9]+) dB [(]lower[)], (-?[0-9]+[.][0-9]+) dB [(]upper[)]$"), #  8 match MER
        re.compile("^[0-9:]{8,8} BER: (0[.][0-9]+), avg: (0[.][0-9]+), min: (0[.][0-9]+), max: (0[.][0-9]+)$"), #  9 match BER
        re.compile("^[0-9:]{8,8} Best gain: (.*) dB,.*$"),                                                 # 10 match gain
        re.compile("^[0-9:]{8,8} SIG Service: type=(.*) number=(.*) name=(.*)$"),                          # 11 match stream
        re.compile("^[0-9:]{8,8} .*Data component:.* id=([0-9]+).* port=([0-9]+).* service_data_type=([0-9]+) .*$"), # 12 match port (and data_service_type)
        re.compile("^[0-9:]{8,8} XHDR: (.*) ([0-9A-Fa-f]{8}) (.*)$"),                                      # 13 match xhdr tag
        re.compile("^[0-9:]{8,8} Unique file identifier: PPC;07; ([a-zA-Z0-9_.]+).*$"),                    # 14 match unique file id
        re.compile("^[0-9:]{8,8} Genre: (.*)$"),                                                           # 15 match genre
        re.compile("^[0-9:]{8,8} Message: (.*)$"),                                                         # 16 match message
        re.compile("^[0-9:]{8,8} Alert: (.*)$"),                                                           # 17 match alert
        re.compile("^[0-9:]{8,8} .*Audio component:.* id=([0-9]+).* port=([0-9]+).* type=([0-9]+) .*$"),   # 18 match port (and type)
        re.compile("^[0-9:]{8,8} Synchronized$"),                                                          # 19 synchronized
        re.compile("^[0-9:]{8,8} Lost synchronization$"),                                                  # 20 lost synch
        re.compile("^[0-9:]{8,8} Lost device$"),                                                           # 21 lost device
        re.compile("^[0-9:]{8,8} Open device failed.$"),                                                   # 22 No device
        re.compile("^[0-9:]{8,8} HERE Image: type=([A-Z]{7,7}), seq=([0-9]+), n1=([0-9]+), n2=([0-9]+), time=(.*), lat1=(-?[0-9.]+), lon1=(-?[0-9.]+), lat2=(-?[0-9.]+), lon2=(-?[0-9.]+), name=(.*[.](?:jpg|jpeg|png)), size=([0-9]+)$"), # 23 Navteq/HERE image info
        re.compile("^[0-9:]{8,8} Packet data: port=([0-9]+).* mime=([a-zA-Z0-9_]+) size=([0-9]+)$")        # 24 Navteq/HERE packet info
        ]
        
        # Use PIPE for stdin (works on all platforms)
        self.nrsc5master = None  # Not used with PIPE
        self.nrsc5slave = PIPE   # Will use stdin PIPE


    def set_tuning_actions(self, widget, name, has_win, set_curs):
        widget.set_property("name",name)
        widget.set_sensitive(False)
        if has_win:
            widget.set_has_window(True)
        widget.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        widget.connect("button-press-event", self.on_program_select)
        if set_curs:
            widget.add_events(Gdk.EventMask.ENTER_NOTIFY_MASK)
            widget.connect("enter-notify-event", self.on_enter_set_cursor)

    def on_enter_set_cursor(self, widget, event):
        if (widget.get_label() != ""):
            widget.get_window().set_cursor(self.default)

    def on_cbCovers_clicked(self, btn):
        dlCoversSet = self.cbCovers.get_active()
        self.lblCoverIncl.set_sensitive(dlCoversSet)
        self.cbCoverIncl.set_sensitive(dlCoversSet)
        self.lblExtend.set_sensitive(dlCoversSet)
        self.cbExtend.set_sensitive(dlCoversSet)

    def restart_program(self):
        python = sys.executable
        os.execl(python, python, *sys.argv)

    def confirm_dialog(self, title, message):
        dialog = Gtk.MessageDialog(parent=self.mainWindow, flags=0, message_type=Gtk.MessageType.WARNING, buttons=Gtk.ButtonsType.YES_NO, text=title)
        dialog.format_secondary_text(message)
        dialog.set_default_response(Gtk.ResponseType.YES)
        response = dialog.run()
        dialog.destroy()
        return (response == Gtk.ResponseType.YES)

    def on_cbxAspect_changed(self, btn):
        screenAspect = self.cbxAspect.get_active_text()
        if (screenAspect == "narrow") or (screenAspect == "wide"):
            mainFile = os.path.join(resDir, "mainForm.glade")
            gladeFile = os.path.join(resDir, "mainForm-"+screenAspect+".glade")
            if (os.path.isfile(gladeFile)):
                shutil.copy(gladeFile,mainFile)
                title = "Aspect Changed"
                message = "You have change the display layout to "+screenAspect+". This change will not happen until the application is restarted. Would you like to restart it now?"
                if (self.confirm_dialog(title,message)):
                    self.restart_program()
                    
    def on_cbxSDRRadio_changed(self, btn):
        useSDRPlay = (self.cbxSDRRadio.get_active_text() == "SDRPlay")
        self.lblSdrPlaySer.set_visible(useSDRPlay)
        self.txtSDRPlaySer.set_visible(useSDRPlay)
        self.txtSDRPlaySer.set_can_focus(useSDRPlay)
        self.label14d.set_visible(useSDRPlay)
        self.lblSDRPlayAnt.set_visible(useSDRPlay)
        self.cbxSDRPlayAnt.set_visible(useSDRPlay)
        self.cbxSDRPlayAnt.set_can_focus(useSDRPlay)
        self.label14a.set_visible(useSDRPlay)
        self.lblRTL.set_visible(not(useSDRPlay))
        self.spinRTL.set_visible(not(useSDRPlay))
        self.spinRTL.set_can_focus(not(useSDRPlay))
        self.label14b.set_visible(useSDRPlay)
        self.lblDevIP.set_visible(not(useSDRPlay))
        self.txtDevIP.set_visible(not(useSDRPlay))
        self.txtDevIP.set_can_focus(not(useSDRPlay))
        self.cbDevIP.set_visible(not(useSDRPlay))
        self.cbDevIP.set_can_focus(not(useSDRPlay))

    def img_to_pixbuf(self,img):
        """convert PIL.Image to GdkPixbuf.Pixbuf"""
        data = GLib.Bytes.new(img.tobytes())
        return GdkPixbuf.Pixbuf.new_from_bytes(data, GdkPixbuf.Colorspace.RGB, 'A' in img.getbands(),8, img.width, img.height, len(img.getbands())*img.width)

    def did_resize(self):
        result = False
        width, height = self.mainWindow.get_size()
        if (self.width != width) or (self.height != height):
            self.width = width
            self.height = height
            result = True
        return result

    def on_cover_resize(self, container):
        global mapDir, imgLANCZOS
        if (self.did_resize()):
            self.showArtwork(self.coverImage)

            img_size = min(self.alignmentMap.get_allocated_height(), self.alignmentMap.get_allocated_width()) - 12           
            if (self.mapData["mapMode"] == 0):
                map_file = os.path.join(mapDir, "TrafficMap.png")
                if os.path.isfile(map_file):
                    with Image.open(map_file) as img:
                        map_img = img.resize((img_size, img_size), imgLANCZOS)
                    self.imgMap.set_from_pixbuf(self.img_to_pixbuf(map_img))
                else:
                    self.imgMap.set_from_icon_name("MISSING_IMAGE", Gtk.IconSize.DIALOG)
            elif (self.mapData["mapMode"] == 1):
                if os.path.isfile(self.mapData["weatherNow"]):
                    with Image.open(self.mapData["weatherNow"]) as img:
                        map_img = img.resize((img_size, img_size), imgLANCZOS)
                    self.imgMap.set_from_pixbuf(self.img_to_pixbuf(map_img))
                else:
                    self.imgMap.set_from_icon_name("MISSING_IMAGE", Gtk.IconSize.DIALOG)

    def id3_did_change(self):
        oldTitle = self.txtTitle.get_label().strip()
        oldArtist = self.txtArtist.get_label().strip()
        newTitle = self.streamInfo["Title"].strip()
        newArtist = self.streamInfo["Artist"].strip()
        return ((newArtist != oldArtist) and (newTitle != oldTitle))

    def fix_artist(self):
        newArtist = self.streamInfo["Artist"]
        if ("/" in newArtist):
            m = re.search(r"/",newArtist)
            if (m.start() > -1):
                newArtist = newArtist[:m.start()].strip()
        return newArtist

    def check_value(self,arg,group,default):
        result = default
        if(arg in group):
            result = group[arg]
        return result

    def check_terms(self,inStr,terms):
        result = False
        for term in terms:
            result=(term in inStr)
            if result:
                break
        return result
  
    def check_musicbrainz_cover(self,inID):
        result = False
        imageList = None

        try:
            imageList = musicbrainzngs.get_image_list(inID)
        except:
            print("MusicBrainz image list retrieval error for id "+inID)

        if (imageList is not None) and ('images' in imageList):
            for (idx, image) in enumerate(imageList['images']):
                imgTypes = self.check_value('types', image, None)
                imgApproved = self.check_value('approved', image, "False")
                result = ('Front' in imgTypes) and imgApproved
                if (result):
                    break
        return result

    def save_musicbrainz_cover(self,inID,saveStr):
        imgData = None
        result = False

        try:
            imgData = musicbrainzngs.get_image_front(inID, size="500")
        except:
            print("MusicBrainz image retrieval error for id "+inID)

        if (imgData is not None) and (len(imgData) > 0):
            dataBytes = io.BytesIO(imgData)
            with Image.open(dataBytes) as img_temp:
                imgCvr = img_temp.copy()  # Make a copy to persist after close
            imgCvr.save(saveStr)
            result = True
        return result

    def get_cover_image_online(self):
        global aasDir
        got_cover = False
        albumExclude = ['hitzone','now that’s what i call music']

        # only care about the first artist listed if separated by slashes
        newArtist = self.fix_artist().replace("'","’")

        setExtend = (self.cbExtend.get_sensitive() and self.cbExtend.get_active())
        searchArtist = newArtist
        newTitle = self.streamInfo["Title"].replace("'","’")
        baseStr = str(newArtist+" - "+self.streamInfo["Title"]).replace(" ","_").replace("/","_").replace(":","_")+".jpg"
        saveStr = os.path.join(aasDir, baseStr)

        if ((newArtist=="") and (newTitle=="")):
            self.displayLogo()
            self.streamInfo['Album']=""
            self.streamInfo['Genre']=""
            return

        # does it already exist?
        if (os.path.isfile(saveStr)):
            self.coverImage = saveStr
            if (baseStr in self.coverMetas):
                self.streamInfo['Album'] = self.coverMetas[baseStr][2]
                self.streamInfo['Genre'] = self.coverMetas[baseStr][3]

        # if not, get it from MusicBrainz
        else:
            try:
                imgSaved = False
                i = 1

                while (not imgSaved):
                    setStrict = (i in [1,3,5,7])
                    setType = ''
                    if (i in [1,2,3,4]):
                        setType = 'Album'
                    setStatus = ''
                    if (i in [1,2,5,6]):
                        setStatus = 'Official'

                    result = None
    
                    try:
                        result = musicbrainzngs.search_recordings(strict=setStrict, artist=searchArtist, recording=newTitle, type=setType, status=setStatus)
                    except:
                        print("MusicBrainz recording search error")
                        print("iteration =",i,".")
                        print("imgSaved =",imgSaved,".")
                        print("strict =",setStrict,".")
                        print("artist =",searchArtist,".")
                        print("recording =",newTitle,".")
                        print("type =",setType,".")
                        print("status =",setStatus,".")
    
                    if (result is not None) and ('recording-list' in result) and (len(result['recording-list']) != 0):    
                        # loop through the list until you get a match
                        for (idx, release) in enumerate(result['recording-list']):
                            resultID = self.check_value('id',release,"")
                            resultScore = self.check_value('ext:score',release,"0")
                            resultArtist = self.check_value('artist-credit-phrase',release,"")
                            resultTitle = self.check_value('title',release,"")
                            resultGenre = self.check_value('name',self.check_value('tag-list',release,""),"")
                            scoreMatch = (int(resultScore) > 90)
                            artistMatch = (newArtist.lower() in resultArtist.lower())
                            titleMatch = (newTitle.lower() in resultTitle.lower())
                            recordingMatch = (artistMatch and titleMatch and scoreMatch)
    
                            # don't bother dealing with releases if artist, title and score don't match
                            resultStatus = ""
                            resultType = ""
                            resultAlbum = ""
                            resultArtist2 = ""
                            releaseMatch = False
                            imageMatch = False
                            if recordingMatch and ('release-list' in release):
                                for (idx2, release2) in enumerate(release['release-list']):
                                    imageMatch = False
                                    resultID = self.check_value('id',release2,"")
                                    resultStatus = self.check_value('status',release2,"Official")
                                    resultType = self.check_value('type',self.check_value('release-group',release2,""),"")
                                    resultAlbum = self.check_value('title',release2,"")
                                    resultArtist2 = self.check_value('artist-credit-phrase',release2,"")
                                    typeMatch = (resultType in ['Single','Album','EP'])
                                    statusMatch = (resultStatus == 'Official')
                                    albumMatch = (not self.check_terms(resultAlbum, albumExclude))
                                    artistMatch2 = (not ('Various' in resultArtist2))
                                    releaseMatch = (artistMatch2 and albumMatch and typeMatch and statusMatch)
                                    # don't bother checking for covers unless album, type, and status match
                                    if releaseMatch:
                                        imageMatch = self.check_musicbrainz_cover(resultID)
                                    if (releaseMatch and imageMatch and ((idx2+1) < len(release['release-list']))):
                                        break
    
                            if (recordingMatch and releaseMatch and imageMatch):
     
                                # got a full match, now get the cover art
                                if self.save_musicbrainz_cover(resultID,saveStr):
                                    self.coverImage = saveStr
                                    imgSaved = True
                                    self.streamInfo['Album']=resultAlbum
                                    self.streamInfo['Genre']=resultGenre
                                    self.coverMetas[baseStr] = [self.streamInfo["Title"],self.streamInfo["Artist"],self.streamInfo["Album"],self.streamInfo["Genre"]]

                            if (imgSaved) and ((idx+1) < len(result['recording-list'])) or (not scoreMatch):
                                break

                    i = i + 1
                    # if we got an image or Strict was false the first time through, there's no need to run through it again
                    if (imgSaved) or (i == 9) or ((not setExtend) and (i == 2)):
                        break

                # If no match use the station logo if there is one
                if (not imgSaved):
                    self.coverImage = os.path.join(aasDir, self.stationLogos[self.stationStr][self.streamNum])
                    self.streamInfo['Album']=""
                    self.streamInfo['Genre']=""
            except:
                print("general error in the musicbrainz routine")

        # now display it by simulating a window resize
        # Use GLib.idle_add because this might be called from a background thread
        GLib.idle_add(self.showArtwork, self.coverImage)

    def showArtwork(self, art):
        if (art != "") and (art[-5:] != "/aas/"):
            img_size = min(self.alignmentCover.get_allocated_height(), self.alignmentCover.get_allocated_width()) - 12
            self.pixbuf = GdkPixbuf.Pixbuf.new_from_file(art)
            self.pixbuf = self.pixbuf.scale_simple(img_size, img_size, GdkPixbuf.InterpType.BILINEAR)
            self.imgCover.set_from_pixbuf(self.pixbuf)

    def displayLogo(self):
        global aasDir
        if (self.stationStr in self.stationLogos):
            # show station logo if it's cached
            logo = os.path.join(aasDir, self.stationLogos[self.stationStr][self.streamNum])
            if (os.path.isfile(logo)):
                self.streamInfo["Logo"] = self.stationLogos[self.stationStr][self.streamNum]
                self.coverImage = logo
                self.showArtwork(logo)
        else:
            # add entry in database for the station if it doesn't exist
            self.stationLogos[self.stationStr] = ["", "", "", "", "", "", "", ""]

    def service_data_type_name(self, type):
        for key, value in self.ServiceDataType.items():
            if (key == type):
               return value

    def program_type_name(self, type):
        for key, value in self.ProgramType.items():
            if (key == type):
               return value

    def handle_window_resize(self):
        if (self.pixbuf != None):
            desired_size = min(self.alignmentCover.get_allocated_height(), self.alignmentCover.get_allocated_width()) - 12
            self.pixbuf = self.pixbuf.scale_simple(desired_size, desired_size, GdkPixbuf.InterpType.BILINEAR)
            self.imgCover.set_from_pixbuf(self.pixbuf)

    def on_window_resized(self,window):
        self.handle_window_resize()

    def on_btnPlay_clicked(self, btn):
        global aasDir
        # start playback
        if (not self.playing):

            self.nrsc5Args = [self.nrsc5Path]
            
            # update all of the spin buttons to prevent the text from sticking 
            self.spinFreq.update()
            self.spinGain.update()
            self.spinPPM.update()
            self.spinRTL.update()
            
            useSDRPlay = (self.cbxSDRRadio.get_active_text() == "SDRPlay")
            
            # enable aas output if temp dir was created
            if (aasDir is not None):
                self.nrsc5Args.append("--dump-aas-files")
                self.nrsc5Args.append(aasDir)
            
            # set IP address if rtl_tcp is used
            if (not(useSDRPlay)) and (self.cbDevIP.get_active()):
                self.nrsc5Args.append("-H")
                self.nrsc5Args.append(self.txtDevIP.get_text())
            
            # set gain if auto gain is not selected
            if (not self.cbAutoGain.get_active()):
                self.streamInfo["Gain"] = round(self.spinGain.get_value(),2)
                self.nrsc5Args.append("-g")
                self.nrsc5Args.append(str(self.streamInfo["Gain"]))
            
            # set ppm error if not zero
            if (self.spinPPM.get_value() != 0):
                self.nrsc5Args.append("-p")
                self.nrsc5Args.append(str(int(self.spinPPM.get_value())))
            
            # set rtl device number if not zero
            if (not(useSDRPlay)) and (self.spinRTL.get_value() != 0):
                self.nrsc5Args.append("-d")
                self.nrsc5Args.append(str(int(self.spinRTL.get_value())))

            # set log level to 2 if SDRPLay enabled
            if (useSDRPlay):
                self.nrsc5Args.append("-l2")
            
            # set SDRPlay serial number if not blank
            if (useSDRPlay) and (self.txtSDRPlaySer.get_text() != ""):
                self.nrsc5Args.append("-d")
                self.nrsc5Args.append(self.txtSDRPlaySer.get_text())
            
            # set SDRPlay antenna if not blank
            if (useSDRPlay) and (self.cbxSDRPlayAnt.get_active_text() != ""):
                if self.cbxSDRPlayAnt.get_active_text() != "Auto":
                    self.nrsc5Args.append("-A")
                    self.nrsc5Args.append("Antenna "+self.cbxSDRPlayAnt.get_active_text())
            
            # set frequency and stream
            self.nrsc5Args.append(str(self.spinFreq.get_value()))
            self.nrsc5Args.append(str(int(self.streamNum)))

            # to emulate reading an IQ file use two lines below, instead of the above:
            # (make sure to set the frequency spinner to the station's frequency before hitting play)
            # FIXME - Create interface and option so these things don't have to be hardcoded
            #self.nrsc5Args.append("-r")
            #self.nrsc5Args.append("/Users/mark/downloads/detroit-1043-HERE.cu8")
            #self.nrsc5Args.append("0")
            #self.spinFreq.set_value(104.3)

            print(self.nrsc5Args)

            # start the timer
            self.statusTimer = Timer(1, self.checkStatus)
            self.statusTimer.start()
            
            # disable the controls
            self.spinFreq.set_sensitive(False)
            self.cbxAspect.set_sensitive(False)
            self.cbxSDRRadio.set_sensitive(False)
            self.spinGain.set_sensitive(False)
            self.spinPPM.set_sensitive(False)
            self.spinRTL.set_sensitive(False)
            self.txtDevIP.set_sensitive(False)
            self.cbDevIP.set_sensitive(False)
            self.txtSDRPlaySer.set_sensitive(False)
            self.cbxSDRPlayAnt.set_sensitive(False)
            self.btnPlay.set_sensitive(False)
            self.btnStop.set_sensitive(True)
            self.cbAutoGain.set_sensitive(False)
            self.playing = True
            self.lastXHDR = ""
            self.lastLOT = ""

            # start the player thread
            self.playerThread = Thread(target=self.play)
            self.playerThread.start()
            
            self.stationStr = str(self.spinFreq.get_value())
            self.displayLogo()         

            self.update_bookmark_buttons()
    
    def update_bookmark_buttons(self):
        # check if station is bookmarked
        self.bookmarked = False
        freq = int((self.spinFreq.get_value()+0.005)*100) + int(self.streamNum + 1)
        for b in self.bookmarks:
            if (b[2] == freq):
                self.bookmarked = True
                break

        self.get_bookmark_names()

        self.btnBookmark.set_sensitive(not self.bookmarked)
        if (self.notebookMain.get_current_page() == 3):
            self.btnDelete.set_sensitive(self.bookmarked)
        else:
            self.btnDelete.set_sensitive(False)
            
    def get_bookmark_names(self):
        self.booknames = ["","","","","","","",""]
        freq = str(int((self.spinFreq.get_value()+0.005)*10))
        for b in self.bookmarks:
            test = str(b[2])
            if (test[:-1] == freq):
                self.booknames[int(test[-1])-1] = b[1]

    def on_btnStop_clicked(self, btn):
        # stop playback
        if (self.playing):
            self.playing = False
            
            # shutdown nrsc5 
            if (self.nrsc5 is not None):
                try:
                    # Check if process is still running before trying to terminate
                    if self.nrsc5.poll() is None:
                        self.nrsc5.terminate()
                        # Give it a moment to terminate gracefully
                        time.sleep(0.1)
                        if self.nrsc5.poll() is None:
                            # Still running, force kill
                            self.nrsc5.kill()
                except:
                    pass  # Process may have already died
            
            if (self.playerThread is not None) and (btn is not None):
                self.playerThread.join(1)
            
            # stop timer
            self.statusTimer.cancel()
            self.statusTimer = None
            
            # enable controls
            if (not self.cbAutoGain.get_active()):
                self.spinGain.set_sensitive(True)
            self.spinFreq.set_sensitive(True)
            self.cbxAspect.set_sensitive(True)
            self.cbxSDRRadio.set_sensitive(True)
            self.spinPPM.set_sensitive(True)
            self.spinRTL.set_sensitive(True)
            self.txtDevIP.set_sensitive(True)
            self.cbDevIP.set_sensitive(True)
            self.txtSDRPlaySer.set_sensitive(True)
            self.cbxSDRPlayAnt.set_sensitive(True)
            self.btnPlay.set_sensitive(True)
            self.btnStop.set_sensitive(False)
            self.btnBookmark.set_sensitive(False)
            self.cbAutoGain.set_sensitive(True)
            
            # clear stream info
            self.initStreamInfo()
            
            self.btnBookmark.set_sensitive(False)
            if (self.notebookMain.get_current_page() != 3):
                self.btnDelete.set_sensitive(False)

    def on_btnBookmark_clicked(self, btn):         
        # pack frequency and channel number into one int
        freq = int((self.spinFreq.get_value()+0.005)*100) + int(self.streamNum + 1)
        
        # create bookmark
        bookmark = [
            "{:4.1f}-{:1.0f}".format(self.spinFreq.get_value(), self.streamNum + 1),
            self.streamInfo["Callsign"],
            freq
        ]
        self.bookmarked = True                  # mark as bookmarked
        self.bookmarks.append(bookmark)         # store bookmark in array
        self.lsBookmarks.append(bookmark)       # add bookmark to listview
        self.btnBookmark.set_sensitive(False)   # disable bookmark button
        
        if (self.notebookMain.get_current_page() != 3):
            self.btnDelete.set_sensitive(True)  # enable delete button

        self.get_bookmark_names()

    def on_btnDelete_clicked(self, btn):
        # select current station if not on bookmarks page
        if (self.notebookMain.get_current_page() != 3):
            station = int((self.spinFreq.get_value()+0.005)*100) + int(self.streamNum + 1)
            for i in range(0, len(self.lsBookmarks)):
                if (self.lsBookmarks[i][2] == station):            
                    self.lvBookmarks.set_cursor(i)
                    break
        
        # get station of selected row
        (model, iter) = self.lvBookmarks.get_selection().get_selected()
        station = model.get_value(iter, 2)
        
        # remove row
        model.remove(iter)
        
        # remove bookmark
        for i in range(0, len(self.bookmarks)):
            if (self.bookmarks[i][2] == station):
                self.bookmarks.pop(i)
                break
        
        if (self.notebookMain.get_current_page() != 3 and self.playing):
            self.btnBookmark.set_sensitive(True)
            self.bookmarked = False

        self.get_bookmark_names()

    def on_btnAbout_activate(self, btn):
        global resDir
        # sets up and displays about dialog
        if self.about_dialog:
            self.about_dialog.present()
            return

        authors = [
            "Cody Nybo <cmnybo@gmail.com>",
            "Clayton Smith <argilo@gmail.com>",
            "zefie <zefie@zefie.net>",
            "Mark J. Fine <mark.fine@fineware-swl.com>",
            "Stephen Ferrell <sferrellblue@yahoo.com>"
        ]

        license = """
        NRSC5 DUI - A second-generation graphical interface for nrsc5
        Copyright (C) 2017-2019  Cody Nybo & Clayton Smith, 2019 zefie, 2021-26 Mark J. Fine
        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 <http://www.gnu.org/licenses/>."""

        about_dialog = Gtk.AboutDialog()
        about_dialog.set_transient_for(self.mainWindow)
        about_dialog.set_destroy_with_parent(True)
        about_dialog.set_name(self.app_name)
        about_dialog.set_program_name(self.app_name)
        about_dialog.set_version(self.version)
        about_dialog.set_copyright(self.copyright)
        about_dialog.set_website(self.web_addr)
        about_dialog.set_comments("A second-generation graphical interface for nrsc5.")
        about_dialog.set_authors(authors)
        about_dialog.set_license(license)
        about_dialog.set_logo(GdkPixbuf.Pixbuf.new_from_file(os.path.join(resDir,"logo.png")))

        # callbacks for destroying the dialog
        def close(dialog, response, editor):
            editor.about_dialog = None
            dialog.destroy()

        def delete_event(dialog, event, editor):
            editor.about_dialog = None
            return True

        about_dialog.connect("response", close, self)
        about_dialog.connect("delete-event", delete_event, self)

        self.about_dialog = about_dialog
        about_dialog.show()

    def on_stream_changed(self):
        self.lastXHDR = ""
        self.lastLOT = ""
        self.streamInfo["Title"] = ""
        self.streamInfo["Album"] = ""
        self.streamInfo["Artist"] = ""
        self.streamInfo["Genre"] = ""
        self.streamInfo["Cover"] = ""
        self.streamInfo["Logo"] = ""
        self.streamInfo["Bitrate"] = 0
        self.set_program_btns()
        if self.playing:
            # Instead of sending to stdin (which doesn't work without PTY),
            # restart nrsc5 with the new stream number
            print(f"[STREAM] Restarting nrsc5 on stream {self.streamNum}")
            self.restart_nrsc5_with_stream(self.streamNum)
            self.displayLogo()
        self.update_bookmark_buttons()
    
    def restart_nrsc5_with_stream(self, stream_num):
        """Restart nrsc5 with a different stream number (Windows-compatible)"""
        if self.nrsc5 is not None:
            try:
                # Terminate the current nrsc5 process
                self.nrsc5.terminate()
                self.nrsc5.wait(timeout=2)
            except:
                # Force kill if it doesn't terminate
                try:
                    self.nrsc5.kill()
                except:
                    pass
        
        # Update the args with the new stream number
        # The stream number is the last argument
        self.nrsc5Args[-1] = str(int(stream_num))
        print(f"[STREAM] New args: {self.nrsc5Args}")
        
        # Start nrsc5 again with the new stream
        FNULL = open(os.devnull, 'w')
        self.nrsc5 = Popen(self.nrsc5Args, shell=False, stdin=PIPE, stdout=FNULL, stderr=PIPE, 
                          universal_newlines=False, bufsize=0)

    def set_program_btns(self):
        self.btnAudioPrgs0.set_active(self.update_btns and self.streamNum == 0)
        self.btnAudioPrgs1.set_active(self.update_btns and self.streamNum == 1)
        self.btnAudioPrgs2.set_active(self.update_btns and self.streamNum == 2)
        self.btnAudioPrgs3.set_active(self.update_btns and self.streamNum == 3)
        self.btnAudioPrgs4.set_active(self.update_btns and self.streamNum == 4)
        self.btnAudioPrgs5.set_active(self.update_btns and self.streamNum == 5)
        self.btnAudioPrgs6.set_active(self.update_btns and self.streamNum == 6)
        self.btnAudioPrgs7.set_active(self.update_btns and self.streamNum == 7)
        self.update_btns = True

    def on_program_select(self, _label, evt):
        stream_num = int(_label.get_property("name")[-1])
        is_lbl = _label.get_property("name")[0] != "b"
        self.update_btns = is_lbl
        self.streamNum = stream_num
        self.on_stream_changed()

    def on_cbAutoGain_toggled(self, btn):
        self.spinGain.set_sensitive(not btn.get_active())
        self.lblGain.set_visible(btn.get_active())

    def on_listviewBookmarks_row_activated(self, treeview, path, view_column):
        if (len(path) != 0):
            # get station from bookmark row
            tree_iter = treeview.get_model().get_iter(path[0])
            station   = treeview.get_model().get_value(tree_iter, 2)

            # capture target freq/stream before doing anything else
            target_freq   = float(int(station/10)/10.0)
            target_stream = (station%10)-1

            # Do the stop/switch/play in a background thread so the GTK main
            # thread is never blocked by sleep() or join(), which would freeze the GUI.
            def _switch():
                # 1. Stop the current player cleanly (kill process, join thread)
                if self.playing:
                    self.playing = False
                    if self.nrsc5 is not None:
                        try:
                            if self.nrsc5.poll() is None:
                                self.nrsc5.terminate()
                                time.sleep(0.2)
                            if self.nrsc5.poll() is None:
                                self.nrsc5.kill()
                        except Exception:
                            pass
                    # Wait for the old player thread to fully exit before starting a new one
                    if self.playerThread is not None:
                        self.playerThread.join(3)

                # 2. Update frequency/stream *after* the old process is dead
                GLib.idle_add(self._apply_bookmark_and_play, target_freq, target_stream)

            Thread(target=_switch, daemon=True).start()

    def _apply_bookmark_and_play(self, freq, stream):
        """Called on the GTK main thread after the old player has been stopped."""
        self.spinFreq.set_value(freq)
        self.streamNum = stream
        # Update stream info display without triggering a nrsc5 restart (we are already stopped)
        self.on_stream_changed_silent()
        # Now start fresh playback
        self.on_btnPlay_clicked(None)
        return False  # remove idle callback

    def on_stream_changed_silent(self):
        """Like on_stream_changed but skips the nrsc5 restart (used when already stopped)."""
        self.streamInfo["Title"]   = ""
        self.streamInfo["Album"]   = ""
        self.streamInfo["Artist"]  = ""
        self.streamInfo["Genre"]   = ""
        self.streamInfo["Cover"]   = ""
        self.streamInfo["Logo"]    = ""
        self.streamInfo["Bitrate"] = 0
        self.set_program_btns()
        self.displayLogo()
        self.update_bookmark_buttons()

    def on_lvBookmarks_selection_changed(self, tree_selection):
        # enable delete button if bookmark is selected
        (model, pathlist) = self.lvBookmarks.get_selection().get_selected_rows()
        self.btnDelete.set_sensitive(len(pathlist) != 0)

    def on_bookmarkNameEdited(self, cell, path, text, data=None):
        # update name in listview
        iter = self.lsBookmarks.get_iter(path)
        self.lsBookmarks.set(iter, 1, text)
        
        # update name in bookmarks array
        for b in self.bookmarks:
            if (b[2] == self.lsBookmarks[path][2]):
                b[1] = text
                break

    def on_notebookMain_switch_page(self, notebook, page, page_num):
        # disable delete button if not on bookmarks page and station is not bookmarked
        if (page_num != 3): #and (not self.bookmarked or not self.playing)):
            self.btnDelete.set_sensitive(False)
        # enable delete button if on bookmarks page and a bookmark is selected
        else:
            (model, iter) = self.lvBookmarks.get_selection().get_selected()
            self.btnDelete.set_sensitive(iter is not None)
    
    def on_radMap_toggled(self, btn):
        global mapDir, imgLANCZOS
        if (btn.get_active()):
            img_size = min(self.alignmentMap.get_allocated_height(), self.alignmentMap.get_allocated_width()) - 12
            if (img_size < 200):
                img_size = 200
            if (btn == self.radMapTraffic):
                self.mapData["mapMode"] = 0
                mapFile = os.path.join(mapDir, "TrafficMap.png")
                if (os.path.isfile(mapFile)):                                                           # check if map exists
                    with Image.open(mapFile) as img:
                        mapImg = img.resize((img_size, img_size), imgLANCZOS)               # scale map to fit window
                        self.imgMap.set_from_pixbuf(imgToPixbuf(mapImg))                                    # convert image to pixbuf and display
                else:
                    self.imgMap.set_from_icon_name("MISSING_IMAGE", Gtk.IconSize.DIALOG)                # display missing image if file is not found
            
            elif (btn == self.radMapWeather):
                self.mapData["mapMode"] = 1
                if (os.path.isfile(self.mapData["weatherNow"])):
                    with Image.open(self.mapData["weatherNow"]) as img:
                        mapImg = img.resize((img_size, img_size), imgLANCZOS)    # scale map to fit window
                        self.imgMap.set_from_pixbuf(imgToPixbuf(mapImg))                                    # convert image to pixbuf and display 
                else:
                    self.imgMap.set_from_icon_name("MISSING_IMAGE", Gtk.IconSize.DIALOG)                # display missing image if file is not found
    
    def on_btnMap_clicked(self, btn):
        # open map viewer window
        if (self.mapViewer is None):
            self.mapViewer = NRSC5_Map(self, self.mapViewerCallback, self.mapData)
            self.mapViewer.mapWindow.show()
    
    def mapViewerCallback(self):
        # delete the map viewer
        self.mapViewer = None

    def on_alignmentCover_clicked(self, widget, event):
        if (event.button == Gdk.BUTTON_SECONDARY):
            if (self.slPopup is None) and (self.playing):
                self.slPopup = NRSC5_SLPopup(self, self.slPopupCallback, self.slData)
                self.slPopup.txtEntry.set_text(self.slData['externalURL'])
                self.slPopup.entryWindow.show()
                # now center it
                winX, winY = self.mainWindow.get_position()
                winW, winH = self.mainWindow.get_size()
                slW, slH = self.slPopup.entryWindow.get_size()
                self.slPopup.entryWindow.move(int(winW/2 - slW/2)+winX, int(winH/2 - slH/2)+winY)
                self.slPopup.entryWindow.set_keep_above(True)

    def slPopupCallback(self):
        extensions = ['.gif','.jpg','.jpeg','.png']
        useExt = ""
        self.slData['externalURL'] = self.slPopup.txtEntry.get_text()
        self.slPopup = None
        if (self.slData['externalURL'] != ""):
            freq = int((self.spinFreq.get_value()+0.005)*100) + int(self.streamNum + 1)
            fileName = str(freq)+"_SL"+self.streamInfo["Callsign"]+"$$"+str(int(self.streamNum + 1))
            for extension in extensions:
                if extension in self.slData['externalURL']:
                    useExt = extension
                    break
            if (useExt != ""):
                fileName = fileName + useExt
                saveStr=os.path.join(aasDir,fileName)
                with self.http.request('GET',self.slData['externalURL'], preload_content=False) as r, open(saveStr, 'wb') as out_file:
                    if(r.status == 200):
                        shutil.copyfileobj(r, out_file)
                        self.stationLogos[self.stationStr][self.streamNum] = fileName
                        self.displayLogo()

    def play(self):
        FNULL = open(os.devnull, 'w')
        FTMP = open('tmp.log','w')

        # run nrsc5 and output stderr to pipe, stdout to /dev/null
        # CRITICAL: stdout must not use PIPE or it will fill up and block nrsc5
        # Use unbuffered stdin (bufsize=0) for immediate command processing
        self.nrsc5 = Popen(self.nrsc5Args, shell=False, stdin=PIPE, stdout=FNULL, stderr=PIPE, 
                          universal_newlines=False, bufsize=0)
        
        try:
            while True:
                # Capture a local reference to avoid race condition where another thread
                # (e.g. switching stations from bookmarks) sets self.nrsc5 = None between
                # our None-check and subsequent use of the object.
                proc = self.nrsc5
                if proc is None:
                    break
                
                # Note: We no longer send stream changes via stdin
                # Stream changes now restart nrsc5 with the new stream number
                # This works on all platforms without requiring PTY
                    
                # read output from nrsc5 (now in binary mode)
                output_bytes = proc.stderr.readline()
                if not output_bytes:
                    # EOF
                    output = ""
                else:
                    output = output_bytes.decode('utf-8', errors='replace')
                
                # Check if we got EOF (empty string means process ended)
                if not output:
                    self.debugLog("nrsc5 stderr closed (process may have ended)")
                    if proc.poll() is not None:
                        # Process has definitely exited
                        if self.playing:
                            self.debugLog("Restarting NRSC5 (unexpected termination)")
                            time.sleep(1)
                            self.nrsc5 = Popen(self.nrsc5Args, shell=False, stdin=PIPE, stdout=FNULL, stderr=PIPE, universal_newlines=False, bufsize=0)
                            continue
                        else:
                            self.debugLog("Process Terminated")
                            self.nrsc5 = None
                            break
                    else:
                        # Process still running but stderr gave us nothing, try again
                        time.sleep(0.1)
                        continue
                
                # parse the output
                self.parseFeedback(output)
                
                # write output to log file if enabled
                if (self.cbLog.get_active() and self.logFile is not None):
                    self.logFile.write(output)
                    self.logFile.flush()
                
                # check if nrsc5 has exited (use local proc ref — safe even if self.nrsc5
                # was set to None by another thread mid-iteration)
                poll_result = proc.poll()
                if poll_result is not None:
                    # Process has exited
                    if not self.playing:
                        # User stopped it - clean shutdown
                        self.debugLog("Process Terminated")
                        self.nrsc5 = None
                        break
                    else:
                        # Unexpected exit - restart
                        self.debugLog("Restarting NRSC5 (exit code: {})".format(poll_result))
                        time.sleep(1)
                        self.nrsc5 = Popen(self.nrsc5Args, shell=False, stdin=self.nrsc5slave, stdout=FNULL, stderr=PIPE, universal_newlines=True)
        finally:
            # Clean up file handles
            FNULL.close()
            FTMP.close()

    def set_synchronization(self, state):
        self.imgNoSynch.set_visible(state == 0)
        self.imgSynch.set_visible(state == 1)
        self.imgLostDevice.set_visible(state == -1)

    def set_button_name(self, btnWidget, lblWidget, stream):
        temp = self.streamInfo["Streams"][stream]
        if ((temp == "") or (temp == "MPS") or (temp[0:3] == "SPS") or (temp[0:2] == "HD") ):
            if (self.booknames[stream] != ""):
                temp = self.booknames[stream]
        lblWidget.set_label(temp)
        btnWidget.set_sensitive(temp != "")

    def set_label_name(self, lblWidget, inString, doSens):
        lblWidget.set_label(inString)
        lblWidget.set_tooltip_text(inString)
        if (doSens):
            lblWidget.set_sensitive(inString != "")

    def getImageLot(self,imgStr):
        r = re.compile("^([0-9]+)_.*$")
        m = r.match(imgStr)
        return m.group(1)

    def checkStatus(self):
        # update status information
        def update():
            global aasDir
            try:
                imagePath = ""
                image = ""
                ber = [self.streamInfo["BER"][i]*100 for i in range(4)]
                self.id3Changed = self.id3_did_change()
                self.txtTitle.set_text(self.streamInfo["Title"])
                self.txtTitle.set_tooltip_text(self.streamInfo["Title"])
                self.txtArtist.set_text(self.streamInfo["Artist"])
                self.txtArtist.set_tooltip_text(self.streamInfo["Artist"])
                self.txtAlbum.set_text(self.streamInfo["Album"])
                self.txtAlbum.set_tooltip_text(self.streamInfo["Album"])
                self.txtGenre.set_text(self.streamInfo["Genre"])
                self.txtGenre.set_tooltip_text(self.streamInfo["Genre"])
                self.lblBitRate.set_label("{:3.1f} kbps".format(self.streamInfo["Bitrate"]))
                self.lblBitRate2.set_label("{:3.1f} kbps".format(self.streamInfo["Bitrate"]))
                self.lblError.set_label("{:2.2f}% BER ".format(self.streamInfo["BER"][0]*100))
                self.lblCall.set_label(" " + self.streamInfo["Callsign"])
                self.lblName.set_label(self.streamInfo["Callsign"])
                self.lblSlogan.set_label(self.streamInfo["Slogan"])
                self.lblSlogan.set_tooltip_text(self.streamInfo["Slogan"])
                self.lblMessage.set_label(self.streamInfo["Message"])
                self.lblMessage.set_tooltip_text(self.streamInfo["Message"])
                if (self.txtMessage2):
                    self.txtMessage2.set_label(self.streamInfo["Message"])
                    self.txtMessage2.set_tooltip_text(self.streamInfo["Message"])
                self.lblAlert.set_label(self.streamInfo["Alert"])
                self.lblAlert.set_tooltip_text(self.streamInfo["Alert"])
                if (self.txtAlert2):
                    self.txtAlert2.set_label(self.streamInfo["Alert"])
                    self.txtAlert2.set_tooltip_text(self.streamInfo["Alert"])
                self.set_button_name(self.btnAudioPrgs0,self.btnAudioLbl0,0)
                self.set_button_name(self.btnAudioPrgs1,self.btnAudioLbl1,1)
                self.set_button_name(self.btnAudioPrgs2,self.btnAudioLbl2,2)
                self.set_button_name(self.btnAudioPrgs3,self.btnAudioLbl3,3)
                self.set_button_name(self.btnAudioPrgs4,self.btnAudioLbl4,4)
                self.set_button_name(self.btnAudioPrgs5,self.btnAudioLbl5,5)
                self.set_button_name(self.btnAudioPrgs6,self.btnAudioLbl6,6)
                self.set_button_name(self.btnAudioPrgs7,self.btnAudioLbl7,7)
                self.set_label_name(self.lblAudioPrgs0, self.streamInfo["Streams"][0], True)
                self.set_label_name(self.lblAudioPrgs1, self.streamInfo["Streams"][1], True)
                self.set_label_name(self.lblAudioPrgs2, self.streamInfo["Streams"][2], True)
                self.set_label_name(self.lblAudioPrgs3, self.streamInfo["Streams"][3], True)
                self.set_label_name(self.lblAudioPrgs4, self.streamInfo["Streams"][4], True)
                self.set_label_name(self.lblAudioPrgs5, self.streamInfo["Streams"][5], True)
                self.set_label_name(self.lblAudioPrgs6, self.streamInfo["Streams"][6], True)
                self.set_label_name(self.lblAudioPrgs7, self.streamInfo["Streams"][7], True)
                self.set_label_name(self.lblAudioSvcs0, self.streamInfo["Programs"][0], True)
                self.set_label_name(self.lblAudioSvcs1, self.streamInfo["Programs"][1], True)
                self.set_label_name(self.lblAudioSvcs2, self.streamInfo["Programs"][2], True)
                self.set_label_name(self.lblAudioSvcs3, self.streamInfo["Programs"][3], True)
                self.set_label_name(self.lblAudioSvcs4, self.streamInfo["Programs"][4], True)
                self.set_label_name(self.lblAudioSvcs5, self.streamInfo["Programs"][5], True)
                self.set_label_name(self.lblAudioSvcs6, self.streamInfo["Programs"][6], True)
                self.set_label_name(self.lblAudioSvcs7, self.streamInfo["Programs"][7], True)
                self.set_label_name(self.lblDataSvcs0, self.streamInfo["Services"][0], False)
                self.set_label_name(self.lblDataSvcs1, self.streamInfo["Services"][1], False)
                self.set_label_name(self.lblDataSvcs2, self.streamInfo["Services"][2], False)
                self.set_label_name(self.lblDataSvcs3, self.streamInfo["Services"][3], False)
                self.set_label_name(self.lblDataType0, self.streamInfo["SvcTypes"][0], False)
                self.set_label_name(self.lblDataType1, self.streamInfo["SvcTypes"][1], False)
                self.set_label_name(self.lblDataType2, self.streamInfo["SvcTypes"][2], False)
                self.set_label_name(self.lblDataType3, self.streamInfo["SvcTypes"][3], False)
                self.lblMerLower.set_label("{:1.2f} dB".format(self.streamInfo["MER"][0]))
                self.lblMerUpper.set_label("{:1.2f} dB".format(self.streamInfo["MER"][1]))
                self.lblBerNow.set_label("{:1.3f}% (Now)".format(ber[0]))
                self.lblBerAvg.set_label("{:1.3f}% (Avg)".format(ber[1]))
                self.lblBerMin.set_label("{:1.3f}% (Min)".format(ber[2]))
                self.lblBerMax.set_label("{:1.3f}% (Max)".format(ber[3]))

                if (self.cbAutoGain.get_active()):
                    self.spinGain.set_value(self.streamInfo["Gain"])
                    self.lblGain.set_label("{:2.1f} dB".format(self.streamInfo["Gain"]))
                
                # second param is lot id, if -1, show cover, otherwise show cover
                # technically we should show the file with the matching lot id

                lot = -1
                if ((self.lastXHDR == "0") and (self.streamInfo["Cover"] != "")):
                    imagePath = os.path.join(aasDir, self.streamInfo["Cover"])
                    image = self.streamInfo["Cover"]
                    lot = self.getImageLot(image)
                elif (((self.lastXHDR == "1") or (self.lastImage != "")) and (self.streamInfo["Logo"] != "")):
                    imagePath = os.path.join(aasDir, self.streamInfo["Logo"])
                    image = self.streamInfo["Logo"]
                    if (not os.path.isfile(imagePath)):
                        self.imgCover.clear()
                        self.coverImage = ""
                    
                # resize and display image if it changed and exists
                if (self.xhdrChanged and (self.lastImage != image) and ((self.lastLOT == lot) or (lot == -1)) and os.path.isfile(imagePath)):
                    self.xhdrChanged = False
                    self.lastImage = image
                    self.coverImage = imagePath
                    self.showArtwork(imagePath)
                    self.debugLog("Image Changed")

                # Disable downloaded cover images until fixed with MusicBrainz
                # CRITICAL: Run in separate thread to avoid blocking GTK main thread with network I/O
                if (self.cbCovers.get_active() and self.id3Changed):
                    Thread(target=self.get_cover_image_online, daemon=True).start()

            finally:
                pass        
        
        if (self.playing):
            GLib.idle_add(update)
            self.statusTimer = Timer(1, self.checkStatus)
            self.statusTimer.start()

    def processHERETrafficMap(self, fileName, timeStr):
        global aasDir, mapDir, imgLANCZOS
        r = re.compile("^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$")
        m = r.match(timeStr)

        if (m):
            # get time from map tile and convert to local time
            dt = datetime.datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5)), int(m.group(6)), tzinfo=tz.tzutc())
            t  = dt.astimezone(tz.tzlocal())                                                            # local time
            ts = dtToTs(dt)                                                                             # unix timestamp (etc)

            r = re.compile("^trafficMap_([0-9])_([0-9])_(.*).png$")
            n = r.match(fileName)
            if (n):
                x = int(n.group(1))
                y = int(n.group(2))
                self.map_progress.set_fraction((x*3+y)/8)

                # prepend filename with timestamp
                fileName = "{0}_{1}".format(ts,fileName)
                self.finishTrafficMap(fileName, ts, t, x, y)
                return False  # CRITICAL: Tell GTK not to call this again
            
    def processTrafficMap(self, fileName):
        global aasDir, mapDir, imgLANCZOS
        r = re.compile("^[0-9]+_TMT_.*_([1-3])_([1-3])_([0-9]{4})([0-9]{2})([0-9]{2})_([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})_([0-9A-Fa-f]{4})[.].*$")     # match file name
        m = r.match(fileName)
        
        if (m):
            x       = int(m.group(1))-1 # X position
            y       = int(m.group(2))-1 # Y position
            self.map_progress.set_fraction((x*3+y)/8)

            # get time from map tile and convert to local time
            dt = datetime.datetime(int(m.group(3)), int(m.group(4)), int(m.group(5)), int(m.group(6)), int(m.group(7)), tzinfo=tz.tzutc())
            t  = dt.astimezone(tz.tzlocal())                                                        # local time
            ts = dtToTs(dt)
            self.finishTrafficMap(fileName, ts, t, x, y)                                            # unix timestamp (utc)
            return False  # CRITICAL: Tell GTK not to call this again
            
    def finishTrafficMap(self, fileName, ts, t, x, y):
        global aasDir, mapDir, imgLANCZOS
        # check if the tile has already been loaded
        if (self.mapData["mapTiles"][x][y] == ts):
            try:
                os.remove(os.path.join(aasDir, fileName))                                           # delete this tile, it's not needed
            except:
                pass
            return                                                                                  # no need to recreate the map if it hasn't changed
            
        self.debugLog("Got Traffic Map Tile: {:g},{:g}".format(x,y))
                
        self.mapData["mapComplete"]    = False                                                      # new tiles are coming in, the map is nolonger complete
        self.mapData["mapTiles"][x][y] = ts                                                         # store time for current tile
            
        try:
            currentPath = os.path.join(aasDir,fileName)
            newPath = os.path.join(mapDir, "TrafficMap_{:g}_{:g}.png".format(x,y))                  # create path to new tile location
            if(os.path.exists(newPath)): os.remove(newPath)                                         # delete old image if it exists (only necessary on windows)
            shutil.move(currentPath, newPath)                                                       # move and rename map tile
        except:
            self.debugLog("Error moving map tile (src: "+currentPath+", dest: "+newPath+")", True)
            self.mapData["mapTiles"][x][y] = 0
                
        # check if all of the tiles are loaded
        if (self.checkTiles(ts)):
            self.debugLog("Got complete traffic map")
            self.mapData["mapComplete"] = True                                                      # map is complete
                
            # stitch the map tiles into one image
            imgMap = Image.new("RGB", (600, 600), "white")                                          # create blank image for traffic map
            for i in range(0,3):
                for j in range(0,3):
                    tileFile = os.path.join(mapDir, "TrafficMap_{:g}_{:g}.png".format(i,j))         # get path to tile
                    with Image.open(tileFile) as tile:
                        imgMap.paste(tile, (j*200, i*200))                              # paste tile into map
                    os.remove(tileFile)                                                             # delete tile image

            # now put a timestamp on it.
            imgMap   = imgMap.convert("RGBA")
            imgBig   = (981,981)                                                                    # size of a weather map
            posTS    = (imgBig[0]-235, imgBig[1]-29)                                                # calculate position to put timestamp (bottom right)
            imgTS    = self.mkTimestamp(t, imgBig, posTS)                                           # create timestamp for a weather map
            imgTS    = imgTS.resize((imgMap.size[0], imgMap.size[1]), imgLANCZOS)                   # resize it so it's proportional to the size of a traffic map (981 -> 600)
            imgMap   = Image.alpha_composite(imgMap, imgTS)                                         # overlay timestamp on traffic map

            imgMap.save(os.path.join(mapDir, "TrafficMap.png"))                                     # save traffic map
                
            # display on map page
            if (self.radMapTraffic.get_active()):
                img_size = min(self.alignmentMap.get_allocated_height(), self.alignmentMap.get_allocated_width()) - 12
                imgMap = imgMap.resize((img_size, img_size), imgLANCZOS)                            # scale map to fit window
                self.imgMap.set_from_pixbuf(imgToPixbuf(imgMap))                                    # convert image to pixbuf and display
                
            if (self.mapViewer is not None): self.mapViewer.updated(0)                              # notify map viwerer if it's open
    
    def processHEREWeatherOverlay(self, fileName, timeStr):
        global aasDir, mapDir, imgLANCZOS
        r = re.compile("^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$")
        m = r.match(timeStr)

        if (m):
            # get time from map tile and convert to local time
            dt = datetime.datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5)), int(m.group(6)), tzinfo=tz.tzutc())
            t  = dt.astimezone(tz.tzlocal())                                                        # local time
            ts = dtToTs(dt)                                                                         # unix timestamp (etc)

            r = re.compile("^WeatherImage_([0-9])_([0-9])_(.*).png$")
            n = r.match(fileName)
            if (n):
                id = n.group(3)

            # prepend filename with timestamp
            fileName = "{0}_{1}".format(ts,fileName)
            self.finishWeatherOverlay(fileName, ts, t, id)
            return False  # CRITICAL: Tell GTK not to call this again
    
    def processWeatherOverlay(self, fileName):
        global aasDir, mapDir, imgLANCZOS
        r = re.compile("^[0-9]+_DWRO_(.*)_.*_([0-9]{4})([0-9]{2})([0-9]{2})_([0-9]{2})([0-9]{2})_([0-9A-Fa-f]+)[.].*$")                    # match file name
        m = r.match(fileName)
        
        if (m):
            # get time from map tile and convert to local time
            dt = datetime.datetime(int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5)), int(m.group(6)), tzinfo=tz.tzutc())
            t  = dt.astimezone(tz.tzlocal())                                                        # local time
            ts = dtToTs(dt)                                                                         # unix timestamp (utc)
            id = self.mapData["weatherID"]
            
            if (m.group(1) != id):
                if (id == ""):
                    self.debugLog("Received weather overlay before metadata, ignoring...");
                else:
                    self.debugLog("Received weather overlay with the wrong ID: " + m.group(1) + " (wanted " + id +")")
                return False  # CRITICAL: Tell GTK not to call this again
                
            self.finishWeatherOverlay(fileName, ts, t, id)
            return False  # CRITICAL: Tell GTK not to call this again
            
    def finishWeatherOverlay(self, fileName, ts, t, id):
        global aasDir, mapDir, imgLANCZOS

        if (self.mapData["weatherTime"] == ts):
            try:
                os.remove(os.path.join(aasDir, fileName))                                           # delete this tile, it's not needed
            except:
                pass
            return                                                                                  # no need to recreate the map if it hasn't changed
            
        self.debugLog("Got Weather Overlay")
            
        self.mapData["weatherTime"] = ts                                                            # store time for current overlay
        wxOlPath  = os.path.join(mapDir,"WeatherOverlay_{:s}_{:}.png".format(id, ts))
        wxMapPath = os.path.join(mapDir,"WeatherMap_{:s}_{:}.png".format(id, ts))
            
        # move new overlay to map directory
        try:
            if(os.path.exists(wxOlPath)): os.remove(wxOlPath)                                       # delete old image if it exists (only necessary on windows)
            shutil.move(os.path.join(aasDir, fileName), wxOlPath)                                   # move and rename map tile
        except:
            self.debugLog("Error moving weather overlay", True)
            self.mapData["weatherTime"] = 0
                
        # create weather map
        try:
            mapPath = os.path.join(mapDir, "BaseMap_" + id + ".png")                                # get path to base map
            if (os.path.isfile(mapPath) == False):                                                  # make sure base map exists
                self.makeBaseMap(self.mapData["weatherID"], self.mapData["weatherPos"])             # create base map if it doesn't exist
                
            with Image.open(mapPath) as img:
                imgMap = img.convert("RGBA")                                          # open map image
                imgBig   = (981,981)                                                                    # size of a weather map
                imgMap   = imgMap.resize(imgBig, imgLANCZOS)                                            # resize if tiny
            posTS    = (imgBig[0]-235, imgBig[1]-29)
            imgTS    = self.mkTimestamp(t, imgBig, posTS)                                           # create timestamp
            imgTS    = imgTS.resize((imgMap.size[0], imgMap.size[1]), imgLANCZOS)                   # resize it so it's proportional to the size of a traffic map (981 -> 600)
            
            # Open overlay image once and properly handle palette mode with transparency
            with Image.open(wxOlPath) as img:
                # Convert palette images to RGBA first to avoid transparency warnings
                if img.mode == 'P':
                    imgRadar = img.convert("RGBA")
                else:
                    imgRadar = img.convert("RGBA")
                # Keep the image data by copying before the with block closes
                imgRadar = imgRadar.copy()
            
            # Resize after copying to avoid issues with closed images
            imgRadar = imgRadar.resize(imgMap.size, imgLANCZOS)
            
            # Create alpha channel from grayscale version
            with Image.open(wxOlPath) as img:
                if img.mode == 'P':
                    # For palette images, convert to RGBA first, then to grayscale
                    imgAlpha = img.convert("RGBA").convert("L")
                else:
                    imgAlpha = img.convert("L")
                imgAlpha = imgAlpha.copy()
            
            imgAlpha = imgAlpha.resize(imgMap.size, imgLANCZOS)
            imgRadar.putalpha(imgAlpha)                                                             # use grayscale overlay to create variable alpha channel.
            del imgAlpha  # Clean up alpha channel image

            imgMap   = Image.alpha_composite(imgMap, imgRadar)                                      # overlay radar image on map
            del imgRadar  # Clean up radar image
            imgMap   = Image.alpha_composite(imgMap, imgTS)                                         # overlay timestamp
            del imgTS  # Clean up timestamp image
            imgMap.save(wxMapPath)                                                                  # save weather map
            os.remove(wxOlPath)                                                                     # remove overlay image
            self.mapData["weatherNow"] = wxMapPath
                
            # display on map page
            if (self.radMapWeather.get_active()):
                img_size = min(self.alignmentMap.get_allocated_height(), self.alignmentMap.get_allocated_width()) - 12
                imgMapResized = imgMap.resize((img_size, img_size), imgLANCZOS)                     # scale map to fit window
                self.imgMap.set_from_pixbuf(imgToPixbuf(imgMapResized))                             # convert image to pixbuf and display
                del imgMapResized  # Clean up resized image
            
            del imgMap  # Clean up main map image
                
            self.proccessWeatherMaps()                                                              # get rid of old maps and add new ones to the list
            if (self.mapViewer is not None): self.mapViewer.updated(1)                              # notify map viwerer if it's open
                    
        except Exception as e:
            self.debugLog("Error creating weather map: {}".format(str(e)), True)
            self.mapData["weatherTime"] = 0
            
    def proccessWeatherInfo(self, fileName):
        global aasDir
        weatherID = None
        weatherPos = None

        try:
            with open(os.path.join(aasDir, fileName)) as weatherInfo:                                   # open weather info file
                for line in weatherInfo:                                                                # read line by line
                    if ("DWR_Area_ID=" in line):                                                        # look for line with "DWR_Area_ID=" in it
                        # get ID from line
                        r = re.compile("^DWR_Area_ID=\"(.+)\"$")
                        m = r.match(line)
                        weatherID = m.group(1)

                    elif ("Coordinates=" in line):                                                      # look for line with "Coordinates=" in it
                        # get coordinates from line
                        r = re.compile("^Coordinates=.*[(](-?[0-9]+[.][0-9]+),(-?[0-9]+[.][0-9]+)[)].*[(](-?[0-9]+[.][0-9]+),(-?[0-9]+[.][0-9]+)[)].*$")
                        m = r.match(line)
                        weatherPos = [float(m.group(1)),float(m.group(2)), float(m.group(3)), float(m.group(4))]
        except:
            self.debugLog("Error opening weather info", True)
        
        if (weatherID is not None and weatherPos is not None):                                          # check if ID and position were found
            if (self.mapData["weatherID"] != weatherID or self.mapData["weatherPos"] != weatherPos):    # check if ID or position has changed
                self.debugLog("Got position: ({:n}, {:n}) ({:n}, {:n})".format(*weatherPos))
                self.mapData["weatherID"]  = weatherID                                                  # set weather ID
                self.mapData["weatherPos"] = weatherPos                                                 # set weather map position
                
                # Make base map creation asynchronous to avoid blocking nrsc5 stderr reading (HEAVY OPERATION)
                GLib.idle_add(self.makeBaseMap, weatherID, weatherPos)
                self.weatherMaps = []
                GLib.idle_add(self.proccessWeatherMaps)
    
    def proccessHEREWeatherInfo(self, fileName, lat1, lon1, lat2, lon2):
        global aasDir
        weatherID = None
        weatherPos = None

        r = re.compile("^.*WeatherImage_([0-9])_([0-9])_(.*).png$")
        m = r.match(fileName)
        if (m):
            weatherID = m.group(3)
            # make weather image the same size/aspect ratio as Traffic image
            if ((self.tLat1 != 0.0) and (self.tLat2 != 0.0)):
                lat1 = (self.tLat1 - self.tLat2) + lat2
            else:
                return
            weatherPos = [lat1, lon1, lat2, lon2]
        
        if (weatherID is not None and weatherPos is not None):                                          # check if ID and position were found
            if (self.mapData["weatherID"] != weatherID or self.mapData["weatherPos"] != weatherPos):    # check if ID or position has changed
                self.debugLog("Got position: ({:n}, {:n}) ({:n}, {:n})".format(*weatherPos))
                self.mapData["weatherID"]  = weatherID                                                  # set weather ID
                self.mapData["weatherPos"] = weatherPos                                                 # set weather map position
                
                # Make base map creation asynchronous to avoid blocking nrsc5 stderr reading (HEAVY OPERATION)
                GLib.idle_add(self.makeBaseMap, weatherID, weatherPos)
                self.weatherMaps = []
                GLib.idle_add(self.proccessWeatherMaps)
    
    def proccessWeatherMaps(self):
        global mapDir
        numberOfMaps = 0
        r     = re.compile("^.*map.WeatherMap_([a-zA-Z0-9]+)_([0-9]+).png")
        now   = dtToTs(datetime.datetime.now(tz.tzutc()))                                               # get current time
        files = glob.glob(os.path.join(mapDir, "WeatherMap_") + "*.png")                                # look for weather map files
        files.sort()                                                                                    # sort files
        for f in files:  
            m = r.match(f)                                                                              # match regex
            if (m):
                id = m.group(1)                                                                         # location ID
                ts = int(m.group(2))                                                                    # timestamp (UTC)
                
                # remove weather maps older than 12 hours
                if (now - ts > 60*60*12):
                    try:
                        if (f in self.weatherMaps):
                            self.weatherMaps.pop(self.weatherMaps.index(f))                             # remove from list
                        os.remove(f)                                                                    # remove file
                        self.debugLog("Deleted old weather map: " + f)
                    except:
                        self.debugLog("Error Failed to Delete: " + f)
                        
                # skip if not the correct location
                elif (id == self.mapData["weatherID"]):
                    if (f not in self.weatherMaps):
                        self.addWeatherMap(f)                                                      # add to list
                    numberOfMaps += 1
        

        self.debugLog("Found {} weather maps".format(numberOfMaps))
        return False  # CRITICAL: Tell GTK not to call this again
        
    def getMapArea(self, lat1, lon1, lat2, lon2):
        from math import asinh, tan, radians
        
        # get pixel coordinates from latitude and longitude
        # calculations taken from https://github.com/KYDronePilot/hdfm
        top  = asinh(tan(radians(52.482780)))
        lat1 = top - asinh(tan(radians(lat1)))
        lat2 = top - asinh(tan(radians(lat2)))
        x1   = (lon1 + 130.781250) * 7162 / 39.34135
        x2   = (lon2 + 130.781250) * 7162 / 39.34135
        y1   = lat1 * 3565 / (top - asinh(tan(radians(38.898))))
        y2   = lat2 * 3565 / (top - asinh(tan(radians(38.898))))
        
        return (int(round(x1)), int(round(y1)), int(round(x2)), int(round(y2)))
    
    def makeBaseMap(self, id, pos):
        global mapDir
        mapPath = os.path.join(mapDir, "BaseMap_" + id + ".png")                                # get map path
        if (os.path.isfile(self.mapFile)):
            if (os.path.isfile(mapPath) == False):                                              # check if the map has already been created for this location
                self.debugLog("Creating new map: " + mapPath)
                px     = self.getMapArea(*pos)                                                  # convert map locations to pixel coordinates
                with Image.open(self.mapFile) as img:
                    mapImg = img.crop(px)                                      # open the full map and crop it to the coordinates
                    mapImg.save(mapPath)                                                            # save the cropped map to disk for later use
                self.debugLog("Finished creating map")
        else:
            self.debugLog("Error map file not found: " + self.mapFile, True)
            mapImg = Image.new("RGBA", (pos[2]-pos[1], pos[3]-pos[1]), "white")                 # if the full map is not available, use a blank image
            mapImg.save(mapPath)
        return False  # CRITICAL: Tell GTK not to call this again
    
    def checkTiles(self, t):
        # check if all the tiles have been received
        for i in range(0,3):
            for j in range(0,3):
                if (self.mapData["mapTiles"][i][j] != t):
                    return False
        return True
    
    def mkTimestamp(self, t, size, pos):
        global resDir
        # create a timestamp image to overlay on the weathermap
        x,y   = pos
        text  = "{:04g}-{:02g}-{:02g} {:02g}:{:02g}".format(t.year, t.month, t.day, t.hour, t.minute)   # format timestamp
        imgTS = Image.new("RGBA", size, (0,0,0,0))                                                      # create a blank image
        draw  = ImageDraw.Draw(imgTS)                                                                   # the drawing object
        font  = ImageFont.truetype(os.path.join(resDir,"DejaVuSansMono.ttf"), 24)                       # DejaVu Sans Mono 24pt font
        draw.rectangle((x,y, x+231,y+25), outline="black", fill=(128,128,128,96))                       # draw a box around the text
        draw.text((x+3,y), text, fill="black", font=font)                                               # draw the text
        return imgTS                                                                                    # return the image

    def checkPorts(self, port, type):
        result = -1
        for i in range(0,7):
            if (len(self.streams[i]) > type):
                if (port == self.streams[i][type]):
                    result = i
        return result

    def parseFeedback(self, line):
        global aasDir, mapDir
        line = line.strip()
        if (self.regex[4].match(line)):
            # match title
            m = self.regex[4].match(line)
            self.streamInfo["Title"] = m.group(1)
        elif (self.regex[5].match(line)):
            # match artist
            m = self.regex[5].match(line)
            self.streamInfo["Artist"] = m.group(1)
        elif (self.regex[6].match(line)):
            # match album
            m = self.regex[6].match(line)
            self.streamInfo["Album"] = m.group(1)
        elif (self.regex[15].match(line)):
            # match genre
            m = self.regex[15].match(line)
            self.streamInfo["Genre"] = m.group(1)
        elif (self.regex[3].match(line)):
            # match audio bit rate
            m = self.regex[3].match(line)
            self.streamInfo["Bitrate"] = float(m.group(1))
        elif (self.regex[8].match(line)):
            # match MER
            m = self.regex[8].match(line)
            self.streamInfo["MER"] = [float(m.group(1)), float(m.group(2))]
        elif (self.regex[9].match(line)):
            # match BER
            m = self.regex[9].match(line)
            self.streamInfo["BER"] = [float(m.group(1)), float(m.group(2)), float(m.group(3)), float(m.group(4))]
        elif (self.regex[13].match(line)):
            # match xhdr
            m = self.regex[13].match(line)
            xhdr = m.group(1)
            mime = m.group(2)
            lot  = m.group(3)
            if (xhdr != self.lastXHDR) or (lot != self.lastLOT):
                self.lastXHDR = xhdr
                self.lastLOT = lot
                self.xhdrChanged = True
                self.debugLog("XHDR Changed: {:s} (lot {:s})".format(xhdr,lot))
        elif (self.regex[23].match(line)):
            # match HERE Images
            m = self.regex[23].match(line)
            if (m):
                type = m.group(1)
                seq = int(m.group(2))
                n1 = int(m.group(3))
                n2 = int(m.group(4))
                timeStr = m.group(5)
                lat1 = float(m.group(6))
                lon1 = float(m.group(7))
                lat2 = float(m.group(8))
                lon2 = float(m.group(9))
                fileName = m.group(10)
                fileSize = m.group(11)
                #temporary print statement until HERE testing done
                print("got HERE image: {} {} of {} {} {} {} {} {} {} {}".format(type,n1,n2,timeStr,lat1,lon1,lat2,lon2,fileName,fileSize))

                # check file existance and size .. right now we just debug log
                #if (not os.path.isfile(os.path.join(aasDir,fileName))):
                #    self.debugLog("Missing file: " + fileName)
                #else:
                #    actualFileSize = os.path.getsize(os.path.join(aasDir,fileName))
                #    if (fileSize != actualFileSize):
                #        self.debugLog("Corrupt file: " + fileName + " (expected: "+str(fileSize)+" bytes, got "+str(actualFileSize)+" bytes)")

                if(type == "WEATHER" and mapDir is not None):
                    self.proccessHEREWeatherInfo(fileName,lat1,lon1,lat2,lon2)
                    # Process weather overlay asynchronously to avoid blocking nrsc5 stderr reading
                    GLib.idle_add(self.processHEREWeatherOverlay, fileName, timeStr)
                elif(type == "TRAFFIC" and mapDir is not None):
                    #save lat at corners of resulting traffic image for later.
                    if (n1 == 1):
                        self.tLat1 = lat1
                    if (n1 == n2):
                        self.tLat2 = lat2
                    # Process traffic map asynchronously to avoid blocking nrsc5 stderr reading
                    GLib.idle_add(self.processHERETrafficMap, fileName, timeStr)
                    
        elif (self.regex[7].match(line)):
            # match album art
            m = self.regex[7].match(line)
            if (m):
                fileName = "{}_{}".format(m.group(2),m.group(3))
                fileSize = int(m.group(4))
                headerOffset = int(len(m.group(2))) + 1

                p = int(m.group(1),16)
                coverStream = self.checkPorts(p,0)
                logoStream = self.checkPorts(p,1)

                # check file existance and size .. right now we just debug log
                if (not os.path.isfile(os.path.join(aasDir,fileName))):
                    self.debugLog("Missing file: " + fileName)
                else:
                    actualFileSize = os.path.getsize(os.path.join(aasDir,fileName))
                    if (fileSize != actualFileSize):
                        self.debugLog("Corrupt file: " + fileName + " (expected: "+str(fileSize)+" bytes, got "+str(actualFileSize)+" bytes)")

                if (coverStream > -1):
                    if coverStream == self.streamNum:
                        #set cover only if downloading covers and including station covers
                        if (self.cbCoverIncl.get_active() or (not self.cbCovers.get_active())):
                            self.streamInfo["Cover"] = fileName
                    self.debugLog("Got Album Cover: " + fileName)
                elif (logoStream > -1):
                    if logoStream == self.streamNum:
                        self.streamInfo["Logo"] = fileName
                    self.stationLogos[self.stationStr][logoStream] = fileName         # add station logo to database
                    self.debugLog("Got Station Logo: "+fileName)

                elif(fileName[headerOffset:(5+headerOffset)] == "DWRO_" and mapDir is not None):
                    # Process weather overlay asynchronously to avoid blocking nrsc5 stderr reading
                    GLib.idle_add(self.processWeatherOverlay, fileName)
                elif(fileName[headerOffset:(4+headerOffset)] == "TMT_" and mapDir is not None):
                    # Process traffic map asynchronously to avoid blocking nrsc5 stderr reading
                    GLib.idle_add(self.processTrafficMap, fileName)
                elif(fileName[headerOffset:(5+headerOffset)] == "DWRI_" and mapDir is not None):
                    self.proccessWeatherInfo(fileName)

        elif (self.regex[0].match(line)):
            # match station name
            m = self.regex[0].match(line)
            self.streamInfo["Callsign"] = m.group(1)
        elif (self.regex[2].match(line)):
            # match station slogan
            m = self.regex[2].match(line)
            self.streamInfo["Slogan"] = m.group(1)
        elif (self.regex[16].match(line)):
            # match message
            m = self.regex[16].match(line)
            self.streamInfo["Message"] = m.group(1)
        elif (self.regex[17].match(line)):
            # match alert
            m = self.regex[17].match(line)
            self.streamInfo["Alert"] = m.group(1)
        elif (self.regex[10].match(line)):
            # match gain
            m = self.regex[10].match(line)
            self.streamInfo["Gain"] = float(m.group(1))
        elif (self.regex[11].match(line)):
            # match stream
            m = self.regex[11].match(line)
            t = m.group(1)          # stream type
            s = int(m.group(2), 10) # stream number
            n = m.group(3)

            self.debugLog("Found Stream: Type {:s}, Number {:02X}". format(t, s))
            self.lastType = t
            if (t == "audio" and s >= 1 and s <= 8):
                self.numStreams = s
                self.streamInfo["Streams"][s-1] = n
            if (t == "data"):
                # CRITICAL FIX: Bounds check to prevent crash during nrsc5 restart
                if self.numServices < len(self.streamInfo["Services"]):
                    self.streamInfo["Services"][self.numServices] = n
                    self.numServices += 1
                else:
                    self.debugLog(f"Warning: numServices={self.numServices} exceeds Services array size")
        elif (self.regex[12].match(line)):
            # match port and data_service_type
            m = self.regex[12].match(line)
            id = int(m.group(1), 10)
            p = int(m.group(2), 16)
            t = int(m.group(3), 10)
            self.debugLog("\tFound Port: {:03X}". format(p))
            
            if (self.lastType == "audio" and self.numStreams > 0):
                self.streams[self.numStreams-1].append(p)
            if ((self.lastType == "data") and (id == 0) and (self.numServices > 0)):
                # CRITICAL FIX: Bounds check
                if self.numServices <= len(self.streamInfo["SvcTypes"]):
                    self.streamInfo["SvcTypes"][self.numServices-1] = self.service_data_type_name(t)
        elif (self.regex[18].match(line)):
            # match program type
            m = self.regex[18].match(line)
            id = int(m.group(1), 10)
            p = int(m.group(2), 16)
            t = int(m.group(3), 10)
            
            if ((self.lastType == "audio") and (id == 0) and (self.numStreams > 0)):
                self.streamInfo["Programs"][self.numStreams-1] = self.program_type_name(t)
        elif (self.regex[19].match(line)):
            # match synchronized
            self.set_synchronization(1)
        elif (self.regex[20].match(line)):
            # match lost synch
            self.set_synchronization(0)
        elif (self.regex[21].match(line)):
            # match lost device
            self.set_synchronization(-1)
        elif (self.regex[22].match(line)):
            # match Open device failed
            self.on_btnStop_clicked(None)
            self.set_synchronization(-1)
            
    def getControls(self):
        global resDir
        # setup gui
        builder = Gtk.Builder()
        builder.add_from_file(os.path.join(resDir,"mainForm.glade"))
        builder.connect_signals(self)
        
        # Windows
        self.mainWindow = builder.get_object("mainWindow")
        self.mainWindow.set_icon_from_file(os.path.join(resDir,"logo.png"))
        self.mainWindow.connect("delete-event", self.shutdown)
        self.mainWindow.connect("destroy", Gtk.main_quit)
        self.about_dialog = None
        
        # get controls
        self.image1        = builder.get_object("image1")
        self.notebookMain  = builder.get_object("notebookMain")
        self.frameCover    = builder.get_object("frameCover")
        self.alignmentCover = builder.get_object("alignmentCover")
        self.imgCover      = builder.get_object("imgCover")
        self.alignmentMap  = builder.get_object("alignment_map")
        self.imgMap        = builder.get_object("imgMap")
        self.spinFreq      = builder.get_object("spinFreq")
        self.cbxAspect     = builder.get_object("cbxAspect")
        self.cbxSDRRadio   = builder.get_object("cbxSDRRadio")
        self.spinGain      = builder.get_object("spinGain")
        self.cbAutoGain    = builder.get_object("cbAutoGain")
        self.spinPPM       = builder.get_object("spinPPM")
        self.lblRTL        = builder.get_object("lblRTL")
        self.spinRTL       = builder.get_object("spinRTL")
        self.label14b      = builder.get_object("label14b")
        self.lblDevIP      = builder.get_object("lblDevIP")
        self.txtDevIP      = builder.get_object("txtDevIP")
        self.cbDevIP       = builder.get_object("cbDevIP")
        self.lblSdrPlaySer = builder.get_object("lblSdrPlaySer")
        self.txtSDRPlaySer = builder.get_object("txtSDRPlaySer")
        self.label14d      = builder.get_object("label14d")
        self.lblSDRPlayAnt = builder.get_object("lblSDRPlayAnt")
        self.cbxSDRPlayAnt = builder.get_object("cbxSDRPlayAnt")
        self.label14a      = builder.get_object("label14a")
        self.cbLog         = builder.get_object("cbLog")
        self.cbCovers      = builder.get_object("cbCovers")
        self.lblCoverIncl  = builder.get_object("lblCoverIncl")
        self.cbCoverIncl   = builder.get_object("cbCoverIncl")
        self.lblExtend     = builder.get_object("lblExtend")
        self.cbExtend      = builder.get_object("cbExtend")
        self.btnPlay       = builder.get_object("btnPlay")
        self.btnStop       = builder.get_object("btnStop")
        self.btnBookmark   = builder.get_object("btnBookmark")
        self.btnDelete     = builder.get_object("btnDelete")
        self.btnMap        = builder.get_object("btnMap")
        self.radMapTraffic = builder.get_object("radMapTraffic")
        self.radMapWeather = builder.get_object("radMapWeather")
        self.map_progress  = builder.get_object("map_progress")
        self.txtTitle      = builder.get_object("txtTitle")
        self.txtArtist     = builder.get_object("txtArtist")
        self.txtAlbum      = builder.get_object("txtAlbum")
        self.txtGenre      = builder.get_object("txtGenre")
        self.lblName       = builder.get_object("lblName")
        self.lblSlogan     = builder.get_object("lblSlogan")
        self.lblMessage    = builder.get_object("lblMessage")
        self.lblAlert      = builder.get_object("lblAlert")
        self.txtMessage2   = builder.get_object("txtMessage2")
        self.txtAlert2     = builder.get_object("txtAlert2")
        self.btnAudioPrgs0 = builder.get_object("btn_audio_prgs0")
        self.btnAudioPrgs1 = builder.get_object("btn_audio_prgs1")
        self.btnAudioPrgs2 = builder.get_object("btn_audio_prgs2")
        self.btnAudioPrgs3 = builder.get_object("btn_audio_prgs3")
        self.btnAudioPrgs4 = builder.get_object("btn_audio_prgs4")
        self.btnAudioPrgs5 = builder.get_object("btn_audio_prgs5")
        self.btnAudioPrgs6 = builder.get_object("btn_audio_prgs6")
        self.btnAudioPrgs7 = builder.get_object("btn_audio_prgs7")
        self.btnAudioLbl0  = builder.get_object("btn_audio_lbl0")
        self.btnAudioLbl1  = builder.get_object("btn_audio_lbl1")
        self.btnAudioLbl2  = builder.get_object("btn_audio_lbl2")
        self.btnAudioLbl3  = builder.get_object("btn_audio_lbl3")
        self.btnAudioLbl4  = builder.get_object("btn_audio_lbl4")
        self.btnAudioLbl5  = builder.get_object("btn_audio_lbl5")
        self.btnAudioLbl6  = builder.get_object("btn_audio_lbl6")
        self.btnAudioLbl7  = builder.get_object("btn_audio_lbl7")
        self.lblAudioPrgs0 = builder.get_object("lbl_audio_prgs0")
        self.lblAudioPrgs1 = builder.get_object("lbl_audio_prgs1")
        self.lblAudioPrgs2 = builder.get_object("lbl_audio_prgs2")
        self.lblAudioPrgs3 = builder.get_object("lbl_audio_prgs3")
        self.lblAudioPrgs4 = builder.get_object("lbl_audio_prgs4")
        self.lblAudioPrgs5 = builder.get_object("lbl_audio_prgs5")
        self.lblAudioPrgs6 = builder.get_object("lbl_audio_prgs6")
        self.lblAudioPrgs7 = builder.get_object("lbl_audio_prgs7")
        self.lblAudioSvcs0 = builder.get_object("lbl_audio_svcs0")
        self.lblAudioSvcs1 = builder.get_object("lbl_audio_svcs1")
        self.lblAudioSvcs2 = builder.get_object("lbl_audio_svcs2")
        self.lblAudioSvcs3 = builder.get_object("lbl_audio_svcs3")
        self.lblAudioSvcs4 = builder.get_object("lbl_audio_svcs4")
        self.lblAudioSvcs5 = builder.get_object("lbl_audio_svcs5")
        self.lblAudioSvcs6 = builder.get_object("lbl_audio_svcs6")
        self.lblAudioSvcs7 = builder.get_object("lbl_audio_svcs7")
        self.lblDataSvcs0  = builder.get_object("lbl_data_svcs0")
        self.lblDataSvcs1  = builder.get_object("lbl_data_svcs1")
        self.lblDataSvcs2  = builder.get_object("lbl_data_svcs2")
        self.lblDataSvcs3  = builder.get_object("lbl_data_svcs3")
        self.lblDataType0  = builder.get_object("lbl_data_svcs10")
        self.lblDataType1  = builder.get_object("lbl_data_svcs11")
        self.lblDataType2  = builder.get_object("lbl_data_svcs12")
        self.lblDataType3  = builder.get_object("lbl_data_svcs13")
        self.lblCall       = builder.get_object("lblCall")
        self.lblGain       = builder.get_object("lblGain")
        self.lblBitRate    = builder.get_object("lblBitRate")
        self.lblBitRate2   = builder.get_object("lblBitRate2")
        self.lblError      = builder.get_object("lblError")
        self.lblMerLower   = builder.get_object("lblMerLower")
        self.lblMerUpper   = builder.get_object("lblMerUpper")
        self.lblBerNow     = builder.get_object("lblBerNow")
        self.lblBerAvg     = builder.get_object("lblBerAvg")
        self.lblBerMin     = builder.get_object("lblBerMin")
        self.lblBerMax     = builder.get_object("lblBerMax")
        self.imgNoSynch    = builder.get_object("img_nosynch")
        self.imgSynch      = builder.get_object("img_synchpilot")
        self.imgLostDevice = builder.get_object("img_lostdevice")
        self.lvBookmarks   = builder.get_object("listviewBookmarks")
        self.lsBookmarks   = Gtk.ListStore(str, str, int)
        
        self.lvBookmarks.set_model(self.lsBookmarks)
        self.lvBookmarks.get_selection().connect("changed", self.on_lvBookmarks_selection_changed)
        
        self.image1.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file(os.path.join(resDir,"weather.png")))
        self.imgNoSynch.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file(os.path.join(resDir,"nosynch.png")))
        self.imgSynch.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file(os.path.join(resDir,"synchpilot.png")))
        self.imgLostDevice.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file(os.path.join(resDir,"lostdevice.png")))
        self.btnMap.set_icon_widget(self.image1)
    
        self.mainWindow.connect("check-resize", self.on_cover_resize)

        self.alignmentCover.set_sensitive(True)
        self.alignmentCover.set_has_window(True)
        self.alignmentCover.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
        self.alignmentCover.connect("button-press-event", self.on_alignmentCover_clicked)

    def initStreamInfo(self):
        # stream information
        self.streamInfo = {
            "Callsign": "",         # station callsign
            "Slogan": "",           # station slogan
            "Message": "",          # station message
            "Alert": "",            # station alert
            "Title": "",            # track title
            "Album": "",            # track album
            "Genre": "",            # track genre
            "Artist": "",           # track artist
            "Cover": "",            # filename of track cover
            "Logo": "",             # station logo
            "Streams": ["","","","","","","",""], # audio stream names
            "Programs": ["","","","","","","",""], # audio stream types
            "Services": ["","","",""], # data service names
            "SvcTypes": ["","","",""], # data service types
            "Bitrate": 0,           # current stream bit rate
            "MER": [0,0],           # modulation error ratio: lower, upper
            "BER": [0,0,0,0],       # bit error rate: current, average, min, max
            "Gain": 0               # automatic gain
        }
        
        self.streams      = [[],[],[],[],[],[],[],[]]
        self.numStreams   = 0
        self.numServices  = 0
        self.lastType     = 0
        
        # clear status info
        self.lblCall.set_label("")
        self.btnAudioLbl0.set_label("")
        self.btnAudioLbl1.set_label("")
        self.btnAudioLbl2.set_label("")
        self.btnAudioLbl3.set_label("")
        self.btnAudioLbl4.set_label("")
        self.btnAudioLbl5.set_label("")
        self.btnAudioLbl6.set_label("")
        self.btnAudioLbl7.set_label("")
        self.lblBitRate.set_label("")
        self.lblBitRate2.set_label("")
        self.lblError.set_label("")
        self.lblGain.set_label("")
        self.txtTitle.set_text("")
        self.txtArtist.set_text("")
        self.txtAlbum.set_text("")
        self.txtGenre.set_text("")
        self.imgCover.clear()
        self.coverImage = ""
        self.lblName.set_label("")
        self.lblSlogan.set_label("")
        self.lblSlogan.set_tooltip_text("")
        self.lblMessage.set_label("")
        self.lblMessage.set_tooltip_text("")
        if (self.txtMessage2):
            self.txtMessage2.set_label("")
            self.txtMessage2.set_tooltip_text("")
        self.lblAlert.set_label("")
        self.lblAlert.set_tooltip_text("")
        if (self.txtAlert2):
            self.txtAlert2.set_label("")
            self.txtAlert2.set_tooltip_text("")
        self.btnAudioPrgs0.set_sensitive(False)
        self.btnAudioPrgs1.set_sensitive(False)
        self.btnAudioPrgs2.set_sensitive(False)
        self.btnAudioPrgs3.set_sensitive(False)
        self.btnAudioPrgs4.set_sensitive(False)
        self.btnAudioPrgs5.set_sensitive(False)
        self.btnAudioPrgs6.set_sensitive(False)
        self.btnAudioPrgs7.set_sensitive(False)
        self.lblAudioPrgs0.set_label("")
        self.lblAudioPrgs0.set_sensitive(False)
        self.lblAudioPrgs1.set_label("")
        self.lblAudioPrgs1.set_sensitive(False)
        self.lblAudioPrgs2.set_label("")
        self.lblAudioPrgs2.set_sensitive(False)
        self.lblAudioPrgs3.set_label("")
        self.lblAudioPrgs3.set_sensitive(False)
        self.lblAudioPrgs4.set_label("")
        self.lblAudioPrgs4.set_sensitive(False)
        self.lblAudioPrgs5.set_label("")
        self.lblAudioPrgs5.set_sensitive(False)
        self.lblAudioPrgs6.set_label("")
        self.lblAudioPrgs6.set_sensitive(False)
        self.lblAudioPrgs7.set_label("")
        self.lblAudioPrgs7.set_sensitive(False)
        self.lblAudioSvcs0.set_label("")
        self.lblAudioSvcs0.set_sensitive(False)
        self.lblAudioSvcs1.set_label("")
        self.lblAudioSvcs1.set_sensitive(False)
        self.lblAudioSvcs2.set_label("")
        self.lblAudioSvcs2.set_sensitive(False)
        self.lblAudioSvcs3.set_label("")
        self.lblAudioSvcs3.set_sensitive(False)
        self.lblAudioSvcs4.set_label("")
        self.lblAudioSvcs4.set_sensitive(False)
        self.lblAudioSvcs5.set_label("")
        self.lblAudioSvcs5.set_sensitive(False)
        self.lblAudioSvcs6.set_label("")
        self.lblAudioSvcs6.set_sensitive(False)
        self.lblAudioSvcs7.set_label("")
        self.lblAudioSvcs7.set_sensitive(False)
        self.lblDataSvcs0.set_label("")
        self.lblDataSvcs1.set_label("")
        self.lblDataSvcs2.set_label("")
        self.lblDataSvcs3.set_label("")
        self.lblDataType0.set_label("")
        self.lblDataType1.set_label("")
        self.lblDataType2.set_label("")
        self.lblDataType3.set_label("")
        self.lblMerLower.set_label("")
        self.lblMerUpper.set_label("")
        self.lblBerNow.set_label("")
        self.lblBerAvg.set_label("")
        self.lblBerMin.set_label("")
        self.lblBerMax.set_label("")
        self.set_synchronization(0)
    
    def loadSettings(self):
        global aasDir, cfgDir, mapDir

        # load station logos
        try:
            stationLogos = os.path.join(cfgDir,"stationLogos.json")
            if (os.path.isfile(stationLogos)):
                with open(stationLogos, mode='r') as f:
                    self.stationLogos = json.load(f)
                for station in self.stationLogos:
                    while (len(self.stationLogos[station]) < 8):
                        self.stationLogos[station].append("")
        except:
            self.debugLog("Error: Unable to load station logo database", True)

        #load cover metadata
        try:
            coverMetas = os.path.join(cfgDir,"coverMetas.json")
            if (os.path.isfile(coverMetas)):
                with open(coverMetas, mode='r') as f:
                    self.coverMetas = json.load(f)
        except:
            self.debugLog("Error: Unable to load cover metadata database", True)

        self.mainWindow.resize(self.defaultSize[0],self.defaultSize[1])

        # load settings
        try:
            configFile = os.path.join(cfgDir,"config.json")
            if (os.path.isfile(configFile)):
                with open(configFile, mode='r') as f:
                    config = json.load(f)
                
                if "MapData" in config:
                    self.mapData = config["MapData"]
                    if   (self.mapData["mapMode"] == 0):
                        self.radMapTraffic.set_active(True)
                        self.radMapTraffic.toggled()
                    elif (self.mapData["mapMode"] == 1):
                        self.radMapWeather.set_active(True)
                        self.radMapWeather.toggled()
                
                if "Width" and "Height" in config:
                    self.mainWindow.resize(config["Width"],config["Height"])
                else:
                    self.mainWindow.resize(self.defaultSize)

                self.mainWindow.move(config["WindowX"], config["WindowY"])
                self.spinFreq.set_value(config["Frequency"])
                self.streamNum = config["Stream"]-1
                if (self.streamNum < 0):
                    self.streamNum = 0
                self.set_program_btns()
                self.spinGain.set_value(config["Gain"])
                self.cbAutoGain.set_active(config["AutoGain"])
                self.spinPPM.set_value(config["PPMError"])
                self.spinRTL.set_value(config["RTL"])
                if ("SDRRadio" in config):
                    self.cbxSDRRadio.set_active_id("rcvr"+config["SDRRadio"])
                if ("SDRPlaySer" in config):
                    self.txtSDRPlaySer.set_text(config["SDRPlaySer"])
                if ("SDRPlayAnt" in config):
                    self.cbxSDRPlayAnt.set_active_id("ant"+config["SDRPlayAnt"])
                self.cbLog.set_active(config["LogToFile"])
                if ("DLoadArt" in config):
                    self.cbCovers.set_active(config["DLoadArt"])
                if ("StationArt" in config):
                    self.cbCoverIncl.set_active(config["StationArt"])
                if ("ExtendQ" in config):
                    self.cbExtend.set_active(config["ExtendQ"])
                if ("UseIP" in config):
                    self.cbDevIP.set_active(config["UseIP"])
                if ("DevIP" in config):
                    self.txtDevIP.set_text(config["DevIP"])
                self.bookmarks = config["Bookmarks"]
                for bookmark in self.bookmarks:
                    self.lsBookmarks.append(bookmark)
        except:
            self.debugLog("Error: Unable to load config", True)
        
        # create cfg directory
        if (not os.path.isdir(cfgDir)):
            try:
                os.mkdir(cfgDir)
                self.debugLog("Needed to create config directory!")
            except:
                self.debugLog("Error: Unable to create config directory", True)
                cfgDir = None

        # create aas directory
        if (not os.path.isdir(aasDir)):
            try:
                os.mkdir(aasDir)
            except:
                self.debugLog("Error: Unable to create AAS directory", True)
                aasDir = None
        
        # create map directory
        if (not os.path.isdir(mapDir)):
            try:
                os.mkdir(mapDir)
            except:
                self.debugLog("Error: Unable to create Map directory", True)
                mapDir = None
        
        # open log file
        try:
            # Close existing logFile to prevent memory leak before opening new one
            if hasattr(self, 'logFile') and self.logFile is not None and not self.logFile.closed:
                self.logFile.close()
            self.logFile = open("nrsc5.log", mode='a')
        except:
            self.debugLog("Error: Unable to create log file", True) 
    
    def shutdown(self, *args):
        global cfgDir
        # stop map viewer animation if it's running
        if (self.mapViewer is not None and self.mapViewer.animateTimer is not None):
            self.mapViewer.animateTimer.cancel()
            self.mapViewer.animateStop = True
            
            while (self.mapViewer.animateBusy):
                self.debugLog("Animation Busy - Stopping")
                if (self.mapViewer.animateTimer is not None):
                    self.mapViewer.animateTimer.cancel()
                time.sleep(0.25)
        
        self.playing = False
        
        # kill nrsc5 if it's running
        if (self.nrsc5 is not None and not self.nrsc5.poll()):
            self.nrsc5.kill()
        
        # shut down status timer if it's running
        if (self.statusTimer is not None):
            self.statusTimer.cancel()
        
        # wait for player thread to exit
        if (self.playerThread is not None and self.playerThread.is_alive()):
            self.playerThread.join(1)
        
        # close log file if it's enabled
        if (self.logFile is not None):
            self.logFile.close()
        
        # save settings
        try:
            with open(os.path.join(cfgDir,"config.json"), mode='w') as f:
                winX, winY = self.mainWindow.get_position()
                width, height = self.mainWindow.get_size()
                config = {
                    "CfgVersion": "1.1.0",
                    "WindowX"   : winX,
                    "WindowY"   : winY,
                    "Width"     : width,
                    "Height"    : height,
                    "Frequency" : self.spinFreq.get_value(),
                    "Stream"    : int(self.streamNum)+1,
                    "Gain"      : self.spinGain.get_value(),
                    "AutoGain"  : self.cbAutoGain.get_active(),
                    "PPMError"  : int(self.spinPPM.get_value()),
                    "RTL"       : int(self.spinRTL.get_value()),
                    "DevIP"     : self.txtDevIP.get_text(),
                    "SDRRadio"   : self.cbxSDRRadio.get_active_text(),
                    "SDRPlaySer" : self.txtSDRPlaySer.get_text(),
                    "SDRPlayAnt" : self.cbxSDRPlayAnt.get_active_text(),
                    "LogToFile" : self.cbLog.get_active(),
                    "DLoadArt"  : self.cbCovers.get_active(),
                    "StationArt" : self.cbCoverIncl.get_active(),
                    "ExtendQ"   : self.cbExtend.get_active(),
                    "UseIP"     : self.cbDevIP.get_active(),
                    "Bookmarks" : self.bookmarks,
                    "MapData"   : self.mapData,
                }
                # sort bookmarks
                config["Bookmarks"].sort(key=lambda t: t[2])
                
                json.dump(config, f, indent=2)
            
            with open(os.path.join(cfgDir,"stationLogos.json"), mode='w') as f:
                json.dump(self.stationLogos, f, indent=2)

            with open(os.path.join(cfgDir,"coverMetas.json"), mode='w') as f:
                json.dump(self.coverMetas, f, indent=2)
        except Exception as e:
            try:
                print(e.message, e.args)
            except:
                print(e)
            self.debugLog("Error: Unable to save config", True)
    
    def addWeatherMap(self, mapFile):
        """Add a weather map file and maintain size limit"""
        self.weatherMaps.append(mapFile)
        
        # Limit the size of weatherMaps list to prevent unbounded growth
        if len(self.weatherMaps) > self.maxWeatherMaps:
            # Remove oldest maps from the list
            self.weatherMaps = self.weatherMaps[-self.maxWeatherMaps:]
    
    def debugLog(self, message, force=False):
        if (debugMessages or force):
            now = datetime.datetime.now()
            print (now.strftime("%b %d %H:%M:%S : ") + message)

class NRSC5_SLPopup(object):
    def __init__(self, parent, callback, data):
        global resDir
        # setup gui
        builder = Gtk.Builder()
        builder.add_from_file(os.path.join(resDir,"entryForm.glade"))
        builder.connect_signals(self)

        self.parent        = parent
        self.callback      = callback
        self.data          = data
        
        # get the controls
        self.entryWindow    = builder.get_object("entryWindow")
        self.txtEntry       = builder.get_object("txtEntry")
        self.btn_cancel     = builder.get_object("btn_cancel")
        self.btn_ok         = builder.get_object("btn_ok")

        self.entryWindow.connect("delete-event", self.on_entryWindow_delete)

    def on_cleanup(self, btn):
        if (btn == self.btn_cancel):
            self.txtEntry.set_text('')
        self.entryWindow.close()

    def on_entryWindow_delete(self, *args):
        self.callback()                                                             # run the callback    

class NRSC5_Map(object):
    def __init__(self, parent, callback, data):
        global resDir
        # setup gui
        builder = Gtk.Builder()
        builder.add_from_file(os.path.join(resDir,"mapForm.glade"))
        builder.connect_signals(self)
        
        self.parent         = parent                                                # parent class
        self.callback       = callback                                              # callback function
        self.data           = data                                                  # map data
        self.animateTimer   = None                                                  # timer used to animate weather maps
        self.animateBusy    = False
        self.animateStop    = False
        self.weatherMaps    = parent.weatherMaps                                    # list of weather maps sorted by time 
        self.mapIndex       = 0                                                     # the index of the next weather map to display
        
        # get the controls
        self.mapWindow      = builder.get_object("mapWindow")
        self.imgMap         = builder.get_object("imgMap")
        self.radMapWeather  = builder.get_object("radMapWeather")
        self.radMapTraffic  = builder.get_object("radMapTraffic")
        self.chkAnimate     = builder.get_object("chkAnimate")
        self.chkScale       = builder.get_object("chkScale")
        self.spnSpeed       = builder.get_object("spnSpeed")
        self.adjSpeed       = builder.get_object("adjSpeed")
        self.imgKey         = builder.get_object("imgKey")

        self.imgKey.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file(os.path.join(resDir,"radar_key.png")))
        self.mapWindow.connect("delete-event", self.on_mapWindow_delete)
        
        self.config = data["viewerConfig"]                                          # get the map viewer config
        self.mapWindow.resize(*self.config["windowSize"])                           # set the window size
        self.mapWindow.move(*self.config["windowPos"])                              # set the window position
        if (self.config["mode"] == 0):
            self.radMapTraffic.set_active(True)                                     # set the map radio buttons
        elif (self.config["mode"] == 1):
            self.radMapWeather.set_active(True)
        self.setMap(self.config["mode"])                                            # display the current map
        
        self.chkAnimate.set_active(self.config["animate"])                          # set the animation mode
        self.chkScale.set_active(self.config["scale"])                              # set the scale mode
        self.spnSpeed.set_value(self.config["animationSpeed"])                      # set the animation speed
    
    def on_radMap_toggled(self, btn):
        if (btn.get_active()):
            if (btn == self.radMapTraffic):
                self.config["mode"] = 0
                self.imgKey.set_visible(False)
                
                # CRITICAL FIX: Properly cancel and clear timer
                if (self.animateTimer is not None):
                    self.animateTimer.cancel()
                    self.animateTimer = None
                
                self.setMap(0)
                
            elif (btn == self.radMapWeather):
                self.config["mode"] = 1
                self.imgKey.set_visible(True)
                
                # CRITICAL FIX: Cancel any existing timer first
                if (self.animateTimer is not None):
                    self.animateTimer.cancel()
                    self.animateTimer = None
                
                # check if animate is enabled and start animation
                if (self.config["animate"]):
                    self.animateTimer = Timer(0.05, self.animate)
                    self.animateTimer.start()
                else:
                    self.setMap(1)
    
    def on_chkAnimate_toggled(self, btn):
        self.config["animate"] = self.chkAnimate.get_active()
        
        # CRITICAL FIX: Always cancel existing timer first
        if (self.animateTimer is not None):
            self.animateTimer.cancel()
            self.animateTimer = None
        
        if (self.config["animate"] and self.config["mode"] == 1):
            # start animation
            self.animateTimer = Timer(self.config["animationSpeed"], self.animate)
            self.animateTimer.start()
        else:
            # animation already stopped above
            self.mapIndex = len(self.weatherMaps)-1
            self.setMap(self.config["mode"])
    
    def on_chkScale_toggled(self, btn):
        self.config["scale"] = btn.get_active()
        if (self.config["mode"] == 1):
            if (self.config["animate"]):
                i = len(self.weatherMaps)-1 if (self.mapIndex-1 < 0) else self.mapIndex-1               # get the index for the current map in the animation
                self.showImage(self.weatherMaps[i], self.config["scale"])                               # show the current map in the animation
            else:
                self.showImage(self.data["weatherNow"], self.config["scale"])                           # show the most recent map
    
    def on_spnSpeed_value_changed(self, spn):
        self.config["animationSpeed"] = self.adjSpeed.get_value()                                       # get the animation speed
    
    def on_mapWindow_delete(self, *args):
        # cancel the timer if it's running
        if (self.animateTimer is not None):
            self.animateTimer.cancel()
            self.animateStop = True
        
        # wait for animation to finish
        while (self.animateBusy):
            self.parent.debugLog("Waiting for animation to finish")
            if (self.animateTimer is not None):
                self.animateTimer.cancel()
            time.sleep(0.25)
        
        self.config["windowPos"]  = self.mapWindow.get_position()                                       # store current window position
        self.config["windowSize"] = self.mapWindow.get_size()                                           # store current window size
        self.callback()                                                                                 # run the callback
    
    def animate(self):
        global imgLANCZOS
        fileName = self.weatherMaps[self.mapIndex] if len(self.weatherMaps) else ""
        if (os.path.isfile(fileName)):
            self.animateBusy = True
            
            # CRITICAL FIX: Cancel existing timer before creating new one
            if (self.animateTimer is not None):
                self.animateTimer.cancel()
                self.animateTimer = None

            try:
                if (self.config["scale"]):
                    with Image.open(fileName) as img:
                        resized = img.resize((600,600), imgLANCZOS)
                        mapImg = imgToPixbuf(resized)
                        del resized  # Explicit cleanup
                else:
                    with Image.open(fileName) as img:
                        img_copy = img.copy()
                        mapImg = imgToPixbuf(img_copy)
                        del img_copy  # Explicit cleanup
             
                if (self.config["animate"] and self.config["mode"] == 1 and not self.animateStop):
                    self.imgMap.set_from_pixbuf(mapImg)
                    del mapImg  # Free pixbuf memory
                    
                    self.mapIndex += 1
                    if (self.mapIndex >= len(self.weatherMaps)):
                        self.mapIndex = 0
                        self.animateTimer = Timer(2, self.animate)
                    else:
                        self.animateTimer = Timer(self.config["animationSpeed"], self.animate)
                     
                    self.animateTimer.start()
                else:
                    del mapImg
                    self.animateTimer = None
            finally:
                # Always reset busy flag
                self.animateBusy = False
        else:
            self.chkAnimate.set_active(False)
            self.mapIndex = 0
    
    def showImage(self, fileName, scale):
        global imgLANCZOS
        
        if (os.path.isfile(fileName)):
            try:
                if (scale):
                    with Image.open(fileName) as img:
                        mapImg = img.resize((600,600), imgLANCZOS)
                        pixbuf = imgToPixbuf(mapImg)
                        self.imgMap.set_from_pixbuf(pixbuf)
                        del mapImg
                        del pixbuf
                else:
                    with Image.open(fileName) as img:
                        img_copy = img.copy()
                        pixbuf = imgToPixbuf(img_copy)
                        self.imgMap.set_from_pixbuf(pixbuf)
                        del img_copy
                        del pixbuf
            except Exception as e:
                print(f"Error loading image {fileName}: {e}")
                self.imgMap.set_from_icon_name("MISSING_IMAGE", Gtk.IconSize.DIALOG)
        else:
            self.imgMap.set_from_icon_name("MISSING_IMAGE", Gtk.IconSize.DIALOG)
    
    def setMap(self, map):
        global mapDir
        if (map == 0):
            self.showImage(os.path.join(mapDir, "TrafficMap.png"), False)                    # show traffic map
        elif (map == 1):
            self.showImage(self.data["weatherNow"], self.config["scale"])                    # show weather map
    
    def updated(self, imageType):
        if   (self.config["mode"] == 0):
            self.setMap(0)
        elif (self.config["mode"] == 1):
            self.setMap(1)
            self.mapIndex = len(self.weatherMaps)-1

def dtToTs(dt):
    # convert datetime to timestamp
    return int((dt - datetime.datetime(1970, 1, 1, tzinfo=tz.tzutc())).total_seconds())

def tsToDt(ts):
    # convert timestamp to datetime
    return datetime.datetime.utcfromtimestamp(ts)

def imgToPixbuf(img):
    # convert PIL.Image to gdk.pixbuf
    img_bytes = img.tobytes()
    data = GLib.Bytes.new(img_bytes)
    pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(data, GdkPixbuf.Colorspace.RGB, 'A' in img.getbands(),
                                           8, img.width, img.height, len(img.getbands())*img.width)
    del img_bytes
    del data
    return pixbuf


if __name__ == "__main__":
    # show main window and start main thread
    nrsc5_dui = NRSC5_DUI()
    nrsc5_dui.mainWindow.show()
    if (debugMessages and debugAutoStart):
        nrsc5_dui.on_btnPlay_clicked(nrsc5_dui)

    Gtk.main()


================================================
FILE: README.md
================================================
NRSC5-DUI is a graphical interface for [nrsc5](https://github.com/theori-io/nrsc5). It makes it easy to play your favorite FM HD radio stations using an RTL-SDR or SDRPlay dongle. It will also display weather radar and traffic maps found on most iHeart radio stations.

This version is really a fork of a fork of the original nrsc5-gui: The first was developed by [cmnybo](https://github.com/cmnybo/nrsc5-gui) and subsequently modified by [zefie](https://github.com/zefie/nrsc5-gui). It merges the features of the former to the architecture of the latter, while adding several additional control and display features.

As such, we have changed the name to 'DUI' as a play on the Italian word for 'two', this being a second generation graphical user interface for nrsc5. (I'll be here all week. Please tip your waitresses.)

# Dependencies

The following programs are required to run NRSC5-DUI

* [Python 3](https://www.python.org/downloads/release)
* [PyGObject](https://pygobject.readthedocs.io/en/latest/)
* [Pillow](https://pillow.readthedocs.io/en/stable/)
* [NumPy](http://www.numpy.org)
* [Python Dateutil](https://pypi.org/project/python-dateutil)
* [urllib3](https://pypi.org/project/urllib3)
* [pyOpenSSL](https://pypi.org/project/pyOpenSSL)
* [musicbrainzngs](https://pypi.org/project/musicbrainzngs)
* [nrsc5 for RTL_SDR only](https://github.com/theori-io/nrsc5) or [nrsc5 for SDRPlay](https://github.com/fventuri/nrsc5)

It is also assumed you have a fully operational Gtk3 environment installed from [Homebrew](https://brew.sh/), if running on macOS.

# Setup
1. Install the latest version of Python, PyGObject, Pillow, and other python dependencies. Once Python is installed, you may install the dependencies by giving the command `pip install -r <path_to requirements.txt>`  
2. Compile and install nrsc5. If using an SDRPlay, you must compile and install the version provided by [fventuri](https://github.com/fventuri/nrsc5).  
3. Install nrsc5-dui files in a directory where you have write permissions.  
4. Optional: To use either the `macOS arm64` or `linux intel x86_64` binary version of nrsc5-dui, download the the appropriate file from the [Releases page](https://github.com/markjfine/nrsc5-dui/releases). Uncompress it and copy the file `nrsc5-dui` to the same directory where `nrsc5-dui.py` resides. Note that the macOS version has only been tested on a MacBook Pro with an Apple M1 chip, running Tahoe 26.3 in an arm64 architecture. Similarly, the linux version has only been tested on a Lenovo Legion 5 Pro with a 12th Gen Intel Core i7 chip, running Fedora 43 in an x86_64 architecture. Your mileage may vary.  

The configuration and resource directories will be created in a new `cfg` and `res` directory under where nrsc5-dui.py resides. Similarly, an `aas` directory will be created for downloaded files and a `map` directory will be created to store weather & traffic maps. The `aas`, `cfg`, and `map` directories may optionally be created in a separate user-defined path as specified within a `$NRSC5DUI_DATA` environment variable.

nrsc5 should be installed in a directory that is in your `$PATH` environment variable. Otherwise the full path to nrsc5 (e.g., `/usr/local/bin/`) may be entered at runtime (see Usage for details, below).

## Windows 10/11 setup notes
One of the goals of this project was to provide a stand-alone, cross-platform application. Please note that NRSC5-DUI will not operate natively in this manner under Windows 10 at this time. This is even when built under a MinGW environment (such as MSYS2) or cross-compiled using MinGW-compatible compilers. The issues found are as follows:  
  
1. The resulting RTL_SDR library used by NRSC5.EXE doesn't seem to work correctly with respect to communicating with the RTL-SDR dongle, as well as any appropriate signal detection and bit error rate evaluation. There has been some success in getting NRSC5.EXE to run using the -H option when the dongle is operating under RTL_TCP on another platform, but again, that's outside a stand-alone operating environment. There is also a question of whether NRSC5.EXE responds to keyboard input properly under a MinGW-environment, which may preclude changing streams (`0` thru `3` keypress) as well as exiting it properly (`q`keypress) without typing Ctrl-C.  
2. PyGObject, which is a critical module, seems to require an older version of Microsoft C/C++ in order to properly build the gi library. This is true when trying to install it using either `pip` or `pacman`, however, some have had success installing PyGObject using `conda`.  
3. Win10, which is not Posix-compliant, does not provide a good pty solution under Python. This is required to spawn and interact with NRSC5.EXE via a pipe. WinPty does exist as an alternative, however it requires a complete rewrite of how the current version of NRSC5-DUI operates. This does not appear to be an issue when running under a MinGW environment.  
  
The bottom line is that some have had success installing and running the application and it's dependencies under specific MinGW environments such as WSL2, but may still require the dongle to operate under RTL_TCP and not directly via NRSC5.EXE. Some legacy Windows executables and libraries have been provided in the `bin` directory for those that wish to experiment further. Feel free to use them at your own risk.

### Usage under Windows Subsystem for Linux (WSL2)
Stephen Ferrell has graciously taken a look at stability issues when running under WSL2g. Specifically, the application would run for ~3 hours until which time the audio would start skipping and the interface would freeze. He used Claude Code to isolate the issues and was extremely successful tracking down several issues impacting nrsc5-dui operation.  
If skipping is still experienced, Stephen recommends disabling the time sync due to a known conflict between the WSL2 backend (PulseAudio) and the Windows host. This can be done by entering:  
`sudo systemctl stop systemd-timesyncd`  
If this works, you can permanently disable it with:  
`sudo systemctl disable systemd-timesyncd`  
If the issue still persists, try adjusting the PulseAudio configuration within your Linux distribution. This can be done by editing the configuration file `/etc/pulse/daemon.conf` and adding/updating the following lines:  
```
high-priority = yes
nice-level = -15
default-fragments = 8
default-fragment-size-msec = 10
```
Once the configuration file is edited, kill PulseAudio by entering `pulseaudio -k` and let it restart automatically.  
You are cautioned that both PulseAudio and pipewire implementations have been known to be buggy under WSL2. Although the above suggestions will improve things, choppy audio may still occur at some point. The only solution is to close and restart nrsc5-dui.

### Usage under MSYS2/Cygwin
Much of the audio skipping problems associated with WSL2 can be avoided by using a version of nrsc5-dui specifically modified by Stephen Ferrell for use under MSYS2/Cygwin. The MSYS2-specific version can be found in the MSYS2 directory. It has been tested for over 36 hours under MSYS2 on Windows 11 without any audio issues. It includes all the features of nrsc5-dui with none of the reliance on Posix-compliant dependencies, such as tty.  
It is recommended that you install each of the dependencies using MSYS2 pacman. As an example:  
`pacman -S mingw-w64-x86_64-python-numpy`  
This may not work correctly for musicbrainz, which under a managed environment should be installed using pip as follows:  
`pip install musicbrainzngs --break-system-packages`  
For those that wish to create a quick-launch CMD file, simply create a CMD file and add the following line:  
`C:\msys64\msys2_shell.cmd -defterm -no-start -mingw64 -here -c /c/msys64/home/<user name>/<nrsc5-dui directory>/nrsc5-dui-msys2.py`  
Remember to change `<user name>` to your user name, and `<nrsc5-dui directory>` to the directory where nrsc5-dui-msys2.py resides. The CMD file could then be double-clicked to launch the application.

# Usage
Please ensure your RTL-SDR dongle or SDRPlay is first connected to an available USB port. Then, from the terminal, start nrsc5-dui by entering:  
`python3 nrsc5-dui.py`  
or something like:  
`python3 nrsc5-dui.py /usr/local/bin/`  
The latter includes the path to nrsc5 when using scripts (like Apple Script) that seemingly ignore the environment.  
You may optionally use the binary version by running it without `python3` or the `.py` extension as follows:  
`nrsc5-dui /usr/local/bin/`

## Settings
You may first change some optional parameters of how nrsc5 works from the Settings tab in nrsc5-dui:  
Set the radio you are using to either RTL_SDR or SDRPlay.  
Set the gain to Auto, or optionally enter an RF gain in dB that has known to work well for some stations.  
Enter a PPM correction value if your RTL-SDR dongle has an offset.  

If using an RTL_SDR:  
Enter the number of the desired device if you have more than one RTL-SDR dongle.  
Enter the IP address that rtl_tcp is listening to and check the Enabled box if you are using a remote RTL-SDR.  

If using an SDRPlay:  
Enter the serial number of the SDRPlay.  
Enter the antenna port used by the SDRPlay.  

Other settings:  
Check `Log to file` to enable writing debug information from nrsc5 to nrsc5.log.  
Check `Download Album Art` to enable automated downloading of album art from MusicBrainz.  
Check `Include Station Art` to display album art that is generated by the station in addition to downloading from MusicBrainz.  
Check `Extended Queries` to apply several MusicBrainz queries to find album art. Turning this option on may be slower than non-extended queries.

## Playing
Enter the frequency in MHz of the station you want to play and either click the triangular Play button on the toolbar, or just hit return. When the receiver attains synchronization, the pilot in the lower left corner of the status bar will turn green. It will return to gray if synchronization is lost. If the device itself becomes 'lost', the pilot will turn red to indicate an error has occurred (this is the theory, though I've yet to see this status message happen in practice). The synchronization process may take about 10 seconds, and the station will begin to play. This depends upon signal strength and whether it's relatively free from adjacent interference. After a short while, the station name will appear to the right of the frequency, and the available streams will show on the two rows of buttons just beneath the frequency entry. Clicking one of these buttons will change to that particular stream. Note: No settings other than stream may be changed while the device is playing. 

## Album Art & Track Info
Some stations will send album art and station logos. These will fill the Album Art tab, as they are made available by the station. Most stations will send the song title, artist, album, and genre. These are displayed in the Track Info pane, also if available.
The user can override what the stations send by enabling the DL Album Art setting. This will use the Title and Artist information to retrieve album art from MusicBrainz. If no album art is found, the station logo will be used, if available. The title, artist, album, and genre (if available) will be cached when new album art is found, and will be automatically displayed when that art is used.
The user can change the logo of the playing station by right-clicking in the Album Art area. This will display a popup prompting you for the URL of an image found on the web. Pasting the URL in the box and clicking 'Ok' will download the image and set the logo of the playing station with it.

## Bookmarks
When a station is playing, you can click the Bookmark Station button to add it to the bookmarks list. You can click on the Name in the bookmarks list to edit it. Double click the Station to tune to that particular station and stream. Click the Delete Bookmark button to delete it. Note that some stations use the default MPS/SPS or HDn naming for their streams. In this case, the respective bookmark will be used to name the stream button.

## Station Info
The station name, slogan, message, and optional alert message will display if the station as pre-programmed them. The current audio bit rate will be displayed here as well as on the status bar. The station's available streams and data services, with a description of each will display, as the station has pre-programmed them. This is a useful feature for noting which stations have [Total Traffic & Weather Network](https://www.ttwnetwork.com/) traffic and weather images.

### Signal Strength
The Modulation Error Ratio for the lower and upper sidebands are displayed as they are determined. Important: High MER values for both sidebands indicates a strong signal. The current, average, minimum and maximum Bit Error Rates will also be displayed as they are determined. High BER values will cause the audio to glitch or drop out. The current BER is also shown on the status bar and may be used as a tuning tool.

Note: The nrsc5 application initially operates on an inverted spectrum for FM signals, using the terms 'lower' and 'upper' to report the MER of the sidebands in a reversed state. The resulting MER values will therefore appear reversed from what a user would see on a standard spectrum display.

## Maps
When listening to radio stations operated by [iHeartMedia](http://iheartmedia.com/iheartmedia/stations), you may view live traffic maps and weather radar. The images are typically sent every few minutes and will fill the tab area once received, processed, and loaded. Clicking the Map Viewer button on the toolbar will open a larger window to view the maps at full size. The weather radar information from the last 12 hours will be stored and can be played back by selecting the Animate Radar option. The delay between frames (in seconds) can be adjusted by changing the Animation Speed value. Other stations provide [Navteq/HERE](https://www.here.com) navigation and weather information which is also displayed. Note that the display of Navteq/HERE data requires the use of nrsc5 v3.00.

### Map Customization
The default map used for the weather radar comes from [OpenStreetMap](https://www.openstreetmap.org). You can replace the map.png image with a map from any website that will let you export map tiles. The tiles used are (35,84) to (81,110) at zoom level 8. The image is 12032x6912 pixels. The portion of the map used for your area is cached in the map directory. If you change the map image, you will have to delete the BaseMap images in the map directory so they will be recreated with the new map. 

## Screenshots
![album art tab](https://raw.githubusercontent.com/markjfine/nrsc5-dui/master/screenshots/Album_Art_Tab.png "Album Art Tab")
![info tab](https://raw.githubusercontent.com/markjfine/nrsc5-dui/master/screenshots/Info_Tab.png "Info Tab")
![settings tab](https://raw.githubusercontent.com/markjfine/nrsc5-dui/master/screenshots/Settings_Tab.png "Settings Tab")
![bookmarks tab](https://raw.githubusercontent.com/markjfine/nrsc5-dui/master/screenshots/Bookmarks_Tab.png "Bookmarks Tab")
![map tab](https://raw.githubusercontent.com/markjfine/nrsc5-dui/master/screenshots/Map_Tab.png "Map Tab")

## Version History
1.0.0 Initial Release  
1.0.1 Fixed compatibility with display scaling  
1.1.0 Added weather radar and traffic map viewer  
1.2.0 zefie update to modern nrsc5 build  
2.0.0 Updated to use the nrsc5 API  
2.1.0 Updated and enhanced operation and use  
2.2.0 Updated for use with SDRPlay and operates with up to 8 possible audio channels (per nrsc5 spec) 


================================================
FILE: nrsc5-dui.py
================================================
#!/usr/bin/python3
# -*- coding: utf-8 -*-

#    NRSC5 DUI - A graphical interface for nrsc5
#    Copyright (C) 2017-2019  Cody Nybo & Clayton Smith, 2019 zefie, 2021-26 Mark J. Fine
#
#    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 <http://www.gnu.org/licenses/>.

#    Updated by zefie for modern nrsc5 ~ 2019
#    Updated and enhanced by markjfine ~ 2021-26
#    Stability enhancements by ferrellsl ~ 2026

import os, pty, select, sys, shutil, re, json, datetime, numpy, glob, time, platform, io
from subprocess import Popen, PIPE
from threading import Timer, Thread
from dateutil import tz
from PIL import Image, ImageFont, ImageDraw, __version__
import gc

print('Using Pillow v'+__version__)

if (int(__version__[0]) < 9):
    imgLANCZOS = Image.LANCZOS
else:
    imgLANCZOS = Image.Resampling.LANCZOS

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GObject, Gdk, GdkPixbuf, GLib

import urllib3
from OpenSSL import SSL

import musicbrainzngs

# print debug messages to stdout (if debugger is attached)
debugMessages = (sys.gettrace() != None)
debugAutoStart = True

if hasattr(sys, 'frozen'):
    runtimeDir = os.path.dirname(sys.executable)  # for py2exe
else:
    runtimeDir = sys.path[0]

if "NRSC5DUI_DATA" in os.environ:
    userDataDir = os.environ["NRSC5DUI_DATA"]
    os.makedirs(userDataDir, exist_ok=True)
else:
    userDataDir = runtimeDir

aasDir = os.path.join(userDataDir, "aas")  # aas (data from nrsc5) file directory
mapDir = os.path.join(userDataDir, "map")  # map (data we process) file directory
resDir = os.path.join(runtimeDir, "res")   # resource (application dependencies) file directory
cfgDir = os.path.join(userDataDir, "cfg")  # config file directory

class NRSC5_DUI(object):
    def __init__(self):
        global runtimeDir, userDataDir, resDir, imgLANCZOS

        self.windowsOS = False          # save our determination as a var in case we change how we determine.

        self.debugLog("Local path determined as " + runtimeDir)
        self.debugLog("User data base directory: " + userDataDir)

        if (platform.system() == 'Windows'):
            # Windows release layout
            self.windowsOS = True
            self.binDir = os.path.join(runtimeDir, "bin")  # windows binaries directory
            self.nrsc5Path = os.path.join(self.binDir,'nrsc5.exe')
        else:
            # Linux/Mac/proper posix
            # if nrsc5 and transcoder are not in the system path, set the full path here
            arg1 = ""
            if (len(sys.argv[1:]) > 0):
                arg1 = sys.argv[1].strip()
            self.nrsc5Path = arg1+"nrsc5"
 
        self.debugLog("OS Determination: Windows = {}".format(self.windowsOS))

        self.app_name       = "NRSC5-DUI"
        self.version        = "2.2.6"
        self.web_addr       = "https://github.com/markjfine/nrsc5-dui"
        self.copyright      = "Copyright © 2017-2019 Cody Nybo & Clayton Smith, 2019 zefie, 2021-26 Mark J. Fine"
        musicbrainzngs.set_useragent(self.app_name,self.version,self.web_addr)

        self.width          = 0         # window width
        self.height         = 0         # window height
        self.mapFile        = os.path.join(resDir, "map.png")
        self.defaultSize    = [490,250] # default width,height of main app
        self.nrsc5          = None      # nrsc5 process
        self.nrsc5master    = None      # required for pipe
        self.nrsc5slave     = None      # required for pipe
        self.playerThread   = None      # player thread
        self.playing        = False     # currently playing
        self.statusTimer    = None      # status update timer
        self.imageChanged   = False     # has the album art changed
        self.xhdrChanged    = False     # has the HDDR data changed
        self.nrsc5Args      = []        # arguments for nrsc5
        self.logFile        = None      # nrsc5 log file
        self.lastImage      = ""        # last image file displayed
        self.coverImage     = ""        # cover image to display
        self.id3Changed     = False     # if the track info changed
        self.lastXHDR       = ""        # the last XHDR data received
        self.lastLOT        = ""        # the last LOT received with XHDR
        self.stationStr     = ""        # current station frequency (string)
        self.streamNum      = 0         # current station stream number
        self.nrsc5msg       = ""        # send key command to nrsc5 (streamNum)
        self.update_btns    = True      # whether to update the stream buttons
        self.bookmarks      = []        # station bookmarks
        self.booknames      = ["","","","","","","",""] # station bookmark names
        self.stationLogos   = {}        # station logos
        self.coverMetas     = {}        # cover metadata
        self.bookmarked     = False     # is current station bookmarked
        self.mapViewer      = None      # map viewer window
        self.weatherMaps    = []        # list of current weathermaps sorted by time
        self.waittime       = 10        # time in seconds to wait for file to exist
        self.waitdivider    = 4         # check this many times per second for file
        self.pixbuf         = None      # store image buffer for rescaling on resize
        self.tLat1          = 0.0       # store upper left lat of HERE traffic image
        self.tLat2          = 0.0       # store lower right lat of HERE traffic image
        self.mimeTypes      = {         # as defined by iHeartRadio anyway, defined here for possible future use
            "4F328CA0":["image/png","png"],
            "1E653E9C":["image/jpg","jpg"],
            "BB492AAC":["text/plain","txt"]
        }
        self.mapData        = {
            "mapMode"       : 1,
            "mapTiles"      : [[0,0,0],[0,0,0],[0,0,0]],
            "mapComplete"   : False,
            "weatherTime"   : 0,
            "weatherPos"    : [0,0,0,0],
            "weatherNow"    : "",
            "weatherID"     : "",
            "viewerConfig"  : {
                "mode"           : 1,
                "animate"        : False,
                "scale"          : True,
                "windowPos"      : (0,0),
                "windowSize"     : (764,632),
                "animationSpeed" : 0.5
            }
        }
        self.maxWeatherMaps = 50  # Limit weather map history to prevent unbounded growth

        # Now initialize components in correct order
        self.getControls()              # get controls and windows
        self.set_program_btns()         # set the stream buttons (needs GUI widgets)
        self.initStreamInfo()           # initilize stream info and clear status widgets
        self.initializeData()           # initialize regex patterns and data structures
        self.http = urllib3.PoolManager()
        
        # Now that GUI is set up, load settings and process maps
        self.loadSettings()
        self.proccessWeatherMaps()

    def __del__(self):
        """Destructor to clean up resources and prevent memory leaks"""
        try:
            if hasattr(self, 'http') and self.http is not None:
                self.http.clear()
            if hasattr(self, 'statusTimer') and self.statusTimer is not None:
                self.statusTimer.cancel()
                self.statusTimer = None
        except:
            pass

    def initializeData(self):
        """Initialize regex patterns and data structures"""
        self.slPopup        = None      # entry for external station logo URL
        self.slData = {
        "externalURL"   : ""
        }

        self.ServiceDataType = {
        0 : "Non_Specific",            
        1 : "News",                     
        3 : "Sports",                   
        29 : "Weather",                  
        31 : "Emergency",                
        65 : "Traffic",                  
        66 : "Image Maps",               
        80 : "Text",                     
        256 : "Advertising",              
        257 : "Financial",                
        258 : "Stock Ticker",             
        259 : "Navigation",               
        260 : "Electronic Program Guide", 
        261 : "Audio",                    
        262 : "Private Data Network",     
        263 : "Service Maintenance",      
        264 : "HD Radio System Services", 
        265 : "Audio-Related Objects",       
        511 : "Reserved for Special Tests"               
        }

        self.ProgramType = {
        0 : "None",
        1 : "News",
        2 : "Information",
        3 : "Sports",
        4 : "Talk",
        5 : "Rock",
        6 : "Classic Rock",
        7 : "Adult Hits",
        8 : "Soft Rock",
        9 : "Top 40",
        10 : "Country",
        11 : "Oldies",
        12 : "Soft",
        13 : "Nostalgia",
        14 : "Jazz",
        15 : "Classical",
        16 : "Rhythm and Blues",
        17 : "Soft Rhythm and Blues",
        18 : "Foreign Language",
        19 : "Religious Music",
        20 : "Religious Talk",
        21 : "Personality",
        22 : "Public",
        23 : "College",
        24 : "Spanish Talk",
        25 : "Spanish Music",
        26 : "Hip-Hop",
        29 : "Weather",
        30 : "Emergency Test",
        31 : "Emergency",
        65 : "Traffic",
        76 : "Special Reading Services"
        }

        self.MIMETypes = {
        0x1E653E9C : "JPEG",
        0x2D42AC3E : "NavTeq",
        0x4F328CA0 : "PNG",
        0x4DC66C5A : "HDC",
        0x4EB03469 : "TTN TPEG 2",
        0x52103469 : "TTN TPEG 3",
        0x82F03DFC : "HERE TPEG",
        0xB39EBEB2 : "TTN TPEG 1",
        0xB7F03DFC : "HERE Image",
        0xB81FFAA8 : "Unknown Test",
        0xBB492AAC : "Text",
        0xBE4B7536 : "Primary Image",
        0xD9C72536 : "Station Logo",
        0xEECB55B6 : "HD TMC",
        0xEF042E96 : "TTN STM Weather",
        0xFF8422D7 : "TTN STM Traffic"
        }

        self.pointer_cursor = Gdk.Cursor(Gdk.CursorType.LEFT_PTR)
        #       self.hand_cursor = Gdk.Cursor(Gdk.CursorType.HAND2)

        # set events on info labels
        self.set_tuning_actions(self.btnAudioPrgs0, "btn_prg0", False, False)
        self.set_tuning_actions(self.btnAudioPrgs1, "btn_prg1", False, False)
        self.set_tuning_actions(self.btnAudioPrgs2, "btn_prg2", False, False)
        self.set_tuning_actions(self.btnAudioPrgs3, "btn_prg3", False, False)
        self.set_tuning_actions(self.btnAudioPrgs4, "btn_prg4", False, False)
        self.set_tuning_actions(self.btnAudioPrgs5, "btn_prg5", False, False)
        self.set_tuning_actions(self.btnAudioPrgs6, "btn_prg6", False, False)
        self.set_tuning_actions(self.btnAudioPrgs7, "btn_prg7", False, False)

        self.set_tuning_actions(self.lblAudioPrgs0, "prg0", True, True)
        self.set_tuning_actions(self.lblAudioPrgs1, "prg1", True, True)
        self.set_tuning_actions(self.lblAudioPrgs2, "prg2", True, True)
        self.set_tuning_actions(self.lblAudioPrgs3, "prg3", True, True)
        self.set_tuning_actions(self.lblAudioPrgs4, "prg4", True, True)
        self.set_tuning_actions(self.lblAudioPrgs5, "prg5", True, True)
        self.set_tuning_actions(self.lblAudioPrgs6, "prg6", True, True)
        self.set_tuning_actions(self.lblAudioPrgs7, "prg7", True, True)

        self.set_tuning_actions(self.lblAudioSvcs0, "svc0", True, True)
        self.set_tuning_actions(self.lblAudioSvcs1, "svc1", True, True)
        self.set_tuning_actions(self.lblAudioSvcs2, "svc2", True, True)
        self.set_tuning_actions(self.lblAudioSvcs3, "svc3", True, True)
        self.set_tuning_actions(self.lblAudioSvcs4, "svc4", True, True)
        self.set_tuning_actions(self.lblAudioSvcs5, "svc5", True, True)
        self.set_tuning_actions(self.lblAudioSvcs6, "svc6", True, True)
        self.set_tuning_actions(self.lblAudioSvcs7, "svc7", True, True)

        # setup bookmarks listview
        nameRenderer = Gtk.CellRendererText()
        nameRenderer.set_property("editable", True)
        nameRenderer.connect("edited", self.on_bookmarkNameEdited)
        
        colStation = Gtk.TreeViewColumn("Station", Gtk.CellRendererText(), text=0)
        colName    = Gtk.TreeViewColumn("Name", nameRenderer, text=1)

        colStation.set_resizable(True)
        colStation.set_sort_column_id(2)
        colName.set_resizable(True)
        colName.set_sort_column_id(1)
        
        self.lvBookmarks.append_column(colStation)
        self.lvBookmarks.append_column(colName)
        
        # regex for getting nrsc5 output
        self.regex = [
        re.compile("^[0-9:]{8,8} Station name: (.*)$"),                                                    #  0 match station name
        re.compile("^[0-9:]{8,8} Station location: (-?[0-9.]+), (-?[0-9.]+), ([0-9]+)m$"),                 #  1 match station location
        re.compile("^[0-9:]{8,8} Slogan: (.*)$"),       
Download .txt
gitextract_phgrdy1q/

├── .gitignore
├── LICENSE
├── MSYS2/
│   ├── .gitignore
│   └── nrsc5-dui-msys2.py
├── README.md
├── nrsc5-dui.py
├── res/
│   ├── entryForm.glade
│   ├── mainForm-narrow.glade
│   ├── mainForm-wide.glade
│   ├── mainForm.glade
│   └── mapForm.glade
└── setup.py
Download .txt
SYMBOL INDEX (188 symbols across 3 files)

FILE: MSYS2/nrsc5-dui-msys2.py
  class NRSC5_DUI (line 68) | class NRSC5_DUI(object):
    method __init__ (line 69) | def __init__(self):
    method __del__ (line 183) | def __del__(self):
    method initializeData (line 194) | def initializeData(self):
    method set_tuning_actions (line 358) | def set_tuning_actions(self, widget, name, has_win, set_curs):
    method on_enter_set_cursor (line 369) | def on_enter_set_cursor(self, widget, event):
    method on_cbCovers_clicked (line 373) | def on_cbCovers_clicked(self, btn):
    method restart_program (line 380) | def restart_program(self):
    method confirm_dialog (line 384) | def confirm_dialog(self, title, message):
    method on_cbxAspect_changed (line 392) | def on_cbxAspect_changed(self, btn):
    method on_cbxSDRRadio_changed (line 404) | def on_cbxSDRRadio_changed(self, btn):
    method img_to_pixbuf (line 424) | def img_to_pixbuf(self,img):
    method did_resize (line 429) | def did_resize(self):
    method on_cover_resize (line 438) | def on_cover_resize(self, container):
    method id3_did_change (line 460) | def id3_did_change(self):
    method fix_artist (line 467) | def fix_artist(self):
    method check_value (line 475) | def check_value(self,arg,group,default):
    method check_terms (line 481) | def check_terms(self,inStr,terms):
    method check_musicbrainz_cover (line 489) | def check_musicbrainz_cover(self,inID):
    method save_musicbrainz_cover (line 507) | def save_musicbrainz_cover(self,inID,saveStr):
    method get_cover_image_online (line 524) | def get_cover_image_online(self):
    method showArtwork (line 649) | def showArtwork(self, art):
    method displayLogo (line 656) | def displayLogo(self):
    method service_data_type_name (line 669) | def service_data_type_name(self, type):
    method program_type_name (line 674) | def program_type_name(self, type):
    method handle_window_resize (line 679) | def handle_window_resize(self):
    method on_window_resized (line 685) | def on_window_resized(self,window):
    method on_btnPlay_clicked (line 688) | def on_btnPlay_clicked(self, btn):
    method update_bookmark_buttons (line 789) | def update_bookmark_buttons(self):
    method get_bookmark_names (line 806) | def get_bookmark_names(self):
    method on_btnStop_clicked (line 814) | def on_btnStop_clicked(self, btn):
    method on_btnBookmark_clicked (line 864) | def on_btnBookmark_clicked(self, btn):
    method on_btnDelete_clicked (line 884) | def on_btnDelete_clicked(self, btn):
    method on_btnAbout_activate (line 912) | def on_btnAbout_activate(self, btn):
    method on_stream_changed (line 969) | def on_stream_changed(self):
    method restart_nrsc5_with_stream (line 988) | def restart_nrsc5_with_stream(self, stream_num):
    method set_program_btns (line 1012) | def set_program_btns(self):
    method on_program_select (line 1023) | def on_program_select(self, _label, evt):
    method on_cbAutoGain_toggled (line 1030) | def on_cbAutoGain_toggled(self, btn):
    method on_listviewBookmarks_row_activated (line 1034) | def on_listviewBookmarks_row_activated(self, treeview, path, view_colu...
    method _apply_bookmark_and_play (line 1068) | def _apply_bookmark_and_play(self, freq, stream):
    method on_stream_changed_silent (line 1078) | def on_stream_changed_silent(self):
    method on_lvBookmarks_selection_changed (line 1091) | def on_lvBookmarks_selection_changed(self, tree_selection):
    method on_bookmarkNameEdited (line 1096) | def on_bookmarkNameEdited(self, cell, path, text, data=None):
    method on_notebookMain_switch_page (line 1107) | def on_notebookMain_switch_page(self, notebook, page, page_num):
    method on_radMap_toggled (line 1116) | def on_radMap_toggled(self, btn):
    method on_btnMap_clicked (line 1141) | def on_btnMap_clicked(self, btn):
    method mapViewerCallback (line 1147) | def mapViewerCallback(self):
    method on_alignmentCover_clicked (line 1151) | def on_alignmentCover_clicked(self, widget, event):
    method slPopupCallback (line 1164) | def slPopupCallback(self):
    method play (line 1185) | def play(self):
    method set_synchronization (line 1263) | def set_synchronization(self, state):
    method set_button_name (line 1268) | def set_button_name(self, btnWidget, lblWidget, stream):
    method set_label_name (line 1276) | def set_label_name(self, lblWidget, inString, doSens):
    method getImageLot (line 1282) | def getImageLot(self,imgStr):
    method checkStatus (line 1287) | def checkStatus(self):
    method processHERETrafficMap (line 1400) | def processHERETrafficMap(self, fileName, timeStr):
    method processTrafficMap (line 1423) | def processTrafficMap(self, fileName):
    method finishTrafficMap (line 1440) | def finishTrafficMap(self, fileName, ts, t, x, y):
    method processHEREWeatherOverlay (line 1496) | def processHEREWeatherOverlay(self, fileName, timeStr):
    method processWeatherOverlay (line 1517) | def processWeatherOverlay(self, fileName):
    method finishWeatherOverlay (line 1539) | def finishWeatherOverlay(self, fileName, ts, t, id):
    method proccessWeatherInfo (line 1627) | def proccessWeatherInfo(self, fileName):
    method proccessHEREWeatherInfo (line 1660) | def proccessHEREWeatherInfo(self, fileName, lat1, lon1, lat2, lon2):
    method proccessWeatherMaps (line 1687) | def proccessWeatherMaps(self):
    method getMapArea (line 1720) | def getMapArea(self, lat1, lon1, lat2, lon2):
    method makeBaseMap (line 1735) | def makeBaseMap(self, id, pos):
    method checkTiles (line 1752) | def checkTiles(self, t):
    method mkTimestamp (line 1760) | def mkTimestamp(self, t, size, pos):
    method checkPorts (line 1772) | def checkPorts(self, port, type):
    method parseFeedback (line 1780) | def parseFeedback(self, line):
    method getControls (line 1978) | def getControls(self):
    method initStreamInfo (line 2115) | def initStreamInfo(self):
    method loadSettings (line 2232) | def loadSettings(self):
    method shutdown (line 2346) | def shutdown(self, *args):
    method addWeatherMap (line 2423) | def addWeatherMap(self, mapFile):
    method debugLog (line 2432) | def debugLog(self, message, force=False):
  class NRSC5_SLPopup (line 2437) | class NRSC5_SLPopup(object):
    method __init__ (line 2438) | def __init__(self, parent, callback, data):
    method on_cleanup (line 2457) | def on_cleanup(self, btn):
    method on_entryWindow_delete (line 2462) | def on_entryWindow_delete(self, *args):
  class NRSC5_Map (line 2465) | class NRSC5_Map(object):
    method __init__ (line 2466) | def __init__(self, parent, callback, data):
    method on_radMap_toggled (line 2509) | def on_radMap_toggled(self, btn):
    method on_chkAnimate_toggled (line 2538) | def on_chkAnimate_toggled(self, btn):
    method on_chkScale_toggled (line 2555) | def on_chkScale_toggled(self, btn):
    method on_spnSpeed_value_changed (line 2564) | def on_spnSpeed_value_changed(self, spn):
    method on_mapWindow_delete (line 2567) | def on_mapWindow_delete(self, *args):
    method animate (line 2584) | def animate(self):
    method showImage (line 2629) | def showImage(self, fileName, scale):
    method setMap (line 2654) | def setMap(self, map):
    method updated (line 2661) | def updated(self, imageType):
  function dtToTs (line 2668) | def dtToTs(dt):
  function tsToDt (line 2672) | def tsToDt(ts):
  function imgToPixbuf (line 2676) | def imgToPixbuf(img):

FILE: nrsc5-dui.py
  class NRSC5_DUI (line 67) | class NRSC5_DUI(object):
    method __init__ (line 68) | def __init__(self):
    method __del__ (line 167) | def __del__(self):
    method initializeData (line 178) | def initializeData(self):
    method set_tuning_actions (line 341) | def set_tuning_actions(self, widget, name, has_win, set_curs):
    method on_enter_set_cursor (line 352) | def on_enter_set_cursor(self, widget, event):
    method on_cbCovers_clicked (line 356) | def on_cbCovers_clicked(self, btn):
    method restart_program (line 363) | def restart_program(self):
    method confirm_dialog (line 367) | def confirm_dialog(self, title, message):
    method on_cbxAspect_changed (line 375) | def on_cbxAspect_changed(self, btn):
    method on_cbxSDRRadio_changed (line 387) | def on_cbxSDRRadio_changed(self, btn):
    method img_to_pixbuf (line 407) | def img_to_pixbuf(self,img):
    method did_resize (line 412) | def did_resize(self):
    method on_cover_resize (line 421) | def on_cover_resize(self, container):
    method id3_did_change (line 443) | def id3_did_change(self):
    method fix_artist (line 450) | def fix_artist(self):
    method check_value (line 458) | def check_value(self,arg,group,default):
    method check_terms (line 464) | def check_terms(self,inStr,terms):
    method check_musicbrainz_cover (line 472) | def check_musicbrainz_cover(self,inID):
    method save_musicbrainz_cover (line 490) | def save_musicbrainz_cover(self,inID,saveStr):
    method get_cover_image_online (line 507) | def get_cover_image_online(self):
    method showArtwork (line 632) | def showArtwork(self, art):
    method displayLogo (line 641) | def displayLogo(self):
    method service_data_type_name (line 654) | def service_data_type_name(self, type):
    method program_type_name (line 659) | def program_type_name(self, type):
    method handle_window_resize (line 664) | def handle_window_resize(self):
    method on_window_resized (line 670) | def on_window_resized(self,window):
    method on_btnPlay_clicked (line 673) | def on_btnPlay_clicked(self, btn):
    method update_bookmark_buttons (line 774) | def update_bookmark_buttons(self):
    method get_bookmark_names (line 791) | def get_bookmark_names(self):
    method on_btnStop_clicked (line 799) | def on_btnStop_clicked(self, btn):
    method on_btnBookmark_clicked (line 849) | def on_btnBookmark_clicked(self, btn):
    method on_btnDelete_clicked (line 869) | def on_btnDelete_clicked(self, btn):
    method on_btnAbout_activate (line 897) | def on_btnAbout_activate(self, btn):
    method on_stream_changed (line 954) | def on_stream_changed(self):
    method set_program_btns (line 970) | def set_program_btns(self):
    method on_program_select (line 981) | def on_program_select(self, _label, evt):
    method on_cbAutoGain_toggled (line 988) | def on_cbAutoGain_toggled(self, btn):
    method on_listviewBookmarks_row_activated (line 992) | def on_listviewBookmarks_row_activated(self, treeview, path, view_colu...
    method on_lvBookmarks_selection_changed (line 1010) | def on_lvBookmarks_selection_changed(self, tree_selection):
    method on_bookmarkNameEdited (line 1015) | def on_bookmarkNameEdited(self, cell, path, text, data=None):
    method on_notebookMain_switch_page (line 1026) | def on_notebookMain_switch_page(self, notebook, page, page_num):
    method on_radMap_toggled (line 1035) | def on_radMap_toggled(self, btn):
    method on_btnMap_clicked (line 1060) | def on_btnMap_clicked(self, btn):
    method mapViewerCallback (line 1066) | def mapViewerCallback(self):
    method on_alignmentCover_clicked (line 1070) | def on_alignmentCover_clicked(self, widget, event):
    method slPopupCallback (line 1083) | def slPopupCallback(self):
    method play (line 1104) | def play(self):
    method set_synchronization (line 1203) | def set_synchronization(self, state):
    method set_button_name (line 1208) | def set_button_name(self, btnWidget, lblWidget, stream):
    method set_label_name (line 1216) | def set_label_name(self, lblWidget, inString, doSens):
    method getImageLot (line 1222) | def getImageLot(self,imgStr):
    method checkStatus (line 1227) | def checkStatus(self):
    method processHERETrafficMap (line 1375) | def processHERETrafficMap(self, fileName, timeStr):
    method processTrafficMap (line 1398) | def processTrafficMap(self, fileName):
    method finishTrafficMap (line 1415) | def finishTrafficMap(self, fileName, ts, t, x, y):
    method processHEREWeatherOverlay (line 1471) | def processHEREWeatherOverlay(self, fileName, timeStr):
    method processWeatherOverlay (line 1492) | def processWeatherOverlay(self, fileName):
    method finishWeatherOverlay (line 1514) | def finishWeatherOverlay(self, fileName, ts, t, id):
    method proccessWeatherInfo (line 1602) | def proccessWeatherInfo(self, fileName):
    method proccessHEREWeatherInfo (line 1635) | def proccessHEREWeatherInfo(self, fileName, lat1, lon1, lat2, lon2):
    method proccessWeatherMaps (line 1662) | def proccessWeatherMaps(self):
    method getMapArea (line 1695) | def getMapArea(self, lat1, lon1, lat2, lon2):
    method makeBaseMap (line 1710) | def makeBaseMap(self, id, pos):
    method checkTiles (line 1727) | def checkTiles(self, t):
    method mkTimestamp (line 1735) | def mkTimestamp(self, t, size, pos):
    method checkPorts (line 1747) | def checkPorts(self, port, type):
    method parseFeedback (line 1755) | def parseFeedback(self, line):
    method getControls (line 1944) | def getControls(self):
    method initStreamInfo (line 2081) | def initStreamInfo(self):
    method loadSettings (line 2198) | def loadSettings(self):
    method shutdown (line 2312) | def shutdown(self, *args):
    method addWeatherMap (line 2389) | def addWeatherMap(self, mapFile):
    method debugLog (line 2398) | def debugLog(self, message, force=False):
  class NRSC5_SLPopup (line 2403) | class NRSC5_SLPopup(object):
    method __init__ (line 2404) | def __init__(self, parent, callback, data):
    method on_cleanup (line 2423) | def on_cleanup(self, btn):
    method on_entryWindow_delete (line 2428) | def on_entryWindow_delete(self, *args):
  class NRSC5_Map (line 2431) | class NRSC5_Map(object):
    method __init__ (line 2432) | def __init__(self, parent, callback, data):
    method on_radMap_toggled (line 2475) | def on_radMap_toggled(self, btn):
    method on_chkAnimate_toggled (line 2504) | def on_chkAnimate_toggled(self, btn):
    method on_chkScale_toggled (line 2521) | def on_chkScale_toggled(self, btn):
    method on_spnSpeed_value_changed (line 2530) | def on_spnSpeed_value_changed(self, spn):
    method on_mapWindow_delete (line 2533) | def on_mapWindow_delete(self, *args):
    method animate (line 2550) | def animate(self):
    method showImage (line 2595) | def showImage(self, fileName, scale):
    method setMap (line 2620) | def setMap(self, map):
    method updated (line 2627) | def updated(self, imageType):
  function dtToTs (line 2634) | def dtToTs(dt):
  function tsToDt (line 2638) | def tsToDt(ts):
  function imgToPixbuf (line 2642) | def imgToPixbuf(img):

FILE: setup.py
  function get_files_recursive (line 9) | def get_files_recursive(directory):
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (804K chars).
[
  {
    "path": ".gitignore",
    "chars": 133,
    "preview": "**/._*\n**/.DS_Store\n*.txt\n*.log\nHERE*\nhere.zip\naas/**\ncfg/**\ncfg/config.json\ncfg/stationLogos.json\nmap/**\nlinux_binary\nm"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "MSYS2/.gitignore",
    "chars": 1,
    "preview": "\n"
  },
  {
    "path": "MSYS2/nrsc5-dui-msys2.py",
    "chars": 134869,
    "preview": "#!/usr/bin/env python3\n#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n#    NRSC5 DUI - A graphical interface for nrsc5\n#   "
  },
  {
    "path": "README.md",
    "chars": 15649,
    "preview": "NRSC5-DUI is a graphical interface for [nrsc5](https://github.com/theori-io/nrsc5). It makes it easy to play your favori"
  },
  {
    "path": "nrsc5-dui.py",
    "chars": 133321,
    "preview": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n#    NRSC5 DUI - A graphical interface for nrsc5\n#    Copyright (C) 2017-201"
  },
  {
    "path": "res/entryForm.glade",
    "chars": 5053,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- Generated with glade 3.38.2 -->\n<interface>\n  <requires lib=\"gtk+\" version=\""
  },
  {
    "path": "res/mainForm-narrow.glade",
    "chars": 140319,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- Generated with glade 3.40.0 -->\n<interface>\n  <requires lib=\"gtk+\" version=\""
  },
  {
    "path": "res/mainForm-wide.glade",
    "chars": 150639,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- Generated with glade 3.40.0 -->\n<interface>\n  <requires lib=\"gtk+\" version=\""
  },
  {
    "path": "res/mainForm.glade",
    "chars": 140319,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- Generated with glade 3.40.0 -->\n<interface>\n  <requires lib=\"gtk+\" version=\""
  },
  {
    "path": "res/mapForm.glade",
    "chars": 13152,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<interface>\n  <requires lib=\"gtk+\" version=\"3.0\"/>\n  <!-- interface-naming-policy"
  },
  {
    "path": "setup.py",
    "chars": 4474,
    "preview": "from distutils.core import setup\r\nimport os, sys, glob, py2exe\r\n\r\n# Find GTK+ installation path\r\n__import__('gtk')\r\nm = "
  }
]

About this extraction

This page contains the full source code of the markjfine/nrsc5-dui GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (755.0 KB), approximately 150.5k tokens, and a symbol index with 188 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!