feat: windows installer with remote updates and remote management added.
This commit is contained in:
459
settings_dialog.py
Normal file
459
settings_dialog.py
Normal file
@@ -0,0 +1,459 @@
|
||||
"""
|
||||
Series 3 Watcher — Settings Dialog v1.4.0
|
||||
|
||||
Provides a Tkinter settings dialog that doubles as a first-run wizard.
|
||||
|
||||
Public API:
|
||||
show_dialog(config_path, wizard=False) -> bool
|
||||
Returns True if the user saved, False if they cancelled.
|
||||
|
||||
Python 3.8 compatible — no walrus operators, no f-string = specifier,
|
||||
no match statements, no 3.9+ syntax.
|
||||
No external dependencies beyond stdlib + tkinter.
|
||||
"""
|
||||
|
||||
import os
|
||||
import configparser
|
||||
import tkinter as tk
|
||||
from tkinter import ttk, filedialog, messagebox
|
||||
from socket import gethostname
|
||||
|
||||
|
||||
# --------------- Defaults (mirror config-template.ini) ---------------
|
||||
|
||||
DEFAULTS = {
|
||||
"API_ENABLED": "true",
|
||||
"API_URL": "",
|
||||
"API_INTERVAL_SECONDS": "300",
|
||||
"SOURCE_ID": "", # empty = use hostname at runtime
|
||||
"SOURCE_TYPE": "series3_watcher",
|
||||
"SERIES3_PATH": r"C:\Blastware 10\Event\autocall home",
|
||||
"MAX_EVENT_AGE_DAYS": "365",
|
||||
"SCAN_INTERVAL_SECONDS":"300",
|
||||
"OK_HOURS": "12",
|
||||
"MISSING_HOURS": "24",
|
||||
"MLG_HEADER_BYTES": "2048",
|
||||
"ENABLE_LOGGING": "true",
|
||||
"LOG_FILE": r"C:\SeismoEmitter\agent_logs\series3_watcher.log",
|
||||
"LOG_RETENTION_DAYS": "30",
|
||||
"COLORIZE": "false",
|
||||
}
|
||||
|
||||
|
||||
# --------------- Config I/O ---------------
|
||||
|
||||
def _load_config(config_path):
|
||||
"""
|
||||
Load existing config.ini. Returns a flat dict of string values.
|
||||
Falls back to DEFAULTS for any missing key.
|
||||
"""
|
||||
values = dict(DEFAULTS)
|
||||
if not os.path.exists(config_path):
|
||||
return values
|
||||
|
||||
cp = configparser.ConfigParser(inline_comment_prefixes=(";", "#"))
|
||||
cp.optionxform = str
|
||||
try:
|
||||
cp.read(config_path, encoding="utf-8")
|
||||
except Exception:
|
||||
return values
|
||||
|
||||
# Accept either [agent] section or a bare file
|
||||
section = None
|
||||
if cp.has_section("agent"):
|
||||
section = "agent"
|
||||
elif cp.sections():
|
||||
section = cp.sections()[0]
|
||||
|
||||
if section:
|
||||
for k in DEFAULTS:
|
||||
if cp.has_option(section, k):
|
||||
values[k] = cp.get(section, k).strip()
|
||||
|
||||
return values
|
||||
|
||||
|
||||
def _save_config(config_path, values):
|
||||
"""Write all values to config_path under [agent] section."""
|
||||
cp = configparser.ConfigParser()
|
||||
cp.optionxform = str
|
||||
cp["agent"] = {}
|
||||
for k, v in values.items():
|
||||
cp["agent"][k] = v
|
||||
|
||||
config_dir = os.path.dirname(config_path)
|
||||
if config_dir and not os.path.exists(config_dir):
|
||||
os.makedirs(config_dir)
|
||||
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
cp.write(f)
|
||||
|
||||
|
||||
# --------------- Spinbox helper ---------------
|
||||
|
||||
def _make_spinbox(parent, from_, to, width=8):
|
||||
"""Create a ttk.Spinbox; fall back to tk.Spinbox on older ttk."""
|
||||
try:
|
||||
sb = ttk.Spinbox(parent, from_=from_, to=to, width=width)
|
||||
except AttributeError:
|
||||
# ttk.Spinbox added in Python 3.7 but not available everywhere
|
||||
sb = tk.Spinbox(parent, from_=from_, to=to, width=width)
|
||||
return sb
|
||||
|
||||
|
||||
# --------------- Field helpers ---------------
|
||||
|
||||
def _add_label_entry(frame, row, label_text, var, hint=None, readonly=False):
|
||||
"""Add a label + entry row to a grid frame. Returns the Entry widget."""
|
||||
tk.Label(frame, text=label_text, anchor="w").grid(
|
||||
row=row, column=0, sticky="w", padx=(8, 4), pady=4
|
||||
)
|
||||
state = "readonly" if readonly else "normal"
|
||||
entry = ttk.Entry(frame, textvariable=var, width=42, state=state)
|
||||
entry.grid(row=row, column=1, sticky="ew", padx=(0, 8), pady=4)
|
||||
if hint and not var.get():
|
||||
# Show placeholder hint in grey; clear on focus
|
||||
entry.config(foreground="grey")
|
||||
entry.insert(0, hint)
|
||||
|
||||
def _on_focus_in(event, e=entry, h=hint, v=var):
|
||||
if e.get() == h:
|
||||
e.delete(0, tk.END)
|
||||
e.config(foreground="black")
|
||||
|
||||
def _on_focus_out(event, e=entry, h=hint, v=var):
|
||||
if not e.get():
|
||||
e.config(foreground="grey")
|
||||
e.insert(0, h)
|
||||
v.set("")
|
||||
|
||||
entry.bind("<FocusIn>", _on_focus_in)
|
||||
entry.bind("<FocusOut>", _on_focus_out)
|
||||
return entry
|
||||
|
||||
|
||||
def _add_label_spinbox(frame, row, label_text, var, from_, to):
|
||||
"""Add a label + spinbox row to a grid frame. Returns the Spinbox widget."""
|
||||
tk.Label(frame, text=label_text, anchor="w").grid(
|
||||
row=row, column=0, sticky="w", padx=(8, 4), pady=4
|
||||
)
|
||||
sb = _make_spinbox(frame, from_=from_, to=to, width=8)
|
||||
sb.grid(row=row, column=1, sticky="w", padx=(0, 8), pady=4)
|
||||
sb.delete(0, tk.END)
|
||||
sb.insert(0, var.get())
|
||||
|
||||
def _on_change(*args):
|
||||
var.set(sb.get())
|
||||
|
||||
sb.config(command=_on_change)
|
||||
sb.bind("<KeyRelease>", _on_change)
|
||||
return sb
|
||||
|
||||
|
||||
def _add_label_check(frame, row, label_text, var):
|
||||
"""Add a checkbox row to a grid frame."""
|
||||
cb = ttk.Checkbutton(frame, text=label_text, variable=var)
|
||||
cb.grid(row=row, column=0, columnspan=2, sticky="w", padx=(8, 8), pady=4)
|
||||
return cb
|
||||
|
||||
|
||||
def _add_label_browse_entry(frame, row, label_text, var, browse_fn):
|
||||
"""Add a label + entry + Browse button row."""
|
||||
tk.Label(frame, text=label_text, anchor="w").grid(
|
||||
row=row, column=0, sticky="w", padx=(8, 4), pady=4
|
||||
)
|
||||
inner = tk.Frame(frame)
|
||||
inner.grid(row=row, column=1, sticky="ew", padx=(0, 8), pady=4)
|
||||
inner.columnconfigure(0, weight=1)
|
||||
|
||||
entry = ttk.Entry(inner, textvariable=var, width=36)
|
||||
entry.grid(row=0, column=0, sticky="ew")
|
||||
btn = ttk.Button(inner, text="Browse...", command=browse_fn, width=9)
|
||||
btn.grid(row=0, column=1, padx=(4, 0))
|
||||
return entry
|
||||
|
||||
|
||||
# --------------- Main dialog class ---------------
|
||||
|
||||
class SettingsDialog:
|
||||
def __init__(self, parent, config_path, wizard=False):
|
||||
self.config_path = config_path
|
||||
self.wizard = wizard
|
||||
self.saved = False
|
||||
|
||||
self.root = parent
|
||||
if wizard:
|
||||
self.root.title("Series 3 Watcher — Setup")
|
||||
else:
|
||||
self.root.title("Series 3 Watcher — Settings")
|
||||
self.root.resizable(False, False)
|
||||
|
||||
# Center on screen
|
||||
self.root.update_idletasks()
|
||||
|
||||
self._values = _load_config(config_path)
|
||||
self._build_vars()
|
||||
self._build_ui()
|
||||
|
||||
# Make dialog modal
|
||||
self.root.grab_set()
|
||||
self.root.protocol("WM_DELETE_WINDOW", self._on_cancel)
|
||||
|
||||
# --- Variable setup ---
|
||||
|
||||
def _build_vars(self):
|
||||
v = self._values
|
||||
|
||||
# Connection
|
||||
self.var_api_enabled = tk.BooleanVar(value=v["API_ENABLED"].lower() in ("1","true","yes","on"))
|
||||
self.var_api_url = tk.StringVar(value=v["API_URL"])
|
||||
self.var_api_interval = tk.StringVar(value=v["API_INTERVAL_SECONDS"])
|
||||
self.var_source_id = tk.StringVar(value=v["SOURCE_ID"])
|
||||
self.var_source_type = tk.StringVar(value=v["SOURCE_TYPE"])
|
||||
|
||||
# Paths
|
||||
self.var_series3_path = tk.StringVar(value=v["SERIES3_PATH"])
|
||||
self.var_max_event_age_days = tk.StringVar(value=v["MAX_EVENT_AGE_DAYS"])
|
||||
self.var_log_file = tk.StringVar(value=v["LOG_FILE"])
|
||||
|
||||
# Scanning
|
||||
self.var_scan_interval = tk.StringVar(value=v["SCAN_INTERVAL_SECONDS"])
|
||||
self.var_ok_hours = tk.StringVar(value=v["OK_HOURS"])
|
||||
self.var_missing_hours = tk.StringVar(value=v["MISSING_HOURS"])
|
||||
self.var_mlg_header_bytes = tk.StringVar(value=v["MLG_HEADER_BYTES"])
|
||||
|
||||
# Logging
|
||||
self.var_enable_logging = tk.BooleanVar(value=v["ENABLE_LOGGING"].lower() in ("1","true","yes","on"))
|
||||
self.var_log_retention_days = tk.StringVar(value=v["LOG_RETENTION_DAYS"])
|
||||
self.var_colorize = tk.BooleanVar(value=v["COLORIZE"].lower() in ("1","true","yes","on"))
|
||||
|
||||
# --- UI construction ---
|
||||
|
||||
def _build_ui(self):
|
||||
outer = tk.Frame(self.root, padx=10, pady=8)
|
||||
outer.pack(fill="both", expand=True)
|
||||
|
||||
if self.wizard:
|
||||
welcome = (
|
||||
"Welcome to Series 3 Watcher!\n\n"
|
||||
"No configuration file was found. Please review the settings below\n"
|
||||
"and click \"Save & Start\" when you are ready."
|
||||
)
|
||||
lbl = tk.Label(
|
||||
outer, text=welcome, justify="left",
|
||||
wraplength=460, fg="#1a5276", font=("TkDefaultFont", 9, "bold"),
|
||||
)
|
||||
lbl.pack(fill="x", pady=(0, 8))
|
||||
|
||||
# Notebook
|
||||
nb = ttk.Notebook(outer)
|
||||
nb.pack(fill="both", expand=True)
|
||||
|
||||
self._build_tab_connection(nb)
|
||||
self._build_tab_paths(nb)
|
||||
self._build_tab_scanning(nb)
|
||||
self._build_tab_logging(nb)
|
||||
|
||||
# Buttons
|
||||
btn_frame = tk.Frame(outer)
|
||||
btn_frame.pack(fill="x", pady=(10, 0))
|
||||
|
||||
save_label = "Save & Start" if self.wizard else "Save"
|
||||
btn_save = ttk.Button(btn_frame, text=save_label, command=self._on_save, width=14)
|
||||
btn_save.pack(side="right", padx=(4, 0))
|
||||
|
||||
btn_cancel = ttk.Button(btn_frame, text="Cancel", command=self._on_cancel, width=10)
|
||||
btn_cancel.pack(side="right")
|
||||
|
||||
def _tab_frame(self, nb, title):
|
||||
"""Create a new tab in nb, return a scrollable inner frame."""
|
||||
outer = tk.Frame(nb, padx=4, pady=4)
|
||||
nb.add(outer, text=title)
|
||||
outer.columnconfigure(1, weight=1)
|
||||
return outer
|
||||
|
||||
def _build_tab_connection(self, nb):
|
||||
f = self._tab_frame(nb, "Connection")
|
||||
|
||||
_add_label_check(f, 0, "API Enabled", self.var_api_enabled)
|
||||
|
||||
_add_label_entry(
|
||||
f, 1, "terra-view URL", self.var_api_url,
|
||||
hint="http://192.168.x.x:8000/api/heartbeat",
|
||||
)
|
||||
|
||||
_add_label_spinbox(f, 2, "API Interval (sec)", self.var_api_interval, 30, 3600)
|
||||
|
||||
source_id_hint = "Defaults to hostname ({})".format(gethostname())
|
||||
_add_label_entry(f, 3, "Source ID", self.var_source_id, hint=source_id_hint)
|
||||
|
||||
_add_label_entry(f, 4, "Source Type", self.var_source_type, readonly=True)
|
||||
|
||||
def _build_tab_paths(self, nb):
|
||||
f = self._tab_frame(nb, "Paths")
|
||||
|
||||
def browse_series3():
|
||||
d = filedialog.askdirectory(
|
||||
title="Select Blastware Event Folder",
|
||||
initialdir=self.var_series3_path.get() or "C:\\",
|
||||
)
|
||||
if d:
|
||||
self.var_series3_path.set(d.replace("/", "\\"))
|
||||
|
||||
_add_label_browse_entry(f, 0, "Series3 Path", self.var_series3_path, browse_series3)
|
||||
_add_label_spinbox(f, 1, "Max Event Age (days)", self.var_max_event_age_days, 1, 3650)
|
||||
|
||||
def browse_log():
|
||||
p = filedialog.asksaveasfilename(
|
||||
title="Select Log File",
|
||||
defaultextension=".log",
|
||||
filetypes=[("Log files", "*.log"), ("Text files", "*.txt"), ("All files", "*.*")],
|
||||
initialfile=os.path.basename(self.var_log_file.get() or "series3_watcher.log"),
|
||||
initialdir=os.path.dirname(self.var_log_file.get() or "C:\\"),
|
||||
)
|
||||
if p:
|
||||
self.var_log_file.set(p.replace("/", "\\"))
|
||||
|
||||
_add_label_browse_entry(f, 2, "Log File", self.var_log_file, browse_log)
|
||||
|
||||
def _build_tab_scanning(self, nb):
|
||||
f = self._tab_frame(nb, "Scanning")
|
||||
_add_label_spinbox(f, 0, "Scan Interval (sec)", self.var_scan_interval, 10, 3600)
|
||||
_add_label_spinbox(f, 1, "OK Hours", self.var_ok_hours, 1, 168)
|
||||
_add_label_spinbox(f, 2, "Missing Hours", self.var_missing_hours, 1, 168)
|
||||
_add_label_spinbox(f, 3, "MLG Header Bytes", self.var_mlg_header_bytes, 256, 65536)
|
||||
|
||||
def _build_tab_logging(self, nb):
|
||||
f = self._tab_frame(nb, "Logging")
|
||||
_add_label_check(f, 0, "Enable Logging", self.var_enable_logging)
|
||||
_add_label_spinbox(f, 1, "Log Retention (days)", self.var_log_retention_days, 1, 365)
|
||||
_add_label_check(f, 2, "Colorize console output", self.var_colorize)
|
||||
|
||||
# --- Validation helpers ---
|
||||
|
||||
def _get_int_var(self, var, name, min_val, max_val, default):
|
||||
"""Parse a StringVar as int, clamp to range, return clamped value or None on error."""
|
||||
raw = var.get().strip()
|
||||
try:
|
||||
val = int(raw)
|
||||
except ValueError:
|
||||
messagebox.showerror(
|
||||
"Validation Error",
|
||||
"{} must be an integer (got: {!r}).".format(name, raw),
|
||||
)
|
||||
return None
|
||||
if val < min_val or val > max_val:
|
||||
messagebox.showerror(
|
||||
"Validation Error",
|
||||
"{} must be between {} and {} (got {}).".format(name, min_val, max_val, val),
|
||||
)
|
||||
return None
|
||||
return val
|
||||
|
||||
# --- Save / Cancel ---
|
||||
|
||||
def _on_save(self):
|
||||
# Validate numeric fields before writing
|
||||
checks = [
|
||||
(self.var_api_interval, "API Interval", 30, 3600, 300),
|
||||
(self.var_max_event_age_days, "Max Event Age Days", 1, 3650, 365),
|
||||
(self.var_scan_interval, "Scan Interval", 10, 3600, 300),
|
||||
(self.var_ok_hours, "OK Hours", 1, 168, 12),
|
||||
(self.var_missing_hours, "Missing Hours", 1, 168, 24),
|
||||
(self.var_mlg_header_bytes, "MLG Header Bytes", 256, 65536, 2048),
|
||||
(self.var_log_retention_days, "Log Retention Days", 1, 365, 30),
|
||||
]
|
||||
int_values = {}
|
||||
for var, name, mn, mx, dflt in checks:
|
||||
result = self._get_int_var(var, name, mn, mx, dflt)
|
||||
if result is None:
|
||||
return # validation failed; keep dialog open
|
||||
int_values[name] = result
|
||||
|
||||
# Resolve source_id placeholder
|
||||
source_id = self.var_source_id.get().strip()
|
||||
# Strip placeholder hint if user left it
|
||||
if source_id.startswith("Defaults to hostname"):
|
||||
source_id = ""
|
||||
|
||||
# Resolve api_url placeholder
|
||||
api_url = self.var_api_url.get().strip()
|
||||
if api_url.startswith("http://192.168"):
|
||||
# This is the hint — only keep it if it looks like a real URL
|
||||
pass # leave as-is; user may have typed it intentionally
|
||||
if api_url == "http://192.168.x.x:8000/api/heartbeat":
|
||||
api_url = ""
|
||||
|
||||
values = {
|
||||
"API_ENABLED": "true" if self.var_api_enabled.get() else "false",
|
||||
"API_URL": api_url,
|
||||
"API_INTERVAL_SECONDS": str(int_values["API Interval"]),
|
||||
"SOURCE_ID": source_id,
|
||||
"SOURCE_TYPE": self.var_source_type.get().strip() or "series3_watcher",
|
||||
"SERIES3_PATH": self.var_series3_path.get().strip(),
|
||||
"MAX_EVENT_AGE_DAYS": str(int_values["Max Event Age Days"]),
|
||||
"SCAN_INTERVAL_SECONDS":str(int_values["Scan Interval"]),
|
||||
"OK_HOURS": str(int_values["OK Hours"]),
|
||||
"MISSING_HOURS": str(int_values["Missing Hours"]),
|
||||
"MLG_HEADER_BYTES": str(int_values["MLG Header Bytes"]),
|
||||
"ENABLE_LOGGING": "true" if self.var_enable_logging.get() else "false",
|
||||
"LOG_FILE": self.var_log_file.get().strip(),
|
||||
"LOG_RETENTION_DAYS": str(int_values["Log Retention Days"]),
|
||||
"COLORIZE": "true" if self.var_colorize.get() else "false",
|
||||
}
|
||||
|
||||
try:
|
||||
_save_config(self.config_path, values)
|
||||
except Exception as e:
|
||||
messagebox.showerror("Save Error", "Could not write config.ini:\n{}".format(e))
|
||||
return
|
||||
|
||||
self.saved = True
|
||||
self.root.destroy()
|
||||
|
||||
def _on_cancel(self):
|
||||
self.saved = False
|
||||
self.root.destroy()
|
||||
|
||||
|
||||
# --------------- Public API ---------------
|
||||
|
||||
def show_dialog(config_path, wizard=False):
|
||||
"""
|
||||
Open the settings dialog.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
config_path : str
|
||||
Absolute path to config.ini (read if it exists, written on Save).
|
||||
wizard : bool
|
||||
If True, shows first-run welcome message and "Save & Start" button.
|
||||
|
||||
Returns
|
||||
-------
|
||||
bool
|
||||
True if the user saved, False if they cancelled.
|
||||
"""
|
||||
root = tk.Tk()
|
||||
root.withdraw() # hide blank root window
|
||||
|
||||
# Create a Toplevel that acts as the dialog window
|
||||
top = tk.Toplevel(root)
|
||||
top.deiconify()
|
||||
|
||||
dlg = SettingsDialog(top, config_path, wizard=wizard)
|
||||
|
||||
# Center after build
|
||||
top.update_idletasks()
|
||||
w = top.winfo_reqwidth()
|
||||
h = top.winfo_reqheight()
|
||||
sw = top.winfo_screenwidth()
|
||||
sh = top.winfo_screenheight()
|
||||
x = (sw - w) // 2
|
||||
y = (sh - h) // 2
|
||||
top.geometry("{}x{}+{}+{}".format(w, h, x, y))
|
||||
|
||||
root.wait_window(top)
|
||||
root.destroy()
|
||||
|
||||
return dlg.saved
|
||||
Reference in New Issue
Block a user