379 lines
13 KiB
Python
379 lines
13 KiB
Python
"""Hauptprogramm: Ein kleiner Texteditor auf Basis von Tkinter.
|
||
|
||
Start:
|
||
python app.py
|
||
|
||
Die UI (Fenster, Menü, Textbereich, Statusleiste) und die Bedienung der
|
||
Dialoge liegen hier; die reine Datei-I/O-Logik liegt in file_io.py und die
|
||
Tokenizing for the Syntax-Highlighting in highlight.py.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import tkinter as tk
|
||
from pathlib import Path
|
||
from tkinter import filedialog, messagebox
|
||
|
||
from file_io import FileLoadError, FileSaveError, load_file, save_file
|
||
from highlight import (
|
||
HIGHLIGHT_TAGS,
|
||
TAG_COLORS,
|
||
detect_language,
|
||
tokenize_python,
|
||
)
|
||
|
||
APP_TITLE = "Texteditor"
|
||
FILE_TYPES = [("Textdateien", "*.txt"), ("Alle Dateien", "*.*")]
|
||
|
||
|
||
class TextEditorApp:
|
||
"""Tkinter-Anwendung mit einem Texteditor für eine offene Datei."""
|
||
|
||
def __init__(self, root: tk.Tk) -> None:
|
||
self.root = root
|
||
self.file_path: Path | None = None
|
||
self._modified = False
|
||
self.language: str | None = None
|
||
|
||
self.root.title(self._build_title())
|
||
self.root.geometry("800x600")
|
||
self.root.minsize(400, 300)
|
||
|
||
self._build_menu()
|
||
self._build_text_area()
|
||
self._build_status_bar()
|
||
self.root.protocol("WM_DELETE_WINDOW", self._on_exit)
|
||
|
||
# ------------------------------------------------------------ UI-Aufbau --
|
||
|
||
def _build_menu(self) -> None:
|
||
menubar = tk.Menu(self.root)
|
||
|
||
file_menu = tk.Menu(menubar, tearoff=False)
|
||
file_menu.add_command(
|
||
label="Neu",
|
||
accelerator="Strg+N",
|
||
command=self.new_file,
|
||
)
|
||
file_menu.add_command(
|
||
label="Öffnen…",
|
||
accelerator="Strg+O",
|
||
command=self.open_file,
|
||
)
|
||
file_menu.add_command(
|
||
label="Speichern",
|
||
accelerator="Strg+S",
|
||
command=self.save_file,
|
||
)
|
||
file_menu.add_command(
|
||
label="Speichern unter…",
|
||
accelerator="Strg+Shift+S",
|
||
command=self.save_file_as,
|
||
)
|
||
file_menu.add_separator()
|
||
file_menu.add_command(
|
||
label="Beenden",
|
||
accelerator="Alt+F4",
|
||
command=self._on_exit,
|
||
)
|
||
menubar.add_cascade(label="Datei", menu=file_menu)
|
||
|
||
help_menu = tk.Menu(menubar, tearoff=False)
|
||
help_menu.add_command(label="Über Texteditor…", command=self._on_about)
|
||
menubar.add_cascade(label="Hilfe", menu=help_menu)
|
||
|
||
# No Shortcut: <Control-h> would collide with the built-in
|
||
# Backspace-Binding of the Text-Widget.
|
||
format_menu = tk.Menu(menubar, tearoff=False)
|
||
highlight_menu = tk.Menu(menubar, tearoff=False)
|
||
highlight_menu.add_command(label="Plain Text", command=self.use_plain_text)
|
||
highlight_menu.add_command(label="Python", command=self.use_python)
|
||
format_menu.add_cascade(
|
||
label="Syntax Highlighting…", menu=highlight_menu
|
||
)
|
||
menubar.add_cascade(label="Formatierung", menu=format_menu)
|
||
|
||
self.root.config(menu=menubar)
|
||
self._bind_shortcuts()
|
||
|
||
def _bind_shortcuts(self) -> None:
|
||
# Groß- und klein geschrieben: Tkinter bindet Großbuchstaben nur zu,
|
||
# wenn Shift gedrückt ist; beide Varianten garantieren die Zuordnung
|
||
# in jeder Shift-Kombination (außer bei Caps Lock).
|
||
self.root.bind("<Control-n>", self.new_file)
|
||
self.root.bind("<Control-N>", self.new_file)
|
||
self.root.bind("<Control-o>", self.open_file)
|
||
self.root.bind("<Control-O>", self.open_file)
|
||
self.root.bind("<Control-s>", self.save_file)
|
||
self.root.bind("<Control-S>", self.save_file)
|
||
self.root.bind("<Control-Shift-s>", self.save_file_as)
|
||
self.root.bind("<Control-Shift-S>", self.save_file_as)
|
||
|
||
def _build_text_area(self) -> None:
|
||
container = tk.Frame(self.root)
|
||
container.pack(fill="both", expand=True)
|
||
|
||
self.text = tk.Text(
|
||
container,
|
||
wrap="none",
|
||
undo=True,
|
||
font=("Consolas", 11),
|
||
relief="flat",
|
||
)
|
||
# Highlighting-Colors per Tag, configured once.
|
||
for tag, color in TAG_COLORS.items():
|
||
self.text.tag_config(tag, foreground=color)
|
||
|
||
v_scroll = tk.Scrollbar(
|
||
container, orient="vertical", command=self.text.yview
|
||
)
|
||
h_scroll = tk.Scrollbar(
|
||
container, orient="horizontal", command=self.text.xview
|
||
)
|
||
self.text.configure(
|
||
yscrollcommand=v_scroll.set, xscrollcommand=h_scroll.set
|
||
)
|
||
|
||
self.text.grid(row=0, column=0, sticky="nsew")
|
||
v_scroll.grid(row=0, column=1, sticky="ns")
|
||
h_scroll.grid(row=1, column=0, sticky="ew")
|
||
container.grid_rowconfigure(0, weight=1)
|
||
container.grid_columnconfigure(0, weight=1)
|
||
|
||
# Ereignisse, die bei jeder Änderung/Navigation neu ausgelöst werden:
|
||
self.text.bind("<<Modified>>", self._on_text_modified)
|
||
self.text.bind("<KeyRelease>", self._update_status)
|
||
self.text.bind("<ButtonRelease-1>", self._update_status)
|
||
|
||
def _build_status_bar(self) -> None:
|
||
status = tk.Frame(self.root, relief="sunken", borderwidth=1)
|
||
status.pack(side="bottom", fill="x")
|
||
|
||
self.lbl_cursor = tk.Label(status, text="Zeile 1, Spalte 1", padx=10)
|
||
self.lbl_chars = tk.Label(status, text="0 Zeichen", padx=10)
|
||
self.lbl_cursor.pack(side="left")
|
||
self.lbl_chars.pack(side="right")
|
||
|
||
# ---------------------------------------------------------- Titel & Status --
|
||
|
||
def _build_title(self) -> str:
|
||
name = self.file_path.name if self.file_path else "Ohne Titel"
|
||
title = f"{name} – {APP_TITLE}"
|
||
return f"*{title}" if self._modified else title
|
||
|
||
def _update_title(self) -> None:
|
||
self.root.title(self._build_title())
|
||
|
||
def _update_status(self, event=None) -> None:
|
||
line, col = self.text.index("insert").split(".")
|
||
self.lbl_cursor.config(
|
||
text=f"Zeile {int(line)}, Spalte {int(col) + 1}"
|
||
)
|
||
char_count = len(self.text.get("1.0", "end-1c"))
|
||
self.lbl_chars.config(text=f"{char_count} Zeichen")
|
||
|
||
def _on_text_modified(self, event=None) -> None:
|
||
"""Verfolgt ungespeicherte Änderungen über <<Modified>>.
|
||
|
||
Tk feuert für jede Änderung ZWEI <<Modified>>-Ereignisse: eines,
|
||
wenn der Dirty-Flag von 0→1 springt, und ein zweites (Echo), weil
|
||
das manuelle ``edit_modified(False)`` selbst den Rückfall 1→0
|
||
meldet. Das Ereignis wird also immer aktiv gelaufen:
|
||
ist der Flag gesetzt, wurde eingegeben → Dirty-Status setzen und
|
||
Flag consume. Der nachfolgende Echo-Ruf sieht dann Flag==False
|
||
und ändert nichts mehr. Abgespeichert (``_do_save``) und
|
||
Programm-Eingriffe (``_set_content``) setzen den Dirty-Status
|
||
selbst zurück.
|
||
"""
|
||
if self.text.edit_modified():
|
||
self.text.edit_modified(False)
|
||
if not self._modified:
|
||
self._modified = True
|
||
self._update_title()
|
||
self._apply_highlighting()
|
||
self._update_status()
|
||
|
||
def _set_content(self, content: str) -> None:
|
||
"""Ersetzt den Textinhalt und setzt die Änderungs- und Undo-Marker zurück."""
|
||
self.text.delete("1.0", "end")
|
||
self.text.insert("1.0", content)
|
||
self.text.edit_reset() # Undo-Verlauf des vorherigen Dokuments
|
||
self.text.edit_modified(False) # Programmänderung zählt nicht
|
||
self._modified = False
|
||
self._apply_highlighting()
|
||
self._update_title()
|
||
self._update_status()
|
||
|
||
# ------------------------------------------------------- Syntax-Highlighting --
|
||
|
||
def set_language(self, language: str | None) -> None:
|
||
"""Sets the Highlighting-Language and reapplies the Highlighting."""
|
||
self.language = language
|
||
self._apply_highlighting()
|
||
|
||
def use_plain_text(self, event=None) -> None:
|
||
self.set_language(None)
|
||
|
||
def use_python(self, event=None) -> None:
|
||
self.set_language("python")
|
||
|
||
def _apply_highlighting(self) -> None:
|
||
"""Applies the Tags of the current Language over the whole Document.
|
||
|
||
Old Tags are always deleted first: Tk-Tags accumulate and the Undo-
|
||
Mechanism does not restore them, therefore the complete Document is
|
||
always highlighted anew.
|
||
"""
|
||
# Tkinter wraps no single ``tag_remove`` of ALL Tags, but the
|
||
# no-op form (tag REMOVE over a RANGE) requires a TAG name as
|
||
# the first argument. So we clear each highlight-tag itself
|
||
# across the whole document; the tag DEFINITION (color) stays
|
||
# configured, only the ranges disappear.
|
||
for tag in HIGHLIGHT_TAGS:
|
||
self.text.tag_remove(tag, "1.0", "end")
|
||
if self.language != "python":
|
||
return
|
||
source = self.text.get("1.0", "end-1c")
|
||
for tag, (srow, scol), (erow, ecol) in tokenize_python(source):
|
||
self._tag_range(tag, srow, scol, erow, ecol)
|
||
|
||
def _tag_range(self, tag: str, srow: int, scol: int, erow: int, ecol: int) -> None:
|
||
"""Colors one Token-Range.
|
||
|
||
Tokenize- und Tk-Positionen sind hier kongruent: Zeile 1-basiert,
|
||
Spalte 0-basiert. Der Tk-Index-String nutzt daher einen Punkt
|
||
("1.1"), nicht einen Doppelpunkt, und benötigt kein +1 auf die
|
||
Spalte – der Token-Endpunkt ist (wie bei Tk) bereits exklusiv.
|
||
"""
|
||
try:
|
||
self.text.tag_add(tag, f"{srow}.{scol}", f"{erow}.{ecol}")
|
||
except tk.TclError: # Index outside the Document (Race-Condition)
|
||
pass
|
||
|
||
# -------------------------------------------------------------- Dateifunktionen --
|
||
|
||
def _confirm_save(self) -> bool:
|
||
"""Fragt, ob ungespeicherte Änderungen gespeichert werden sollen.
|
||
|
||
Returns:
|
||
True, wenn die Aktion (Neu/Öffnen/Beenden) fortgesetzt
|
||
werden darf, False, wenn sie abgebrochen werden soll.
|
||
"""
|
||
if not self._modified:
|
||
return True
|
||
answer = messagebox.askyesnocancel(
|
||
title="Änderungen speichern?",
|
||
message=(
|
||
"Die aktuellen Änderungen wurden noch nicht gespeichert.\n"
|
||
"Möchtest du die Änderungen speichern?"
|
||
),
|
||
icon="question",
|
||
default="no",
|
||
parent=self.root,
|
||
)
|
||
if answer is None: # Abbrechen
|
||
return False
|
||
if answer: # Ja → speichern
|
||
return self.save_file()
|
||
return True # Nein → Änderungen verwerfen
|
||
|
||
def new_file(self, event=None) -> None:
|
||
if not self._confirm_save():
|
||
return
|
||
self.file_path = None
|
||
self.language = None
|
||
self._set_content("")
|
||
|
||
def open_file(self, event=None) -> None:
|
||
if not self._confirm_save():
|
||
return
|
||
path = filedialog.askopenfilename(
|
||
parent=self.root,
|
||
title="Datei öffnen",
|
||
filetypes=FILE_TYPES,
|
||
)
|
||
if not path:
|
||
return
|
||
try:
|
||
content = load_file(path)
|
||
except FileLoadError as exc:
|
||
messagebox.showerror(APP_TITLE, str(exc), parent=self.root)
|
||
return
|
||
self.file_path = Path(path)
|
||
# Language guess from the Suffix; the Menu-Choice of the User wins
|
||
# again until the next File-Opening.
|
||
self.language = detect_language(path)
|
||
self._set_content(content)
|
||
|
||
def save_file(self, event=None) -> bool:
|
||
"""Speichert das aktuelle Dokument.
|
||
|
||
Returns:
|
||
True, wenn die Speicherung erfolgreich war oder nicht
|
||
nötig war, False, wenn sie fehlgeschlagen oder abgebrochen
|
||
wurde.
|
||
"""
|
||
if self.file_path is not None and not self._modified:
|
||
return True
|
||
if self.file_path is None:
|
||
return self.save_file_as()
|
||
return self._do_save()
|
||
|
||
def save_file_as(self, event=None) -> bool:
|
||
initial = self.file_path.name if self.file_path else "unbenannt.txt"
|
||
path = filedialog.asksaveasfilename(
|
||
parent=self.root,
|
||
title="Speichern unter",
|
||
defaultextension=".txt",
|
||
initialfile=initial,
|
||
filetypes=FILE_TYPES,
|
||
)
|
||
if not path: # Abbrechen
|
||
return False
|
||
self.file_path = Path(path)
|
||
return self._do_save()
|
||
|
||
def _do_save(self) -> bool:
|
||
assert self.file_path is not None
|
||
try:
|
||
save_file(self.file_path, self.text.get("1.0", "end-1c"))
|
||
except FileSaveError as exc:
|
||
messagebox.showerror(APP_TITLE, str(exc), parent=self.root)
|
||
return False
|
||
self._modified = False
|
||
self._update_title()
|
||
return True
|
||
|
||
# ------------------------------------------------------------------ Sonstiges --
|
||
|
||
def _on_exit(self, event=None) -> None:
|
||
if not self._confirm_save():
|
||
return
|
||
self.root.destroy()
|
||
|
||
def _on_about(self) -> None:
|
||
messagebox.showinfo(
|
||
"Über Texteditor",
|
||
"Texteditor\n\n"
|
||
"Ein kleiner Texteditor, gebaut mit Tkinter und Python.",
|
||
parent=self.root,
|
||
)
|
||
|
||
|
||
def main() -> None:
|
||
# Schärferes Rendering auf Windows bei hochauflösender Anzeige.
|
||
try:
|
||
import ctypes
|
||
|
||
ctypes.windll.shcore.SetProcessDpiAwareness(1)
|
||
except Exception:
|
||
pass
|
||
|
||
root = tk.Tk()
|
||
TextEditorApp(root)
|
||
root.mainloop()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|