25 Commits
0.4 ... master

Author SHA1 Message Date
c5d4cbdfd8 bugfix: about dialog ni deloval pri tipični namestitvi 2026-04-22 20:31:31 +02:00
f21adfbc80 Priprava na izdajo: dokumentacija in inkrement verzije 2026-03-27 21:49:06 +01:00
c80bebe1f0 Še malo šminke (št. pesmi) in 9900 za prikaz istega preko tipkovnice. #9 2026-03-27 21:37:34 +01:00
f75a6f04dd Server-side events (SSE) namesto pollinga #14 2026-03-27 21:03:46 +01:00
8c18e3fa6b Dialog O programu #9 2026-03-27 20:46:29 +01:00
ced80f7024 še malo finalnega tuninga #3 2026-03-25 22:43:13 +01:00
3f10341bc9 manjši code cleanup #3 2026-03-25 22:31:53 +01:00
2b0e02e94c še interaktivna kontrola za prelom #3 2026-03-25 22:29:37 +01:00
1dcb80739c prelom strani glede na split_by_stanza nastavitev #3 2026-03-25 22:17:13 +01:00
40ff1f8ec8 višina strani določena glede na font metriko; varnostni faktor 0,85 #3 2026-03-25 22:09:16 +01:00
8d0956378b nov algoritem za prelom vrstic in postavljanje na stran #3 2026-03-25 21:50:41 +01:00
1008b26960 malo čiščenji, mali refactor (self.label -> text_display) 2026-03-23 13:26:51 +01:00
da06ef25a0 ikono mi je narisal grok #13 2026-03-22 18:14:08 +01:00
1e2eacdeb8 Še malo izboljšav za robustnejše zaganjanje startup.sh (požene python projekcijo iz istega direktorija kot je skripta). 2026-03-22 17:37:19 +01:00
dbf4c2da16 malo čiščenja kode in robustnostni popravek (kreiranje prazne sheme) 2026-03-22 16:42:28 +01:00
48536d57ab Privzete nastavitve - uskladitev v kodo programa 2026-03-22 16:17:12 +01:00
e09ebbe165 settings je samo primer (.sample) 2026-03-21 23:23:59 +01:00
e49142ea6f Implementacija obveščanja preko ntfy.sh #12 2026-03-21 23:15:36 +01:00
e57727ba0b licenciranje - GPL v3 #9 2026-03-21 22:27:10 +01:00
15c449b63e Osvežitev readme-ja 2026-03-21 22:11:50 +01:00
21d7baaea6 še malo čiščenja (vzorec teksta za uvoz je prestavljen v mapo z orodji) 2026-03-21 22:04:04 +01:00
33dc8048d6 čiščenje namestitve 2026-03-21 22:01:28 +01:00
190203cbff malo čiščenja kode (projekcije se ne zaganja več od tu) 2026-03-21 21:58:15 +01:00
008f616cea čiščenje: orodja v podmapo, preštevilčenje nekaterih sistemskih operacij; odstranitev orodij iz glavnega programa 2026-03-21 21:53:35 +01:00
9c9fe7b069 update urlja nočem imeti javno objavljenega 2026-03-21 21:48:02 +01:00
17 changed files with 1442 additions and 248 deletions

1
.gitignore vendored
View File

@@ -11,3 +11,4 @@ __pycache__/
# Datoteke dnevnikov (logs) # Datoteke dnevnikov (logs)
*.log *.log
settings.json

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

201
README.md
View File

@@ -1,153 +1,168 @@
# Projekcija besedil (Lyrics Projector) # Projekcija besedil (Lyrics Projector)
A Tkinter-based song projector application with optional Flask web interface for remote control. A Tkinter-based song projector application with a Flask web interface for remote control. Designed for displaying lyrics on a large screen while controlling them from a computer or mobile device.
## Features ## Features
- **Tkinter GUI**: Full-screen song display with customizable fonts, colors, and sizing - **Tkinter GUI**: Full-screen song display with customizable fonts, colors, and sizing.
- **Song Database**: SQLite database with lyrics and metadata - **Smart Text Wrapping**: Automatically splits long lines and divides lyrics into pages based on screen height and stanza breaks.
- **Web Interface** (optional): Control the projector via web browser - **Song Database**: SQLite database with lyrics and metadata.
- Load songs by number or search by title - **Web Interface**: Comprehensive remote control via web browser.
- Navigate between lyrics pages - Load songs by number or search by title.
- Toggle uppercase display - Real-time status synchronization across multiple devices.
- Clear/dim the screen - Navigate between lyrics pages.
- **Keyboard Shortcuts**: Quick navigation and screen control - **Song Editor**: Edit existing songs or add new ones directly from the web interface.
- **Settings**: JSON-based configuration for fonts, colors, and display options - Toggle uppercase display.
- Clear/dim the screen.
- Virtual keypad for mobile-friendly input.
- **Keyboard Shortcuts**: Quick navigation and screen control using physical or numeric keypad.
- **Settings**: JSON-based configuration for fonts, colors, display options, and remote update URLs.
- **System Integration**:
- Prevents screen sleep/saver on Windows and Linux (GNOME).
- Automatic cursor hiding.
- Remote system commands (shutdown, restart).
- Remote database updates via URL.
## Project Structure ## Project Structure
``` ```
projekcija/ Projekcija/
├── projector.py # Main Tkinter application ├── projector.py # Main Tkinter application
├── nastavitve.py # Settings defaults and initialization ├── settings.json # User configuration (generated from sample)
├── add_song.py # Utility to import songs into database ├── settings.json.sample # Template for settings
├── songs.db # SQLite database with lyrics ├── songs.db # SQLite database with lyrics
├── settings.json # User configuration ├── startup.sh # Linux launcher script
├── startup.bat # Windows launcher script
├── tools/ # Utility scripts
│ ├── add_song.py # Import songs into database
│ ├── nastavitve.py # Settings management
│ └── ...
├── web/ # Flask web server package ├── web/ # Flask web server package
│ ├── __init__.py
│ ├── server.py # Flask app and API endpoints │ ├── server.py # Flask app and API endpoints
│ ├── static/ # Web assets │ ├── static/ # Web assets (JS, CSS)
│ ├── styles.css └── templates/ # HTML templates
│ │ └── script.js
│ └── templates/
│ └── index.html
├── tests/ # Test suite ├── tests/ # Test suite
│ ├── test_api.py └── ...
│ ├── test_integration.py
│ └── test_mock.py
└── startup.bat # Windows batch launcher
``` ```
## Installation ## Installation
### Requirements ### Requirements
- Python 3.8+ - Python 3.8+
- Flask (for web interface) - **Tkinter** (usually included with Python, but may require `python3-tk` on some Linux distributions)
- sqlite3 (included with Python) - **Flask** (for web interface)
- `sqlite3` (included with Python)
- `requests` (for remote database updates and notifications)
### Setup ### Setup
1. **Install Dependencies**:
```bash ```bash
# Install Flask pip install flask requests
pip install flask
# Create or import songs into database (optional)
python add_song.py
``` ```
2. **Configure Settings**:
Copy `settings.json.sample` to `settings.json` and adjust values as needed.
3. **Prepare Database**:
Ensure `songs.db` exists. You can use tools in the `tools/` directory to manage songs.
## Usage ## Usage
### Launch the Application ### Launch the Application
```bash **Windows:**
python projector.py
```
Or use the batch file:
```bash ```bash
startup.bat startup.bat
``` ```
### Keyboard Shortcuts **Linux:**
```bash
./startup.sh
```
- **Enter**: Load song by number (when typing in keyboard mode) **Manual:**
```bash
python projector.py
```
### Keyboard Shortcuts (Projector Window)
- **0-9**: Type song number
- **Enter**: Load song by number / Next page
- **+** (plus): Clear/dim the screen - **+** (plus): Clear/dim the screen
- **-** (minus): Previous page - **-** (minus): Previous page
- **\*** (multiply): Toggle uppercase
- **/** (slash): Search songs by title - **/** (slash): Search songs by title
- **Backspace**: Delete last digit of song number
### Special Commands (Input as song number)
- **9999**: Shutdown system (Windows/Linux)
- **9998**: Restart system (Windows/Linux)
- **9997**: Restart application
- **9988**: Exit application
- **9901**: Update songs database from `db_update_url`
- **9900**: Show application information (version, author, license)
### Configuration ### Configuration
Edit `settings.json` to customize: Edit `settings.json` to customize:
- Font name, size, and color - **font_name**: Font family (e.g., "Arial")
- Background color - **font_size**: Base font size
- Display width percentage - **fg_color**: Text color (HEX)
- **web_port**: Set to a port number (e.g., 5000) to enable web interface, or 0 to disable - **bg_color**: Background color (HEX)
- **screen_width_percent**: Width of the text area (e.g., 60)
Example `settings.json`: - **font_bold**: Use bold font (true/false)
```json - **show_song_info**: Show song number and page info at bottom (true/false)
{ - **split_by_stanza**: If true, each stanza starts on a new page (true/false)
"font_name": "Times New Roman", - **web_port**: Port for web interface (0 to disable)
"font_size": 32, - **db_update_url**: URL for remote database synchronization
"fg_color": "#FFFFFF", - **ntfy_topic**: Topic for ntfy.sh notifications
"bg_color": "#000000", - **installation_label**: Custom label for the installation (shown in app info)
"screen_width_percent": 60,
"font_bold": true,
"web_port": 5000
}
```
### Web Interface ### Web Interface
If `web_port` is configured and > 0, the web interface opens automatically: Access the control panel at:
``` ```
http://127.0.0.1:<web_port>/ http://<computer-ip>:<web_port>/
``` ```
Features: Features:
- **Load by Number**: Input song ID and press "Naloži" - **Load by Number**: Input song ID and press "Naloži" (or Enter).
- **Search**: Find songs by keyword - **Search**: Real-time search by title.
- **Navigation**: Next/Previous buttons to flip pages - **Navigation**: Next/Previous buttons.
- **Case Toggle**: "velikE črke" button for uppercase - **Edit Mode**: Click "Uredi besedilo" to modify the current song or add a new one.
- **Clear Screen**: "Zatemniti ekran" button to dim display - **Virtual Keypad**: Toggleable numeric keypad for touch devices.
- **Wake Lock**: Attempts to keep the mobile screen on while the interface is open.
## Testing ## API Endpoints
Run the integration test to verify the web server: - `GET /api/state` Current projector state (text, page info, modes)
- `GET /api/events` SSE endpoint for real-time update notifications
```bash - `GET /api/app_info` Application metadata (version, author, song count)
python -m tests.test_integration - `POST /api/load_song` Load a song by number
```
This starts a mock projector, launches the Flask server, and exercises all API endpoints.
## Architecture
### Database Schema
- `songs` table: `id, title, lyrics`
- Read-only mode (no modifications via web interface)
### API Endpoints
- `GET /` HTML interface
- `GET /api/state` Current projector state (text, page, navigation flags)
- `POST /api/load_song` Load a song
- `POST /api/next_page` Next page - `POST /api/next_page` Next page
- `POST /api/prev_page` Previous page - `POST /api/prev_page` Previous page
- `POST /api/clear_screen` Clear display - `POST /api/clear_screen` Clear display
- `POST /api/toggle_caps` Toggle uppercase - `POST /api/toggle_caps` Toggle uppercase
- `POST /api/search_songs` Find songs by title - `POST /api/toggle_split` Toggle stanza split mode
- `POST /api/search_songs` Search songs by title
- `GET /api/get_song_details` Get lyrics and title for editing
- `POST /api/update_song` Save song changes or create new
### Threading ## Testing
- Web server runs in a daemon thread
- Safe SQLite access with `check_same_thread=False`
## Notes Run the test suite:
```bash
python -m tests.test_integration
```
- The web interface is optional; disable it by setting `web_port: 0` in settings ## Avtorstvo in Licenca (Authorship and License)
- HTML, CSS, and JavaScript are stored in separate files under `web/`
- For production deployment, use a WSGI server (Gunicorn, uWSGI) instead of Flask development server
- Songs database is read-only via web interface; add songs using admin tools or direct SQL
## License **Izvorna zasnova in implementacija:** Uroš Urbanija
**Nadgradnje in vzdrževanje:** Valentin Korenjak
[Add your license here] Ta projekt je licenciran pod pogoji **GNU GPL v3**. Za več informacij si oglejte datoteko [LICENSE](LICENSE).
This project is licensed under the terms of the **GNU GPL v3**. See the [LICENSE](LICENSE) file for details.

10
appinfo.json Normal file
View File

@@ -0,0 +1,10 @@
{
"name": "Projekcija",
"description": "Aplikacija za projekcijo besedil pesmi na zaslon.",
"version": "0.7.1",
"authors": [
"Uroš Urbanija (izvorna zasnova)",
"Valentin Korenjak (nadgradnje in vzdrževanje)"
],
"license": "GPLv3"
}

15
db_schema.py Normal file
View File

@@ -0,0 +1,15 @@
import sqlite3
def create_tables(conn):
"""
Ustvari potrebne tabele v bazi, če še ne obstajajo.
"""
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS songs (
id INTEGER PRIMARY KEY,
title TEXT,
lyrics TEXT
)
''')
conn.commit()

View File

@@ -1,8 +1,27 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#
# Projekcija - Lyrics Projector
#
# Izvorna zasnova in implementacija: Uroš Urbanija
# Nadgradnje in vzdrževanje: Valentin Korenjak
#
# 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/>.
import sqlite3 import sqlite3
import tkinter as tk import tkinter as tk
from tkinter import font
import json import json
import os import os
import math import math
@@ -10,16 +29,17 @@ import subprocess
import sys import sys
import ctypes import ctypes
import tkinter.messagebox as messagebox import tkinter.messagebox as messagebox
from web.server import start_server_thread from web.server import start_server_thread, notify_clients
import urllib.request import urllib.request
import tempfile import tempfile
from db_schema import create_tables
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
APPINFO_PATH = os.path.join(BASE_DIR, 'appinfo.json')
DB_PATH = 'songs.db' DB_PATH = 'songs.db'
SETTINGS_PATH = 'settings.json' SETTINGS_PATH = 'settings.json'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class SongProjector: class SongProjector:
def __init__(self, root): def __init__(self, root):
self.root = root self.root = root
@@ -28,6 +48,7 @@ class SongProjector:
# Odpri read-only; ne bo ustvaril prazne baze, če datoteka manjka # Odpri read-only; ne bo ustvaril prazne baze, če datoteka manjka
# check_same_thread=False omogoča uporabo v večih nitih # check_same_thread=False omogoča uporabo v večih nitih
self.conn = sqlite3.connect(DB_PATH, check_same_thread=False) self.conn = sqlite3.connect(DB_PATH, check_same_thread=False)
create_tables(self.conn)
self.cursor = self.conn.cursor() self.cursor = self.conn.cursor()
except sqlite3.OperationalError as e: except sqlite3.OperationalError as e:
# Jasno sporočilo in varen izhod # Jasno sporočilo in varen izhod
@@ -45,21 +66,23 @@ class SongProjector:
# Nastavitve # Nastavitve
# -------------------------------------------------- # --------------------------------------------------
DEFAULT_SETTINGS = { DEFAULT_SETTINGS = {
"font_name": "Times New Roman", "font_name": "Noto Sans",
"bg_color": "#000000", "bg_color": "#000000",
"fg_color": "#FFFFFF", "fg_color": "#FFFFFF",
"font_size": 32, "font_size": 32,
"screen_width_percent": 60, "screen_width_percent": 60,
"font_bold": True, "font_bold": False,
"show_song_info": True, "show_song_info": True,
"split_by_stanza": False, # TODO: mogoče nekoč (prelom po kitici namesto po višini) "split_by_stanza": False,
"db_update_url": "" "web_port": 5000,
"db_update_url": "",
"ntfy_topic": "",
"installation_label": "Projekcija"
} }
if not os.path.exists(SETTINGS_PATH): if not os.path.exists(SETTINGS_PATH):
self.settings = DEFAULT_SETTINGS.copy() self.settings = DEFAULT_SETTINGS.copy()
with open(SETTINGS_PATH, "w", encoding="utf-8") as f: self.save_settings()
json.dump(self.settings, f, indent=4, ensure_ascii=False)
else: else:
try: try:
with open(SETTINGS_PATH, "r", encoding="utf-8") as f: with open(SETTINGS_PATH, "r", encoding="utf-8") as f:
@@ -68,7 +91,19 @@ class SongProjector:
# Povratek na varne privzete # Povratek na varne privzete
self.settings = DEFAULT_SETTINGS.copy() self.settings = DEFAULT_SETTINGS.copy()
self.line_height = int(int(self.settings["font_size"]) * 1.5) # --------------------------------------------------
# Pisava (Font)
# --------------------------------------------------
font_weight = "bold" if self.settings.get("font_bold", False) else "normal"
self.custom_font = font.Font(
family=self.settings["font_name"],
size=int(self.settings["font_size"]),
weight=font_weight
)
# Izračunamo dejansko višino vrstice glede na pisavo
# metrics("linespace") vrne priporočen razmik med vrsticami v pikslih
self.line_height = self.custom_font.metrics("linespace")
# -------------------------------------------------- # --------------------------------------------------
# Okno # Okno
@@ -104,18 +139,16 @@ class SongProjector:
self.right_frame = tk.Frame(root, bg="black", width=black_side_width, height=screen_height) self.right_frame = tk.Frame(root, bg="black", width=black_side_width, height=screen_height)
self.right_frame.pack(side="right", fill="y") self.right_frame.pack(side="right", fill="y")
font_weight = "bold" if self.settings.get("font_bold", False) else "normal" self.display_text = tk.Label(
self.label = tk.Label(
self.color_frame, self.color_frame,
text="", text="",
bg=self.settings["bg_color"], bg=self.settings["bg_color"],
fg=self.settings["fg_color"], fg=self.settings["fg_color"],
font=(self.settings["font_name"], int(self.settings["font_size"]), font_weight), font=self.custom_font,
wraplength=color_width, wraplength=color_width,
justify="center" justify="center"
) )
self.label.pack(expand=True) self.display_text.pack(expand=True)
right_edge_x = int((screen_width - color_width) / 2 + color_width) right_edge_x = int((screen_width - color_width) / 2 + color_width)
@@ -205,37 +238,28 @@ class SongProjector:
def split_long_line(self, line): def split_long_line(self, line):
""" """
Vrne seznam pod-vrstic, ki skupaj tvorijo `line`, Vrne seznam pod-vrstic, ki skupaj tvorijo `line`,
pri čemer so (približno) enako dolge glede na število znakov. pri čemer so dolge največ `self.color_width` pikslov.
""" """
avg_char_width = int(self.settings["font_size"]) * 0.57
wraplength_px = self.color_width
# Koliko znakov približno gre v eno vrstico
approx_chars_per_line = max(1, int(wraplength_px / avg_char_width))
if len(line) <= approx_chars_per_line:
return [line]
# Potrebno število podvrstic
n_sub = math.ceil(len(line) / approx_chars_per_line)
words = line.split() words = line.split()
total_chars = sum(len(w) for w in words) + len(words) - 1 # vključno s presledki if not words:
target_len = total_chars / n_sub return [""]
sub_lines = [] sub_lines = []
current_words = [] current_words = []
current_len = 0
for word in words: for word in words:
added_len = len(word) + (1 if current_words else 0) # presledek pred besedo, če ni prva test_line = " ".join(current_words + [word])
if current_len + added_len > target_len and len(sub_lines) < n_sub - 1: # Izmerimo širino v pikslih
# Začni novo vrstico if self.custom_font.measure(test_line) <= self.color_width:
current_words.append(word)
else:
if current_words:
sub_lines.append(" ".join(current_words)) sub_lines.append(" ".join(current_words))
current_words = [word] current_words = [word]
current_len = len(word)
else: else:
current_words.append(word) # Beseda je sama po sebi predolga (zelo redko)
current_len += added_len sub_lines.append(word)
current_words = []
if current_words: if current_words:
sub_lines.append(" ".join(current_words)) sub_lines.append(" ".join(current_words))
@@ -251,8 +275,7 @@ class SongProjector:
elif event.keysym == "BackSpace": elif event.keysym == "BackSpace":
self.song_number = self.song_number[:-1] self.song_number = self.song_number[:-1]
elif event.char == "*": elif event.char == "*":
self.all_caps_mode = not self.all_caps_mode self.toggle_split_mode()
self.show_page()
def enter_pressed(self, event=None): def enter_pressed(self, event=None):
if self.song_number: if self.song_number:
@@ -260,6 +283,26 @@ class SongProjector:
elif not self.waiting_for_song: elif not self.waiting_for_song:
self.next_page() self.next_page()
def save_settings(self):
"""Shrani trenutne nastavitve v settings.json."""
try:
with open(SETTINGS_PATH, "w", encoding="utf-8") as f:
json.dump(self.settings, f, indent=4, ensure_ascii=False)
except Exception as e:
print(f"Napaka pri shranjevanju nastavitev: {e}")
def toggle_split_mode(self):
"""Preklopi med načinom preloma po kiticah in prostim prelomom."""
self.settings["split_by_stanza"] = not self.settings.get("split_by_stanza", False)
# Shranimo v settings.json, da se ohrani ob ponovnem zagonu
# TODO: preveri z Urošem, kaj bi bilo bolje (shraniti ali ne)
# self.save_settings()
# Ponovno naložimo trenutno pesem, da se osveži prelom
if self.song_number_last:
self.song_number = self.song_number_last
self.load_song()
# ------------------------------------------------------ # ------------------------------------------------------
# Nalaganje in obdelava besedila # Nalaganje in obdelava besedila
# ------------------------------------------------------ # ------------------------------------------------------
@@ -275,8 +318,8 @@ class SongProjector:
# Ponastavitev izgleda barvnega območja # Ponastavitev izgleda barvnega območja
self.color_frame.config(bg=self.settings["bg_color"], width=self.color_width, height=self.screen_height) self.color_frame.config(bg=self.settings["bg_color"], width=self.color_width, height=self.screen_height)
self.color_frame.place(relx=0.5, rely=0.5, anchor="center") self.color_frame.place(relx=0.5, rely=0.5, anchor="center")
self.label.config(bg=self.settings["bg_color"], fg=self.settings["fg_color"]) self.display_text.config(bg=self.settings["bg_color"], fg=self.settings["fg_color"])
self.label.pack(expand=True) self.display_text.pack(expand=True)
# Posebni ukazi # Posebni ukazi
if self.song_number == "9999": if self.song_number == "9999":
@@ -294,21 +337,15 @@ class SongProjector:
elif self.song_number == "9997": elif self.song_number == "9997":
self.restart_program() self.restart_program()
return return
elif self.song_number == "7777": elif self.song_number == "9988":
subprocess.Popen([sys.executable, os.path.join(BASE_DIR, "nastavitve.py")]) # fixme: novi proces ne dobi stdin-a; predelati na tkinter aplikacijo?
self.exit_program()
return
elif self.song_number == "8888":
self.exit_program()
return
elif self.song_number == "6666":
subprocess.Popen([sys.executable, os.path.join(BASE_DIR, "add_song.py")]) # fixme: novi proces ne dobi stdin-a; predelati na tkinter aplikacijo?
self.exit_program() self.exit_program()
return return
elif self.song_number == "9901": elif self.song_number == "9901":
self.update_songs_database() self.update_songs_database()
return return
elif self.song_number == "9900":
self.show_app_info_tkinter()
return
try: try:
song_id = int(self.song_number) song_id = int(self.song_number)
self.cursor.execute("SELECT lyrics FROM songs WHERE id=?", (song_id,)) self.cursor.execute("SELECT lyrics FROM songs WHERE id=?", (song_id,))
@@ -316,75 +353,97 @@ class SongProjector:
if result: if result:
lyrics = result[0] lyrics = result[0]
max_height = self.screen_height - (self.line_height * 1.5) # Pustimo 10% varnostnega roba zgoraj in spodaj + prostor za song_info
avg_char_width = int(self.settings["font_size"]) * 0.57 max_height = self.screen_height * 0.90
wraplength = self.color_width
# ------------------------------------------- # 1. Razdelimo na kitice (stanzas)
# 1. Razbijanje besedila na (pod-)vrstice # Kitice so ločene z dvojno prazno vrstico (\n\n\n ali \n\s*\n\s*\n)
# ------------------------------------------- import re
raw_lines = lyrics.strip().splitlines() # Razdelimo po vsaj dveh praznih vrsticah (trije ali več \n)
processed_lines = [] stanzas_raw = re.split(r'\n\s*\n\s*\n+', lyrics.strip())
for raw in raw_lines:
if raw.strip() == "": processed_stanzas = []
processed_lines.append("") # ohranimo prazno vrstico for stanza in stanzas_raw:
# Znotraj kitice ohranimo enojne prazne vrstice kot razmike
lines = stanza.splitlines()
stanza_lines = []
for line in lines:
if line.strip():
stanza_lines.extend(self.split_long_line(line))
else: else:
processed_lines.extend(self.split_long_line(raw)) stanza_lines.append("") # Enojna prazna vrstica znotraj kitice
if stanza_lines:
processed_stanzas.append(stanza_lines)
# ------------------------------------------- # 2. Razdeljevanje kitic na strani
# 2. Razdeljevanje vrstic na strani
# -------------------------------------------
pages = [] pages = []
current_page_lines = [] current_page_lines = []
current_height = 0 current_height = 0
blank_line_count = 0 split_by_stanza = self.settings.get("split_by_stanza", False)
for line in processed_lines: for stanza in processed_stanzas:
is_blank = (line.strip() == "") stanza_height = len(stanza) * self.line_height
if is_blank:
blank_line_count += 1
else:
blank_line_count = 0
approx_line_length = len(line) # Če je vklopljen split_by_stanza, vsaka kitica dobi svojo stran
approx_line_count = 1 if is_blank else math.ceil((approx_line_length * avg_char_width) / wraplength) if split_by_stanza:
needed_height = self.line_height * approx_line_count
# Prazna vrstica več kot 1krat pomeni nova kitica ⇒ nova stran
if blank_line_count >= 2:
if current_page_lines: if current_page_lines:
pages.append("\n".join(current_page_lines).strip()) pages.append("\n".join(current_page_lines))
current_page_lines = [] current_page_lines = []
current_height = 0 current_height = 0
blank_line_count = 0
# Če je kitica predolga za eno stran, jo še vedno moramo razdeliti
if stanza_height > max_height:
temp_stanza_lines = []
temp_height = 0
for line in stanza:
if temp_height + self.line_height > max_height:
pages.append("\n".join(temp_stanza_lines))
temp_stanza_lines = [line]
temp_height = self.line_height
else:
temp_stanza_lines.append(line)
temp_height += self.line_height
if temp_stanza_lines:
pages.append("\n".join(temp_stanza_lines))
else:
pages.append("\n".join(stanza))
continue continue
# Če čez spodnji rob strani … # Standardna logika (več kitic na stran, če grejo)
if current_height + needed_height > max_height + self.line_height // 2: if stanza_height > max_height:
# poskusimo prelomiti na prazni vrstici znotraj strani if current_page_lines:
found_split = False pages.append("\n".join(current_page_lines))
for i in reversed(range(len(current_page_lines))):
if current_page_lines[i].strip() == "":
pages.append("\n".join(current_page_lines[:i]).strip())
current_page_lines = current_page_lines[i + 1:]
current_height = sum(
self.line_height * (
1 if l.strip() == "" else math.ceil(len(l) * avg_char_width / wraplength)
)
for l in current_page_lines
)
found_split = True
break
if not found_split:
pages.append("\n".join(current_page_lines).strip())
current_page_lines = [] current_page_lines = []
current_height = 0 current_height = 0
current_page_lines.append(line) temp_stanza_lines = []
current_height += needed_height temp_height = 0
for line in stanza:
if temp_height + self.line_height > max_height:
pages.append("\n".join(temp_stanza_lines))
temp_stanza_lines = [line]
temp_height = self.line_height
else:
temp_stanza_lines.append(line)
temp_height += self.line_height
if temp_stanza_lines:
current_page_lines = temp_stanza_lines
current_height = temp_height
elif current_height + stanza_height + (self.line_height if current_page_lines else 0) > max_height:
pages.append("\n".join(current_page_lines))
current_page_lines = stanza
current_height = stanza_height
else:
if current_page_lines:
current_page_lines.append("") # Razmik med kiticami
current_height += self.line_height
current_page_lines.extend(stanza)
current_height += stanza_height
if current_page_lines: if current_page_lines:
pages.append("\n".join(current_page_lines).strip()) pages.append("\n".join(current_page_lines))
self.pages = pages self.pages = pages
self.current_page_index = 0 self.current_page_index = 0
@@ -392,7 +451,7 @@ class SongProjector:
self.song_number_last = self.song_number self.song_number_last = self.song_number
self.show_page() self.show_page()
else: else:
self.label.config(text="") self.display_text.config(text="")
self.pages = [] self.pages = []
self.current_page_index = 0 self.current_page_index = 0
self.waiting_for_song = True self.waiting_for_song = True
@@ -400,7 +459,7 @@ class SongProjector:
self.song_info_label.config(text=self.song_number_last) self.song_info_label.config(text=self.song_number_last)
self.song_info_label.lift() self.song_info_label.lift()
except Exception as e: except Exception as e:
self.label.config(text=f"Napaka: {e}") self.display_text.config(text=f"Napaka: {e}")
finally: finally:
self.song_number = "" self.song_number = ""
@@ -412,7 +471,7 @@ class SongProjector:
text = self.pages[self.current_page_index] text = self.pages[self.current_page_index]
if self.all_caps_mode: if self.all_caps_mode:
text = text.upper() text = text.upper()
self.label.config(text=text) self.display_text.config(text=text)
if self.settings.get("show_song_info", False): if self.settings.get("show_song_info", False):
current_page = self.current_page_index + 1 current_page = self.current_page_index + 1
total_pages = len(self.pages) total_pages = len(self.pages)
@@ -420,6 +479,7 @@ class SongProjector:
self.song_info_label.lift() self.song_info_label.lift()
else: else:
self.song_info_label.config(text="") self.song_info_label.config(text="")
notify_clients()
# ------------------------------------------------------ # ------------------------------------------------------
# Navigacija po straneh # Navigacija po straneh
@@ -443,11 +503,12 @@ class SongProjector:
self.current_page_index = 0 self.current_page_index = 0
self.waiting_for_song = True self.waiting_for_song = True
self.label.config(text="") self.display_text.config(text="")
self.label.pack_forget() self.display_text.pack_forget()
self.color_frame.config(bg="black", width=self.color_width, height=self.screen_height) self.color_frame.config(bg="black", width=self.color_width, height=self.screen_height)
self.color_frame.place(relx=0.5, rely=0.5, anchor="center") self.color_frame.place(relx=0.5, rely=0.5, anchor="center")
self.song_info_label.config(text="") self.song_info_label.config(text="")
notify_clients()
# ------------------------------------------------------ # ------------------------------------------------------
# Iskanje po naslovu # Iskanje po naslovu
@@ -489,10 +550,10 @@ class SongProjector:
query = self.search_entry.get().strip() query = self.search_entry.get().strip()
self.search_label.destroy() self.search_label.destroy()
self.search_entry.destroy() self.search_entry.destroy()
self.label.pack(expand=True) self.display_text.pack(expand=True)
if not query: if not query:
self.label.config(text="(Prazno iskanje)") self.display_text.config(text="(Prazno iskanje)")
return return
try: try:
@@ -502,14 +563,14 @@ class SongProjector:
) )
matched = self.cursor.fetchall() matched = self.cursor.fetchall()
except Exception as e: except Exception as e:
self.label.config(text=f"Napaka pri iskanju: {e}") self.display_text.config(text=f"Napaka pri iskanju: {e}")
return return
if matched: if matched:
found = "\n".join(f"{sid}: {title}" for sid, title in matched) found = "\n".join(f"{sid}: {title}" for sid, title in matched)
self.label.config(text=found) self.display_text.config(text=found)
else: else:
self.label.config(text="Ni zadetkov.") self.display_text.config(text="Ni zadetkov.")
# ------------------------------------------------------ # ------------------------------------------------------
# Posodobitev baze pesmi # Posodobitev baze pesmi
@@ -519,13 +580,13 @@ class SongProjector:
if not url: if not url:
msg = "URL za posodobitev ni nastavljen v settings.json." msg = "URL za posodobitev ni nastavljen v settings.json."
print(msg) print(msg)
self.label.config(text=msg) self.display_text.config(text=msg)
self.song_number = "" self.song_number = ""
return return
msg = f"Prenašam posodobitev iz: {url}..." msg = f"Prenašam posodobitev iz: {url}..."
print(msg) print(msg)
self.label.config(text=msg) self.display_text.config(text=msg)
self.root.update() self.root.update()
temp_db_path = None temp_db_path = None
@@ -570,12 +631,12 @@ class SongProjector:
final_msg = f"Posodobitev uspešna! Posodobljenih/dodanih {upsert_count} pesmi." final_msg = f"Posodobitev uspešna! Posodobljenih/dodanih {upsert_count} pesmi."
print(final_msg) print(final_msg)
self.label.config(text=final_msg) self.display_text.config(text=final_msg)
except Exception as e: except Exception as e:
error_msg = f"Napaka pri posodobitvi: {e}" error_msg = f"Napaka pri posodobitvi: {e}"
print(error_msg) print(error_msg)
self.label.config(text=error_msg) self.display_text.config(text=error_msg)
finally: finally:
if temp_db_path and os.path.exists(temp_db_path): if temp_db_path and os.path.exists(temp_db_path):
try: try:
@@ -624,6 +685,84 @@ class SongProjector:
subprocess.Popen(args) subprocess.Popen(args)
self.root.after(200, self.exit_program) self.root.after(200, self.exit_program)
# ------------------------------------------------------
# Pošiljanje ntfy obvestil
# ------------------------------------------------------
def send_ntfy_notification(self, song_id, title, lyrics):
"""
Pošlje obvestilo o spremembi besedila preko ntfy.sh.
"""
topic = self.settings.get("ntfy_topic", "").strip()
if not topic:
return
label = self.settings.get("installation_label", "Projekcija")
# ntfy.sh headers must be ASCII. We'll use base64 encoding for the title to support non-ASCII characters.
import base64
encoded_label = "=?UTF-8?B?" + base64.b64encode(label.encode('utf-8')).decode('utf-8') + "?="
message = f"{song_id}\n{title}\n{lyrics}"
try:
url = f"https://ntfy.sh/{topic}"
req = urllib.request.Request(
url,
data=message.encode('utf-8'),
method='POST',
headers={ "Title": encoded_label,
"Priority": "high",
"Tags": "loudspeaker" }
)
# Uporabimo kratek timeout, da ne blokiramo aplikacije
with urllib.request.urlopen(req, timeout=5) as response:
pass
except Exception as e:
print(f"Napaka pri pošiljanju ntfy obvestila: {e}")
# ------------------------------------------------------
# Prikaži informacije o aplikaciji v Tkinter oknu
# ------------------------------------------------------
def show_app_info_tkinter(self):
"""Prikaže informacije o aplikaciji v glavnem oknu (ukaz 9900)."""
try:
with open(APPINFO_PATH, 'r', encoding='utf-8') as f:
info = json.load(f)
self.cursor.execute("SELECT COUNT(*) FROM songs")
count = self.cursor.fetchone()[0]
authors = ", ".join(info.get("authors", []))
display_text = (
f"{info.get('name', 'Projekcija')}\n"
f"Verzija: {info.get('version', 'neznana')}\n\n"
f"{info.get('description', '')}\n\n"
f"Avtorji: {authors}\n\n"
f"Število pesmi v bazi: {count}"
)
# Ponastavitev izgleda barvnega območja za prikaz informacij
self.color_frame.config(bg=self.settings["bg_color"], width=self.color_width, height=self.screen_height)
self.color_frame.place(relx=0.5, rely=0.5, anchor="center")
self.display_text.config(bg=self.settings["bg_color"], fg=self.settings["fg_color"], text=display_text)
self.display_text.pack(expand=True)
# self.song_number_last = "9900"
self.song_info_label.config(text="Informacije o programu")
self.song_info_label.lift()
self.pages = []
self.current_page_index = 0
self.waiting_for_song = True
notify_clients()
except Exception as e:
self.display_text.config(text=f"Napaka pri branju informacij: {e}")
finally:
self.song_number = ""
# ---------------------------------------------------------- # ----------------------------------------------------------
# Zagon aplikacije # Zagon aplikacije
# ---------------------------------------------------------- # ----------------------------------------------------------

View File

@@ -8,5 +8,7 @@
"show_song_info": true, "show_song_info": true,
"split_by_stanza": false, "split_by_stanza": false,
"web_port": 5000, "web_port": 5000,
"db_update_url": "https://k5c.korenjak.si/s/dKeE6eXMmBPteQF/download" "db_update_url": "",
"ntfy_topic": "",
"installation_label": "Projekcija"
} }

View File

@@ -42,14 +42,14 @@ IF EXIST "D:\Projekcija" (
echo Zagon projector.py ... echo Zagon projector.py ...
pushd "%TARGET%" pushd "%TARGET%"
python projector.py py "%~dp0projector.py"
popd popd
) ELSE ( ) ELSE (
cls cls
echo USB ključek ni najden. Zagon lokalne verzije... echo USB ključek ni najden. Zagon lokalne verzije...
echo Zagon projector.py ... echo Zagon projector.py ...
pushd "%TARGET%" pushd "%TARGET%"
py "projekcija\projector.py" py "%~dp0projector.py"
popd popd
) )

View File

@@ -37,8 +37,12 @@ if [ -n "$SOURCE" ]; then
fi fi
echo "Zagon projector.py..." echo "Zagon projector.py..."
# Pridobi direktorij, v katerem se nahaja ta skripta
echo "Bash source: ${BASH_SOURCE[0]}"
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [ -d "$TARGET" ]; then if [ -d "$TARGET" ]; then
cd "$TARGET" && projekcija/projector.py cd "$TARGET" && python3 "$SCRIPT_DIR/projector.py"
else else
echo "Napaka: Mapa $TARGET ne obstaja." echo "Napaka: Mapa $TARGET ne obstaja."
fi fi

View File

@@ -4,6 +4,12 @@
import sqlite3 import sqlite3
import json import json
import os import os
import urllib.request
import sys
# Dodajanje poti do korenskega imenika, da lahko uvozimo db_schema
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from db_schema import create_tables
DB_PATH = 'songs.db' DB_PATH = 'songs.db'
SETTINGS_PATH = 'settings.json' SETTINGS_PATH = 'settings.json'
@@ -14,26 +20,43 @@ EXPORT_PATH = 'pesmi_export.txt'
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
if not os.path.exists(SETTINGS_PATH): if not os.path.exists(SETTINGS_PATH):
print("Nastavitve manjkajo! Zaženi 'nastavitve.bat' najprej.") print("Nastavitve manjkajo! Zaženi program za prjekcijo, da jih pripravi.")
exit() exit()
with open(SETTINGS_PATH, "r", encoding="utf-8") as f: with open(SETTINGS_PATH, "r", encoding="utf-8") as f:
settings = json.load(f) settings = json.load(f)
conn = sqlite3.connect(DB_PATH) conn = sqlite3.connect(DB_PATH)
create_tables(conn)
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS songs (
id INTEGER PRIMARY KEY,
title TEXT,
lyrics TEXT
)''')
conn.commit()
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# POMOŽNE FUNKCIJE # POMOŽNE FUNKCIJE
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def send_ntfy_notification(song_id, title, lyrics):
"""
Pošlje obvestilo o spremembi besedila preko ntfy.sh.
"""
topic = settings.get("ntfy_topic", "").strip()
if not topic:
return
label = settings.get("installation_label", "Projekcija")
message = f"{song_id}\n{title}\n{lyrics}"
try:
url = f"https://ntfy.sh/{topic}"
req = urllib.request.Request(
url,
data=message.encode('utf-8'),
method='POST'
)
with urllib.request.urlopen(req, timeout=5) as response:
pass
except Exception as e:
print(f"Napaka pri pošiljanju ntfy obvestila: {e}")
def get_next_free_id(start: int = 792) -> int: def get_next_free_id(start: int = 792) -> int:
"""Vrne prvo prosto številko pesmi, ki je ≥ start (privzeto 792).""" """Vrne prvo prosto številko pesmi, ki je ≥ start (privzeto 792)."""
next_id = start next_id = start
@@ -56,7 +79,6 @@ def prikazi_meni():
print("5. Izvozi bazo v TXT") print("5. Izvozi bazo v TXT")
print("6. Uvozi bazo iz TXT") print("6. Uvozi bazo iz TXT")
print("7. Izpiši kazalo") print("7. Izpiši kazalo")
print("8. Zaženi projekcijo")
print("9. Zapri program") print("9. Zapri program")
def uredi_vnos(lines): def uredi_vnos(lines):
@@ -126,6 +148,7 @@ def dodaj_pesem():
cursor.execute("INSERT OR REPLACE INTO songs (id, title, lyrics) VALUES (?,?,?)", cursor.execute("INSERT OR REPLACE INTO songs (id, title, lyrics) VALUES (?,?,?)",
(song_id, title, full_lyrics)) (song_id, title, full_lyrics))
conn.commit() conn.commit()
send_ntfy_notification(song_id, title, full_lyrics)
print("Pesem uspešno shranjena!") print("Pesem uspešno shranjena!")
def uredi_pesem(): def uredi_pesem():
@@ -163,6 +186,7 @@ def uredi_pesem():
cursor.execute("UPDATE songs SET title = ?, lyrics = ? WHERE id = ?", cursor.execute("UPDATE songs SET title = ?, lyrics = ? WHERE id = ?",
(new_title, new_lyrics, song_id)) (new_title, new_lyrics, song_id))
conn.commit() conn.commit()
send_ntfy_notification(song_id, new_title, new_lyrics)
print("Pesem uspešno posodobljena!") print("Pesem uspešno posodobljena!")
def prestavi_pesem(): def prestavi_pesem():
@@ -201,6 +225,7 @@ def prestavi_pesem():
(new_id, vir[0], vir[1])) (new_id, vir[0], vir[1]))
cursor.execute("DELETE FROM songs WHERE id = ?", (old_id,)) cursor.execute("DELETE FROM songs WHERE id = ?", (old_id,))
conn.commit() conn.commit()
send_ntfy_notification(new_id, vir[0], vir[1])
print("Pesem uspešno prestavljena!") print("Pesem uspešno prestavljena!")
def izbrisi_pesem(): def izbrisi_pesem():
@@ -321,6 +346,7 @@ def uvozi_bazo():
# -- shranjevanje pesmi --------------------------------------------- # -- shranjevanje pesmi ---------------------------------------------
cursor.execute("INSERT OR REPLACE INTO songs (id, title, lyrics) VALUES (?,?,?)", cursor.execute("INSERT OR REPLACE INTO songs (id, title, lyrics) VALUES (?,?,?)",
(song_id, title, lyrics)) (song_id, title, lyrics))
send_ntfy_notification(song_id, title, lyrics)
conn.commit() conn.commit()
print("\nUvoz pesmi uspešen!") print("\nUvoz pesmi uspešen!")
@@ -381,12 +407,6 @@ def izpisi_kazalo():
print("Kazalo izpisano v 'kazalo.txt'.") print("Kazalo izpisano v 'kazalo.txt'.")
def zazeni_projekcijo():
print("Zaganjam projekcijo …")
conn.close()
python_exe = os.sys.executable
os.execl(python_exe, python_exe, "projector.py")
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# G L A V N I Z A G O N # G L A V N I Z A G O N
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -404,7 +424,6 @@ def main():
elif izbira == "5": izvozi_bazo() elif izbira == "5": izvozi_bazo()
elif izbira == "6": uvozi_bazo() elif izbira == "6": uvozi_bazo()
elif izbira == "7": izpisi_kazalo() elif izbira == "7": izpisi_kazalo()
elif izbira == "8": zazeni_projekcijo()
elif izbira == "9": elif izbira == "9":
print("Program se zapira …") print("Program se zapira …")
break break

View File

@@ -8,15 +8,18 @@ import subprocess
import sys import sys
DEFAULT_SETTINGS = { DEFAULT_SETTINGS = {
"font_name": "Times New Roman", "font_name": "Noto Sans",
"bg_color": "#000000", "bg_color": "#000000",
"fg_color": "#FFFFFF", "fg_color": "#FFFFFF",
"font_size": 32, "font_size": 32,
"screen_width_percent": 60, "screen_width_percent": 60,
"font_bold": True, "font_bold": False,
"show_song_info": True, "show_song_info": True,
"split_by_stanza": False, "split_by_stanza": False,
"web_port": 5000 "web_port": 5000,
"db_update_url": "",
"ntfy_topic": "",
"installation_label": "Projekcija"
} }
SETTINGS_FILE = "settings.json" SETTINGS_FILE = "settings.json"

View File

@@ -1,6 +1,7 @@
=== ===
1 1
Prva Pesem Prva Pesem: skopiraj tole datoteko v pesmi_export.txt in jo uvozi v novo bazo
Bela črka sredi teme, Bela črka sredi teme,
zdaj prebija mrak dvorane, zdaj prebija mrak dvorane,
da rešila bi dileme, da rešila bi dileme,

View File

@@ -1,5 +1,23 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#
# Projekcija - Lyrics Projector (Web Server)
#
# Izvorna zasnova in implementacija: Uroš Urbanija
# Nadgradnje in vzdrževanje: Valentin Korenjak
#
# 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/>.
"""Flask web server for the song projector application. """Flask web server for the song projector application.
@@ -9,8 +27,11 @@ than being generated inside Python code.
import threading import threading
import os import os
import json
import queue
import time
from flask import Flask, render_template, request, jsonify from flask import Flask, render_template, request, jsonify, Response
# create Flask app with proper folders relative to this file # create Flask app with proper folders relative to this file
app = Flask(__name__, static_folder="static", template_folder="templates") app = Flask(__name__, static_folder="static", template_folder="templates")
@@ -18,6 +39,17 @@ app = Flask(__name__, static_folder="static", template_folder="templates")
# Globalna referenca na SongProjector aplikaciju # Globalna referenca na SongProjector aplikaciju
_projector_app = None _projector_app = None
# List of queues for SSE clients
_sse_clients = []
_sse_lock = threading.Lock()
def notify_clients():
"""Notify all connected SSE clients to refresh content"""
with _sse_lock:
for q in _sse_clients:
q.put("refresh content")
def set_projector_app(projector_app): def set_projector_app(projector_app):
"""Postavi referenco na SongProjector aplikacijo""" """Postavi referenco na SongProjector aplikacijo"""
@@ -44,6 +76,7 @@ def get_state():
'current_text': 'Napaka: Aplikacija ni inicijalizirana', 'current_text': 'Napaka: Aplikacija ni inicijalizirana',
'page_info': '', 'page_info': '',
'caps_mode': False, 'caps_mode': False,
'split_by_stanza': False,
'can_prev': False, 'can_prev': False,
'can_next': False 'can_next': False
}) })
@@ -71,11 +104,32 @@ def get_state():
'current_text': current_text, 'current_text': current_text,
'page_info': page_info, 'page_info': page_info,
'caps_mode': _projector_app.all_caps_mode, 'caps_mode': _projector_app.all_caps_mode,
'split_by_stanza': _projector_app.settings.get("split_by_stanza", False),
'can_prev': can_prev, 'can_prev': can_prev,
'can_next': can_next 'can_next': can_next
}) })
@app.route('/api/events')
def sse_events():
"""SSE endpoint for real-time updates"""
def event_stream():
q = queue.Queue()
with _sse_lock:
_sse_clients.append(q)
try:
# Send initial refresh command on connection
yield "data: refresh content\n\n"
while True:
msg = q.get()
yield f"data: {msg}\n\n"
finally:
with _sse_lock:
_sse_clients.remove(q)
return Response(event_stream(), mimetype="text/event-stream")
@app.route('/api/load_song', methods=['POST']) @app.route('/api/load_song', methods=['POST'])
def load_song(): def load_song():
"""Naloži pesem po številki""" """Naloži pesem po številki"""
@@ -90,6 +144,7 @@ def load_song():
_projector_app.load_song() _projector_app.load_song()
if hasattr(_projector_app, 'show_page'): if hasattr(_projector_app, 'show_page'):
_projector_app.show_page() _projector_app.show_page()
notify_clients()
return jsonify({'status': 'ok'}) return jsonify({'status': 'ok'})
@@ -99,6 +154,7 @@ def next_page():
"""Naslednja stran""" """Naslednja stran"""
if _projector_app is not None: if _projector_app is not None:
_projector_app.next_page() _projector_app.next_page()
notify_clients()
return jsonify({'status': 'ok'}) return jsonify({'status': 'ok'})
@@ -108,6 +164,7 @@ def prev_page():
"""Prejšnja stran""" """Prejšnja stran"""
if _projector_app is not None: if _projector_app is not None:
_projector_app.prev_page() _projector_app.prev_page()
notify_clients()
return jsonify({'status': 'ok'}) return jsonify({'status': 'ok'})
@@ -117,6 +174,7 @@ def clear_screen():
"""Zatemniti ekran""" """Zatemniti ekran"""
if _projector_app is not None: if _projector_app is not None:
_projector_app.clear_screen() _projector_app.clear_screen()
notify_clients()
return jsonify({'status': 'ok'}) return jsonify({'status': 'ok'})
@@ -127,10 +185,42 @@ def toggle_caps():
if _projector_app is not None: if _projector_app is not None:
_projector_app.all_caps_mode = not _projector_app.all_caps_mode _projector_app.all_caps_mode = not _projector_app.all_caps_mode
_projector_app.show_page() _projector_app.show_page()
notify_clients()
return jsonify({'status': 'ok'}) return jsonify({'status': 'ok'})
@app.route('/api/toggle_split', methods=['POST'])
def toggle_split():
"""Preklop med načinom preloma po kiticah in prostim prelomom"""
if _projector_app is not None:
_projector_app.toggle_split_mode()
notify_clients()
return jsonify({'status': 'ok'})
@app.route('/api/app_info', methods=['GET'])
def get_app_info():
"""Vrne informacije o aplikaciji iz appinfo.json"""
try:
# appinfo.json je v korenskem imeniku projekta (nad web/)
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
appinfo_path = os.path.join(base_dir, 'appinfo.json')
with open(appinfo_path, 'r', encoding='utf-8') as f:
info = json.load(f)
# Dodaj število pesmi v bazi
if _projector_app is not None:
_projector_app.cursor.execute("SELECT COUNT(*) FROM songs")
count = _projector_app.cursor.fetchone()[0]
info['song_count'] = count
return jsonify(info)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/search_songs', methods=['POST']) @app.route('/api/search_songs', methods=['POST'])
def search_songs(): def search_songs():
"""Iskanje besedil po naslovu""" """Iskanje besedil po naslovu"""
@@ -223,16 +313,25 @@ def update_song():
_projector_app.song_number = str(new_id) _projector_app.song_number = str(new_id)
_projector_app.load_song() _projector_app.load_song()
# Pošlji ntfy obvestilo
if hasattr(_projector_app, 'send_ntfy_notification'):
_projector_app.send_ntfy_notification(new_id, title, lyrics)
return jsonify({'status': 'ok', 'new_id': new_id}) return jsonify({'status': 'ok', 'new_id': new_id})
# Obstoječa pesem # Obstoječa pesem
_projector_app.cursor.execute("UPDATE songs SET title=?, lyrics=? WHERE id=?", (title, lyrics, song_id)) _projector_app.cursor.execute("UPDATE songs SET title=?, lyrics=? WHERE id=?", (title, lyrics, song_id))
_projector_app.conn.commit() _projector_app.conn.commit()
# Pošlji ntfy obvestilo
if hasattr(_projector_app, 'send_ntfy_notification'):
_projector_app.send_ntfy_notification(song_id, title, lyrics)
# Osvežimo trenutno pesem, če je to ta, ki smo jo pravkar uredili # Osvežimo trenutno pesem, če je to ta, ki smo jo pravkar uredili
if str(_projector_app.song_number_last) == str(song_id): if str(_projector_app.song_number_last) == str(song_id):
_projector_app.song_number = str(song_id) _projector_app.song_number = str(song_id)
_projector_app.load_song() _projector_app.load_song()
notify_clients()
return jsonify({'status': 'ok'}) return jsonify({'status': 'ok'})
except Exception as e: except Exception as e:

30
web/static/favicon.svg Normal file
View File

@@ -0,0 +1,30 @@
<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<!-- ozadje (temna stena) -->
<rect width="512" height="512" fill="#2c2f33"/>
<!-- okvir projekcijskega platna (črn mat okvir) -->
<rect x="96" y="80" width="320" height="352" rx="12" fill="#1a1c20" stroke="#111" stroke-width="8"/>
<!-- notranji okvir (rahlo svetlejši rob) -->
<rect x="104" y="88" width="304" height="336" rx="8" fill="#22252a"/>
<!-- projekcijsko platno rahlo svetlejše sivo z gradientom za "zasvetlitev" -->
<defs>
<linearGradient id="platnoGrad" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#e8ecef"/>
<stop offset="40%" stop-color="#d8e0e5"/>
<stop offset="70%" stop-color="#c8d4db"/>
<stop offset="100%" stop-color="#b0c0ca"/>
</linearGradient>
</defs>
<rect x="112" y="96" width="288" height="320" rx="6" fill="url(#platnoGrad)"/>
<!-- rahla senca / val na platnu za občutek zavese -->
<path d="M112 96 Q 256 160 400 96 L400 416 L112 416 Z" fill="rgba(0,0,0,0.12)" opacity="0.6"/>
<!-- subtilni highlight na vrhu (kot da prihaja svetloba od projektorja) -->
<rect x="112" y="96" width="288" height="60" fill="white" opacity="0.12"/>
<!-- tanka črna črta na dnu (kot da je platno rahlo napeto) -->
<line x1="112" y1="412" x2="400" y2="412" stroke="#111" stroke-width="4"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -7,8 +7,12 @@ const displayArea = document.getElementById('display-area');
const prevBtn = document.getElementById('prev-btn'); const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn'); const nextBtn = document.getElementById('next-btn');
const darkBtn = document.getElementById('dark-btn'); const darkBtn = document.getElementById('dark-btn');
const splitBtn = document.getElementById('split-btn');
const pageInfo = document.getElementById('page-info'); const pageInfo = document.getElementById('page-info');
const clearBtn = document.getElementById('clear-btn'); const clearBtn = document.getElementById('clear-btn');
const aboutBtn = document.getElementById('about-btn');
const aboutModal = document.getElementById('about-modal');
const aboutCloseBtn = document.getElementById('about-close-btn');
const keypadButtons = document.querySelectorAll('.btn-key'); const keypadButtons = document.querySelectorAll('.btn-key');
const keypadWrapper = document.getElementById('keypad-wrapper'); const keypadWrapper = document.getElementById('keypad-wrapper');
const toggleKeypadBtn = document.getElementById('toggle-keypad-btn'); const toggleKeypadBtn = document.getElementById('toggle-keypad-btn');
@@ -37,6 +41,7 @@ const infoMessage = document.getElementById('info-message');
const infoOkBtn = document.getElementById('info-ok-btn'); const infoOkBtn = document.getElementById('info-ok-btn');
let capsMode = false; let capsMode = false;
let splitByStanza = false;
let wakeLock = null; let wakeLock = null;
let lastStateSignature = ""; let lastStateSignature = "";
let lastPageInfo = ""; let lastPageInfo = "";
@@ -81,6 +86,7 @@ async function updateState(force = false) {
current_text: data.current_text || '', current_text: data.current_text || '',
page_info: data.page_info || '', page_info: data.page_info || '',
caps_mode: data.caps_mode || false, caps_mode: data.caps_mode || false,
split_by_stanza: data.split_by_stanza || false,
can_prev: !!data.can_prev can_prev: !!data.can_prev
}); });
@@ -102,6 +108,13 @@ async function updateState(force = false) {
darkBtn.classList.remove('active'); darkBtn.classList.remove('active');
} }
splitByStanza = data.split_by_stanza || false;
if (splitByStanza) {
splitBtn.classList.add('active');
} else {
splitBtn.classList.remove('active');
}
prevBtn.disabled = !data.can_prev; prevBtn.disabled = !data.can_prev;
} catch (error) { } catch (error) {
console.error('Napaka pri posodabljanju stanja:', error); console.error('Napaka pri posodabljanju stanja:', error);
@@ -237,6 +250,16 @@ async function toggleCaps() {
} }
} }
// Preklop načina preloma po kiticah
async function toggleSplit() {
try {
await fetch('/api/toggle_split', { method: 'POST' });
await updateState(true);
} catch (error) {
console.error('Napaka pri preklopu načina preloma:', error);
}
}
// Odpri urejevalnik // Odpri urejevalnik
async function openEditor(songId = null) { async function openEditor(songId = null) {
try { try {
@@ -325,6 +348,41 @@ async function saveSongEdit() {
} }
} }
// Odpri About dialog
async function openAbout() {
try {
const response = await fetch('/api/app_info');
const data = await response.json();
if (data.error) {
alert('Napaka pri pridobivanju informacij o programu.');
return;
}
document.getElementById('about-name').textContent = data.name;
document.getElementById('about-version').textContent = 'Verzija ' + data.version;
document.getElementById('about-description').textContent = data.description;
// Dodaj število pesmi
if (data.song_count !== undefined) {
document.getElementById('about-description').innerHTML += `<br><br>Število pesmi v bazi: <strong>${data.song_count}</strong>`;
}
const authorsList = document.getElementById('about-authors');
authorsList.innerHTML = '';
data.authors.forEach(author => {
const li = document.createElement('li');
li.textContent = author;
authorsList.appendChild(li);
});
aboutModal.classList.add('show');
menuDropdown.classList.remove('show');
} catch (error) {
console.error('Napaka pri pridobivanju informacij o programu:', error);
}
}
// skrij/pokaži tipkovnico // skrij/pokaži tipkovnico
function toggleKeypad() { function toggleKeypad() {
if (!keypadWrapper || !toggleKeypadBtn) return; if (!keypadWrapper || !toggleKeypadBtn) return;
@@ -383,6 +441,14 @@ darkBtn.addEventListener('click', () => {
toggleCaps(); toggleCaps();
}); });
// Prelom po kiticah
if (splitBtn) {
splitBtn.addEventListener('click', () => {
vibrate();
toggleSplit();
});
}
// Skrij/Pokaži tipkovnico // Skrij/Pokaži tipkovnico
if (toggleKeypadBtn) { if (toggleKeypadBtn) {
toggleKeypadBtn.addEventListener('click', (e) => { toggleKeypadBtn.addEventListener('click', (e) => {
@@ -391,6 +457,20 @@ if (toggleKeypadBtn) {
}); });
} }
// O programu
if (aboutBtn) {
aboutBtn.addEventListener('click', () => {
vibrate();
openAbout();
});
}
if (aboutCloseBtn) {
aboutCloseBtn.addEventListener('click', () => {
aboutModal.classList.remove('show');
});
}
// Uredi besedilo // Uredi besedilo
if (editSongBtn) { if (editSongBtn) {
editSongBtn.addEventListener('click', () => { editSongBtn.addEventListener('click', () => {
@@ -461,6 +541,10 @@ document.addEventListener('click', (e) => {
if (menuDropdown && !menuDropdown.contains(e.target) && e.target !== menuToggle) { if (menuDropdown && !menuDropdown.contains(e.target) && e.target !== menuToggle) {
menuDropdown.classList.remove('show'); menuDropdown.classList.remove('show');
} }
// Zapri About modal ob kliku izven vsebine
if (e.target === aboutModal) {
aboutModal.classList.remove('show');
}
}); });
// Iskanje dogodki // Iskanje dogodki
@@ -551,10 +635,10 @@ document.addEventListener('keydown', (e) => {
return; return;
} }
// AAaa // preklopi prelom
if (e.key === '*' || e.code === 'NumpadMultiply') { if (e.key === '*' || e.code === 'NumpadMultiply') {
e.preventDefault(); e.preventDefault();
toggleCaps(); toggleSplit();
return; return;
} }
@@ -569,9 +653,24 @@ document.addEventListener('keydown', (e) => {
updateState(true); updateState(true);
requestWakeLock(); requestWakeLock();
// osveževanje za sinhronizacijo med več napravami // SSE osveževanje za sinhronizacijo med več napravami
setInterval(() => { function setupSSE() {
const evtSource = new EventSource("/api/events");
evtSource.onmessage = function(event) {
console.log("SSE dogodek:", event.data);
if (event.data === "refresh content") {
updateState(false); updateState(false);
}, 1000); }
};
evtSource.onerror = function(err) {
console.error("SSE napaka, ponovni poskus čez 5s...", err);
evtSource.close();
setTimeout(setupSSE, 5000);
};
}
setupSSE();
console.log('JavaScript inicializacija zaključena'); console.log('JavaScript inicializacija zaključena');

View File

@@ -28,7 +28,7 @@
} }
body { body {
font-family: 'Times New Roman', serif; font-family: 'Noto Sans', sans-serif;
background-color: #0a0a0a; background-color: #0a0a0a;
color: #ffffff; color: #ffffff;
min-height: var(--container-min-h); min-height: var(--container-min-h);
@@ -429,6 +429,12 @@ body {
height: 100%; height: 100%;
background-color: rgba(0,0,0,0.8); background-color: rgba(0,0,0,0.8);
overflow-y: auto; overflow-y: auto;
align-items: center;
justify-content: center;
}
.modal.show {
display: flex !important;
} }
.modal-content { .modal-content {
@@ -474,6 +480,59 @@ textarea.form-control {
margin-top: 20px; margin-top: 20px;
} }
/* About Modal Styles */
.about-content {
text-align: center;
padding: 30px;
}
.about-header {
margin-bottom: 25px;
}
.about-logo {
width: 96px;
height: 96px;
margin-bottom: 15px;
}
.about-version {
color: var(--text-muted);
font-size: 0.9rem;
margin-top: 5px;
}
.about-description {
font-size: 1.1rem;
margin-bottom: 25px;
line-height: 1.5;
}
.about-authors-section {
text-align: left;
background: rgba(255, 255, 255, 0.05);
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
}
.about-authors-section h3 {
margin-top: 0;
font-size: 1rem;
color: #1f8a46;
}
.about-authors-list {
list-style: none;
padding: 0;
margin: 10px 0 0 0;
}
.about-authors-list li {
margin-bottom: 5px;
font-size: 0.95rem;
}
.btn-primary { .btn-primary {
background-color: #1f8a46; background-color: #1f8a46;
color: white; color: white;

View File

@@ -4,6 +4,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<title>Projekcija besedil</title> <title>Projekcija besedil</title>
<link rel="icon" type="image/svg+xml" href="{{ url_for('static', filename='favicon.svg') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head> </head>
@@ -25,7 +26,9 @@
<div id="menu-dropdown" class="menu-dropdown"> <div id="menu-dropdown" class="menu-dropdown">
<button id="toggle-keypad-btn" class="menu-item" type="button">Skrij tipkovnico</button> <button id="toggle-keypad-btn" class="menu-item" type="button">Skrij tipkovnico</button>
<button id="dark-btn" class="menu-item" type="button">Velike/male črke (AAaa)</button> <button id="dark-btn" class="menu-item" type="button">Velike/male črke (AAaa)</button>
<button id="split-btn" class="menu-item" type="button">Prelom po kiticah</button>
<button id="edit-song-btn" class="menu-item" type="button">Uredi besedilo</button> <button id="edit-song-btn" class="menu-item" type="button">Uredi besedilo</button>
<button id="about-btn" class="menu-item" type="button">O programu</button>
</div> </div>
</div> </div>
</div> </div>
@@ -78,6 +81,27 @@
</div> </div>
</div> </div>
<!-- About Modal -->
<div id="about-modal" class="modal">
<div class="modal-content about-content">
<div class="about-header">
<img src="{{ url_for('static', filename='favicon.svg') }}" alt="Logo" class="about-logo">
<h1 id="about-name">Projekcija</h1>
<p id="about-version" class="about-version"></p>
</div>
<div class="about-body">
<p id="about-description" class="about-description"></p>
<div class="about-authors-section">
<h3>Avtorji:</h3>
<ul id="about-authors" class="about-authors-list"></ul>
</div>
</div>
<div class="modal-footer">
<button id="about-close-btn" class="btn-primary">Zapri</button>
</div>
</div>
</div>
<div class="content"> <div class="content">
<div id="display-area" class="lyrics-display"> <div id="display-area" class="lyrics-display">
<span class="status-message">Pripravljeno. Vpiši številko pesmi ali drugega besedila.</span> <span class="status-message">Pripravljeno. Vpiši številko pesmi ali drugega besedila.</span>