7 Commits

5 changed files with 188 additions and 106 deletions

View File

@@ -21,6 +21,7 @@
import sqlite3
import tkinter as tk
from tkinter import font
import json
import os
import math
@@ -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 podvrstic
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
test_line = " ".join(current_words + [word])
# Izmerimo širino v pikslih
if self.custom_font.measure(test_line) <= self.color_width:
current_words.append(word)
else:
if current_words:
sub_lines.append(" ".join(current_words))
current_words = [word]
current_len = len(word)
else:
current_words.append(word)
current_len += added_len
# 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":
@@ -330,75 +350,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
# 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:
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 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
for stanza in processed_stanzas:
stanza_height = len(stanza) * self.line_height
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 1krat pomeni nova kitica ⇒ nova stran
if blank_line_count >= 2:
# Č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 +448,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 +456,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 +468,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)
@@ -457,8 +499,8 @@ 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="")
@@ -503,10 +545,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 +558,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 +575,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 +626,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:

View File

@@ -62,6 +62,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,6 +90,7 @@ 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
})
@@ -149,6 +151,15 @@ def toggle_caps():
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()
return jsonify({'status': 'ok'})
@app.route('/api/search_songs', methods=['POST'])
def search_songs():
"""Iskanje besedil po naslovu"""

View File

@@ -7,6 +7,7 @@ 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 keypadButtons = document.querySelectorAll('.btn-key');
@@ -37,6 +38,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 +83,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 +105,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 +247,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 {
@@ -383,6 +403,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) => {
@@ -551,10 +579,10 @@ document.addEventListener('keydown', (e) => {
return;
}
// AAaa
// preklopi prelom
if (e.key === '*' || e.code === 'NumpadMultiply') {
e.preventDefault();
toggleCaps();
toggleSplit();
return;
}

View File

@@ -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);

View File

@@ -26,6 +26,7 @@
<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>
</div>
</div>