Compare commits
12 Commits
projekcija
...
projekcija
| Author | SHA1 | Date | |
|---|---|---|---|
| c5d4cbdfd8 | |||
| f21adfbc80 | |||
| c80bebe1f0 | |||
| f75a6f04dd | |||
| 8c18e3fa6b | |||
| ced80f7024 | |||
| 3f10341bc9 | |||
| 2b0e02e94c | |||
| 1dcb80739c | |||
| 40ff1f8ec8 | |||
| 8d0956378b | |||
| 1008b26960 |
23
README.md
23
README.md
@@ -49,14 +49,16 @@ Projekcija/
|
||||
|
||||
### Requirements
|
||||
- Python 3.8+
|
||||
- Flask (for web interface)
|
||||
- **Tkinter** (usually included with Python, but may require `python3-tk` on some Linux distributions)
|
||||
- **Flask** (for web interface)
|
||||
- `sqlite3` (included with Python)
|
||||
- `requests` (for remote database updates and notifications)
|
||||
|
||||
### Setup
|
||||
|
||||
1. **Install Dependencies**:
|
||||
```bash
|
||||
pip install flask
|
||||
pip install flask requests
|
||||
```
|
||||
|
||||
2. **Configure Settings**:
|
||||
@@ -96,11 +98,12 @@ python projector.py
|
||||
|
||||
### Special Commands (Input as song number)
|
||||
|
||||
- **9999**: Shutdown system
|
||||
- **9998**: Restart system
|
||||
- **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
|
||||
|
||||
@@ -112,8 +115,11 @@ Edit `settings.json` to customize:
|
||||
- **screen_width_percent**: Width of the text area (e.g., 60)
|
||||
- **font_bold**: Use bold font (true/false)
|
||||
- **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)
|
||||
- **web_port**: Port for web interface (0 to disable)
|
||||
- **db_update_url**: URL for remote database synchronization
|
||||
- **ntfy_topic**: Topic for ntfy.sh notifications
|
||||
- **installation_label**: Custom label for the installation (shown in app info)
|
||||
|
||||
### Web Interface
|
||||
|
||||
@@ -132,14 +138,17 @@ Features:
|
||||
|
||||
## API Endpoints
|
||||
|
||||
- `GET /api/state` – Current projector state
|
||||
- `GET /api/state` – Current projector state (text, page info, modes)
|
||||
- `GET /api/events` – SSE endpoint for real-time update notifications
|
||||
- `GET /api/app_info` – Application metadata (version, author, song count)
|
||||
- `POST /api/load_song` – Load a song by number
|
||||
- `POST /api/next_page` – Next page
|
||||
- `POST /api/prev_page` – Previous page
|
||||
- `POST /api/clear_screen` – Clear display
|
||||
- `POST /api/toggle_caps` – Toggle uppercase
|
||||
- `POST /api/search_songs` – Search songs
|
||||
- `GET /api/get_song_details` – Get lyrics for editing
|
||||
- `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
|
||||
|
||||
## Testing
|
||||
|
||||
10
appinfo.json
Normal file
10
appinfo.json
Normal 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"
|
||||
}
|
||||
304
projector.py
304
projector.py
@@ -21,6 +21,7 @@
|
||||
|
||||
import sqlite3
|
||||
import tkinter as tk
|
||||
from tkinter import font
|
||||
import json
|
||||
import os
|
||||
import math
|
||||
@@ -28,17 +29,17 @@ import subprocess
|
||||
import sys
|
||||
import ctypes
|
||||
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 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'
|
||||
SETTINGS_PATH = 'settings.json'
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
class SongProjector:
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
@@ -81,8 +82,7 @@ class SongProjector:
|
||||
|
||||
if not os.path.exists(SETTINGS_PATH):
|
||||
self.settings = DEFAULT_SETTINGS.copy()
|
||||
with open(SETTINGS_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(self.settings, f, indent=4, ensure_ascii=False)
|
||||
self.save_settings()
|
||||
else:
|
||||
try:
|
||||
with open(SETTINGS_PATH, "r", encoding="utf-8") as f:
|
||||
@@ -91,7 +91,19 @@ class SongProjector:
|
||||
# Povratek na varne privzete
|
||||
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
|
||||
@@ -127,18 +139,16 @@ class SongProjector:
|
||||
self.right_frame = tk.Frame(root, bg="black", width=black_side_width, height=screen_height)
|
||||
self.right_frame.pack(side="right", fill="y")
|
||||
|
||||
font_weight = "bold" if self.settings.get("font_bold", False) else "normal"
|
||||
|
||||
self.label = tk.Label(
|
||||
self.display_text = tk.Label(
|
||||
self.color_frame,
|
||||
text="",
|
||||
bg=self.settings["bg_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,
|
||||
justify="center"
|
||||
)
|
||||
self.label.pack(expand=True)
|
||||
self.display_text.pack(expand=True)
|
||||
|
||||
right_edge_x = int((screen_width - color_width) / 2 + color_width)
|
||||
|
||||
@@ -228,37 +238,28 @@ class SongProjector:
|
||||
def split_long_line(self, 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 pod‑vrstic
|
||||
n_sub = math.ceil(len(line) / approx_chars_per_line)
|
||||
|
||||
words = line.split()
|
||||
total_chars = sum(len(w) for w in words) + len(words) - 1 # vključno s presledki
|
||||
target_len = total_chars / n_sub
|
||||
if not words:
|
||||
return [""]
|
||||
|
||||
sub_lines = []
|
||||
current_words = []
|
||||
current_len = 0
|
||||
|
||||
for word in words:
|
||||
added_len = len(word) + (1 if current_words else 0) # presledek pred besedo, če ni prva
|
||||
if current_len + added_len > target_len and len(sub_lines) < n_sub - 1:
|
||||
# Začni novo vrstico
|
||||
sub_lines.append(" ".join(current_words))
|
||||
current_words = [word]
|
||||
current_len = len(word)
|
||||
else:
|
||||
test_line = " ".join(current_words + [word])
|
||||
# Izmerimo širino v pikslih
|
||||
if self.custom_font.measure(test_line) <= self.color_width:
|
||||
current_words.append(word)
|
||||
current_len += added_len
|
||||
else:
|
||||
if current_words:
|
||||
sub_lines.append(" ".join(current_words))
|
||||
current_words = [word]
|
||||
else:
|
||||
# Beseda je sama po sebi predolga (zelo redko)
|
||||
sub_lines.append(word)
|
||||
current_words = []
|
||||
|
||||
if current_words:
|
||||
sub_lines.append(" ".join(current_words))
|
||||
@@ -274,8 +275,7 @@ class SongProjector:
|
||||
elif event.keysym == "BackSpace":
|
||||
self.song_number = self.song_number[:-1]
|
||||
elif event.char == "*":
|
||||
self.all_caps_mode = not self.all_caps_mode
|
||||
self.show_page()
|
||||
self.toggle_split_mode()
|
||||
|
||||
def enter_pressed(self, event=None):
|
||||
if self.song_number:
|
||||
@@ -283,6 +283,26 @@ class SongProjector:
|
||||
elif not self.waiting_for_song:
|
||||
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
|
||||
# ------------------------------------------------------
|
||||
@@ -298,8 +318,8 @@ class SongProjector:
|
||||
# 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.place(relx=0.5, rely=0.5, anchor="center")
|
||||
self.label.config(bg=self.settings["bg_color"], fg=self.settings["fg_color"])
|
||||
self.label.pack(expand=True)
|
||||
self.display_text.config(bg=self.settings["bg_color"], fg=self.settings["fg_color"])
|
||||
self.display_text.pack(expand=True)
|
||||
|
||||
# Posebni ukazi
|
||||
if self.song_number == "9999":
|
||||
@@ -323,6 +343,9 @@ class SongProjector:
|
||||
elif self.song_number == "9901":
|
||||
self.update_songs_database()
|
||||
return
|
||||
elif self.song_number == "9900":
|
||||
self.show_app_info_tkinter()
|
||||
return
|
||||
try:
|
||||
song_id = int(self.song_number)
|
||||
self.cursor.execute("SELECT lyrics FROM songs WHERE id=?", (song_id,))
|
||||
@@ -330,75 +353,97 @@ class SongProjector:
|
||||
if result:
|
||||
lyrics = result[0]
|
||||
|
||||
max_height = self.screen_height - (self.line_height * 1.5)
|
||||
avg_char_width = int(self.settings["font_size"]) * 0.57
|
||||
wraplength = self.color_width
|
||||
# Pustimo 10% varnostnega roba zgoraj in spodaj + prostor za song_info
|
||||
max_height = self.screen_height * 0.90
|
||||
|
||||
# -------------------------------------------
|
||||
# 1. Razbijanje besedila na (pod-)vrstice
|
||||
# -------------------------------------------
|
||||
raw_lines = lyrics.strip().splitlines()
|
||||
processed_lines = []
|
||||
for raw in raw_lines:
|
||||
if raw.strip() == "":
|
||||
processed_lines.append("") # ohranimo prazno vrstico
|
||||
else:
|
||||
processed_lines.extend(self.split_long_line(raw))
|
||||
# 1. Razdelimo na kitice (stanzas)
|
||||
# Kitice so ločene z dvojno prazno vrstico (\n\n\n ali \n\s*\n\s*\n)
|
||||
import re
|
||||
# Razdelimo po vsaj dveh praznih vrsticah (trije ali več \n)
|
||||
stanzas_raw = re.split(r'\n\s*\n\s*\n+', lyrics.strip())
|
||||
|
||||
processed_stanzas = []
|
||||
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:
|
||||
stanza_lines.append("") # Enojna prazna vrstica znotraj kitice
|
||||
if stanza_lines:
|
||||
processed_stanzas.append(stanza_lines)
|
||||
|
||||
# -------------------------------------------
|
||||
# 2. Razdeljevanje vrstic na strani
|
||||
# -------------------------------------------
|
||||
# 2. Razdeljevanje kitic na strani
|
||||
pages = []
|
||||
current_page_lines = []
|
||||
current_height = 0
|
||||
blank_line_count = 0
|
||||
split_by_stanza = self.settings.get("split_by_stanza", False)
|
||||
|
||||
for line in processed_lines:
|
||||
is_blank = (line.strip() == "")
|
||||
if is_blank:
|
||||
blank_line_count += 1
|
||||
else:
|
||||
blank_line_count = 0
|
||||
|
||||
approx_line_length = len(line)
|
||||
approx_line_count = 1 if is_blank else math.ceil((approx_line_length * avg_char_width) / wraplength)
|
||||
needed_height = self.line_height * approx_line_count
|
||||
|
||||
# Prazna vrstica več kot 1‑krat pomeni nova kitica ⇒ nova stran
|
||||
if blank_line_count >= 2:
|
||||
for stanza in processed_stanzas:
|
||||
stanza_height = len(stanza) * self.line_height
|
||||
|
||||
# Če je vklopljen split_by_stanza, vsaka kitica dobi svojo stran
|
||||
if split_by_stanza:
|
||||
if current_page_lines:
|
||||
pages.append("\n".join(current_page_lines).strip())
|
||||
pages.append("\n".join(current_page_lines))
|
||||
current_page_lines = []
|
||||
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
|
||||
|
||||
# Če čez spodnji rob strani …
|
||||
if current_height + needed_height > max_height + self.line_height // 2:
|
||||
# poskusimo prelomiti na prazni vrstici znotraj strani
|
||||
found_split = False
|
||||
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())
|
||||
# Standardna logika (več kitic na stran, če grejo)
|
||||
if stanza_height > max_height:
|
||||
if current_page_lines:
|
||||
pages.append("\n".join(current_page_lines))
|
||||
current_page_lines = []
|
||||
current_height = 0
|
||||
|
||||
current_page_lines.append(line)
|
||||
current_height += needed_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:
|
||||
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:
|
||||
pages.append("\n".join(current_page_lines).strip())
|
||||
pages.append("\n".join(current_page_lines))
|
||||
|
||||
self.pages = pages
|
||||
self.current_page_index = 0
|
||||
@@ -406,7 +451,7 @@ class SongProjector:
|
||||
self.song_number_last = self.song_number
|
||||
self.show_page()
|
||||
else:
|
||||
self.label.config(text="")
|
||||
self.display_text.config(text="")
|
||||
self.pages = []
|
||||
self.current_page_index = 0
|
||||
self.waiting_for_song = True
|
||||
@@ -414,7 +459,7 @@ class SongProjector:
|
||||
self.song_info_label.config(text=self.song_number_last)
|
||||
self.song_info_label.lift()
|
||||
except Exception as e:
|
||||
self.label.config(text=f"Napaka: {e}")
|
||||
self.display_text.config(text=f"Napaka: {e}")
|
||||
finally:
|
||||
self.song_number = ""
|
||||
|
||||
@@ -426,7 +471,7 @@ class SongProjector:
|
||||
text = self.pages[self.current_page_index]
|
||||
if self.all_caps_mode:
|
||||
text = text.upper()
|
||||
self.label.config(text=text)
|
||||
self.display_text.config(text=text)
|
||||
if self.settings.get("show_song_info", False):
|
||||
current_page = self.current_page_index + 1
|
||||
total_pages = len(self.pages)
|
||||
@@ -434,6 +479,7 @@ class SongProjector:
|
||||
self.song_info_label.lift()
|
||||
else:
|
||||
self.song_info_label.config(text="")
|
||||
notify_clients()
|
||||
|
||||
# ------------------------------------------------------
|
||||
# Navigacija po straneh
|
||||
@@ -457,11 +503,12 @@ class SongProjector:
|
||||
self.current_page_index = 0
|
||||
self.waiting_for_song = True
|
||||
|
||||
self.label.config(text="")
|
||||
self.label.pack_forget()
|
||||
self.display_text.config(text="")
|
||||
self.display_text.pack_forget()
|
||||
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.song_info_label.config(text="")
|
||||
notify_clients()
|
||||
|
||||
# ------------------------------------------------------
|
||||
# Iskanje po naslovu
|
||||
@@ -503,10 +550,10 @@ class SongProjector:
|
||||
query = self.search_entry.get().strip()
|
||||
self.search_label.destroy()
|
||||
self.search_entry.destroy()
|
||||
self.label.pack(expand=True)
|
||||
self.display_text.pack(expand=True)
|
||||
|
||||
if not query:
|
||||
self.label.config(text="(Prazno iskanje)")
|
||||
self.display_text.config(text="(Prazno iskanje)")
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -516,14 +563,14 @@ class SongProjector:
|
||||
)
|
||||
matched = self.cursor.fetchall()
|
||||
except Exception as e:
|
||||
self.label.config(text=f"Napaka pri iskanju: {e}")
|
||||
self.display_text.config(text=f"Napaka pri iskanju: {e}")
|
||||
return
|
||||
|
||||
if matched:
|
||||
found = "\n".join(f"{sid}: {title}" for sid, title in matched)
|
||||
self.label.config(text=found)
|
||||
self.display_text.config(text=found)
|
||||
else:
|
||||
self.label.config(text="Ni zadetkov.")
|
||||
self.display_text.config(text="Ni zadetkov.")
|
||||
|
||||
# ------------------------------------------------------
|
||||
# Posodobitev baze pesmi
|
||||
@@ -533,13 +580,13 @@ class SongProjector:
|
||||
if not url:
|
||||
msg = "URL za posodobitev ni nastavljen v settings.json."
|
||||
print(msg)
|
||||
self.label.config(text=msg)
|
||||
self.display_text.config(text=msg)
|
||||
self.song_number = ""
|
||||
return
|
||||
|
||||
msg = f"Prenašam posodobitev iz: {url}..."
|
||||
print(msg)
|
||||
self.label.config(text=msg)
|
||||
self.display_text.config(text=msg)
|
||||
self.root.update()
|
||||
|
||||
temp_db_path = None
|
||||
@@ -584,12 +631,12 @@ class SongProjector:
|
||||
|
||||
final_msg = f"Posodobitev uspešna! Posodobljenih/dodanih {upsert_count} pesmi."
|
||||
print(final_msg)
|
||||
self.label.config(text=final_msg)
|
||||
self.display_text.config(text=final_msg)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Napaka pri posodobitvi: {e}"
|
||||
print(error_msg)
|
||||
self.label.config(text=error_msg)
|
||||
self.display_text.config(text=error_msg)
|
||||
finally:
|
||||
if temp_db_path and os.path.exists(temp_db_path):
|
||||
try:
|
||||
@@ -673,6 +720,49 @@ class SongProjector:
|
||||
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
|
||||
# ----------------------------------------------------------
|
||||
|
||||
@@ -27,8 +27,11 @@ than being generated inside Python code.
|
||||
|
||||
import threading
|
||||
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
|
||||
app = Flask(__name__, static_folder="static", template_folder="templates")
|
||||
@@ -36,6 +39,17 @@ app = Flask(__name__, static_folder="static", template_folder="templates")
|
||||
# Globalna referenca na SongProjector aplikaciju
|
||||
_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):
|
||||
"""Postavi referenco na SongProjector aplikacijo"""
|
||||
@@ -62,6 +76,7 @@ def get_state():
|
||||
'current_text': 'Napaka: Aplikacija ni inicijalizirana',
|
||||
'page_info': '',
|
||||
'caps_mode': False,
|
||||
'split_by_stanza': False,
|
||||
'can_prev': False,
|
||||
'can_next': False
|
||||
})
|
||||
@@ -89,11 +104,32 @@ def get_state():
|
||||
'current_text': current_text,
|
||||
'page_info': page_info,
|
||||
'caps_mode': _projector_app.all_caps_mode,
|
||||
'split_by_stanza': _projector_app.settings.get("split_by_stanza", False),
|
||||
'can_prev': can_prev,
|
||||
'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'])
|
||||
def load_song():
|
||||
"""Naloži pesem po številki"""
|
||||
@@ -108,6 +144,7 @@ def load_song():
|
||||
_projector_app.load_song()
|
||||
if hasattr(_projector_app, 'show_page'):
|
||||
_projector_app.show_page()
|
||||
notify_clients()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -117,6 +154,7 @@ def next_page():
|
||||
"""Naslednja stran"""
|
||||
if _projector_app is not None:
|
||||
_projector_app.next_page()
|
||||
notify_clients()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -126,6 +164,7 @@ def prev_page():
|
||||
"""Prejšnja stran"""
|
||||
if _projector_app is not None:
|
||||
_projector_app.prev_page()
|
||||
notify_clients()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -135,6 +174,7 @@ def clear_screen():
|
||||
"""Zatemniti ekran"""
|
||||
if _projector_app is not None:
|
||||
_projector_app.clear_screen()
|
||||
notify_clients()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -145,10 +185,42 @@ def toggle_caps():
|
||||
if _projector_app is not None:
|
||||
_projector_app.all_caps_mode = not _projector_app.all_caps_mode
|
||||
_projector_app.show_page()
|
||||
notify_clients()
|
||||
|
||||
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'])
|
||||
def search_songs():
|
||||
"""Iskanje besedil po naslovu"""
|
||||
@@ -259,6 +331,7 @@ def update_song():
|
||||
if str(_projector_app.song_number_last) == str(song_id):
|
||||
_projector_app.song_number = str(song_id)
|
||||
_projector_app.load_song()
|
||||
notify_clients()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
except Exception as e:
|
||||
|
||||
@@ -7,8 +7,12 @@ const displayArea = document.getElementById('display-area');
|
||||
const prevBtn = document.getElementById('prev-btn');
|
||||
const nextBtn = document.getElementById('next-btn');
|
||||
const darkBtn = document.getElementById('dark-btn');
|
||||
const splitBtn = document.getElementById('split-btn');
|
||||
const pageInfo = document.getElementById('page-info');
|
||||
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 keypadWrapper = document.getElementById('keypad-wrapper');
|
||||
const toggleKeypadBtn = document.getElementById('toggle-keypad-btn');
|
||||
@@ -37,6 +41,7 @@ const infoMessage = document.getElementById('info-message');
|
||||
const infoOkBtn = document.getElementById('info-ok-btn');
|
||||
|
||||
let capsMode = false;
|
||||
let splitByStanza = false;
|
||||
let wakeLock = null;
|
||||
let lastStateSignature = "";
|
||||
let lastPageInfo = "";
|
||||
@@ -81,6 +86,7 @@ async function updateState(force = false) {
|
||||
current_text: data.current_text || '',
|
||||
page_info: data.page_info || '',
|
||||
caps_mode: data.caps_mode || false,
|
||||
split_by_stanza: data.split_by_stanza || false,
|
||||
can_prev: !!data.can_prev
|
||||
});
|
||||
|
||||
@@ -102,6 +108,13 @@ async function updateState(force = false) {
|
||||
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;
|
||||
} catch (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
|
||||
async function openEditor(songId = null) {
|
||||
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
|
||||
function toggleKeypad() {
|
||||
if (!keypadWrapper || !toggleKeypadBtn) return;
|
||||
@@ -383,6 +441,14 @@ darkBtn.addEventListener('click', () => {
|
||||
toggleCaps();
|
||||
});
|
||||
|
||||
// Prelom po kiticah
|
||||
if (splitBtn) {
|
||||
splitBtn.addEventListener('click', () => {
|
||||
vibrate();
|
||||
toggleSplit();
|
||||
});
|
||||
}
|
||||
|
||||
// Skrij/Pokaži tipkovnico
|
||||
if (toggleKeypadBtn) {
|
||||
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
|
||||
if (editSongBtn) {
|
||||
editSongBtn.addEventListener('click', () => {
|
||||
@@ -461,6 +541,10 @@ document.addEventListener('click', (e) => {
|
||||
if (menuDropdown && !menuDropdown.contains(e.target) && e.target !== menuToggle) {
|
||||
menuDropdown.classList.remove('show');
|
||||
}
|
||||
// Zapri About modal ob kliku izven vsebine
|
||||
if (e.target === aboutModal) {
|
||||
aboutModal.classList.remove('show');
|
||||
}
|
||||
});
|
||||
|
||||
// Iskanje dogodki
|
||||
@@ -551,10 +635,10 @@ document.addEventListener('keydown', (e) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// AAaa
|
||||
// preklopi prelom
|
||||
if (e.key === '*' || e.code === 'NumpadMultiply') {
|
||||
e.preventDefault();
|
||||
toggleCaps();
|
||||
toggleSplit();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -569,9 +653,24 @@ document.addEventListener('keydown', (e) => {
|
||||
updateState(true);
|
||||
requestWakeLock();
|
||||
|
||||
// osveževanje za sinhronizacijo med več napravami
|
||||
setInterval(() => {
|
||||
updateState(false);
|
||||
}, 1000);
|
||||
// SSE osveževanje za sinhronizacijo med več napravami
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
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');
|
||||
@@ -28,7 +28,7 @@
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Times New Roman', serif;
|
||||
font-family: 'Noto Sans', sans-serif;
|
||||
background-color: #0a0a0a;
|
||||
color: #ffffff;
|
||||
min-height: var(--container-min-h);
|
||||
@@ -429,6 +429,12 @@ body {
|
||||
height: 100%;
|
||||
background-color: rgba(0,0,0,0.8);
|
||||
overflow-y: auto;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.modal.show {
|
||||
display: flex !important;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
@@ -474,6 +480,59 @@ textarea.form-control {
|
||||
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 {
|
||||
background-color: #1f8a46;
|
||||
color: white;
|
||||
|
||||
@@ -26,7 +26,9 @@
|
||||
<div id="menu-dropdown" class="menu-dropdown">
|
||||
<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="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="about-btn" class="menu-item" type="button">O programu</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -78,6 +80,27 @@
|
||||
</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 id="display-area" class="lyrics-display">
|
||||
|
||||
Reference in New Issue
Block a user