feat: rebuild app with Qt UI, installer and safer switch sync

- Replace the Tkinter app with a PySide6 UI: sidebar navigation, central
  profile switcher, autosave, light/dark theme, background tasks with
  progress and cancel, toasts and a filterable activity log
- Split logic into netbox_sync.core (config, NetBox, VMware/Proxmox,
  VM import, switches) and netbox_sync.ui
- Replace the three-dialog import chain with a four-step import wizard;
  support the global VRF and match VMs per cluster
- Expose the previously unreachable VRF/prefix batch tool
- Switch sync: no silent LLDP config changes, TOFU host key checks,
  platform auto-detection, Comware name normalization, fixed AOS-S and
  Comware LLDP parsing, FQDN/management-IP cable matching, dry-run
  preview, interface types only set on create
- Add PyInstaller onedir spec, Inno Setup installer and build.ps1
- Add pytest suite with an in-memory NetBox fake
- Stop tracking the built exe

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-12 15:15:23 +02:00
1 parent e983791baa
commit 4878275f2a
50 files changed
+7960 -3186

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Qt user interface."""
+363
View File
@@ -0,0 +1,363 @@
"""Long-running operations started from the UI. Everything here runs in background tasks."""
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from PySide6.QtCore import QTimer
from netbox_sync.core import netbox
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.netbox import NetBoxError, related_name
from netbox_sync.core.switches import (
PLATFORMS,
describe_snapshot,
discover_switch,
suggest_platform,
sync_snapshot_to_netbox,
)
from netbox_sync.core.virtualization import load_source
from netbox_sync.core.vm_sync import VMSyncEngine
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import SyncPreviewDialog
from netbox_sync.ui.tasks import area_log, logger
def _device_row(device):
primary = getattr(device, "primary_ip", None) or getattr(device, "primary_ip4", None)
address = ""
if primary is not None:
address = str(getattr(primary, "address", None) or (primary.get("address") if isinstance(primary, dict) else ""))
device_type = getattr(device, "device_type", None)
model = related_name(device, "device_type") or getattr(device_type, "model", "") or ""
manufacturer = related_name(device_type, "manufacturer") if device_type is not None else ""
platform = related_name(device, "platform")
site = related_name(device, "site")
tenant = related_name(device, "tenant")
role = related_name(device, "role") or related_name(device, "device_role")
name = str(device.name)
return {
"id": device.id,
"name": name,
"site": site,
"tenant": tenant,
"role": role,
"model": model,
"manufacturer": manufacturer,
"host": address.split("/")[0] if address else "",
"platform": suggest_platform(platform, manufacturer, model),
"label": " · ".join(part for part in (name, site, tenant) if part),
}
class Actions:
def __init__(self, window):
self.window = window
self.state = window.state
self.tasks = window.tasks
# ------------------------------------------------------------------
# helpers
# ------------------------------------------------------------------
def _netbox_params(self):
profile = self.state.profile or {}
return profile.get("netbox_url", ""), profile.get("netbox_token", ""), profile.get("netbox_ignore_ssl", False)
def _connector(self):
"""Return a function for worker threads that yields a connected API object."""
existing = self.state.nb
url, token, ignore_ssl = self._netbox_params()
def get(ctx):
if existing is not None:
return existing
ctx.log(f"Verbinde zu NetBox ({url}) …")
nb = netbox.connect(url, token, ignore_ssl)
area_log("netbox")(f"Verbunden mit NetBox {nb.netbox_version}", "success")
return nb
return get
def _netbox_failed(self, error, title="NetBox-Verbindung fehlgeschlagen"):
if isinstance(error, NetBoxError):
self.state.set_netbox(status="error", message=str(error))
widgets.error(self.window, title, str(error), getattr(error, "traceback_text", None)
if not isinstance(error, NetBoxError) else None)
def require_netbox_config(self):
if self.state.netbox_configured():
return True
if widgets.confirm(self.window, "NetBox ist noch nicht eingerichtet",
"Bitte zuerst URL und API-Token der NetBox-Instanz hinterlegen.",
ok_text="Verbindungen öffnen"):
self.window.navigate("connections")
return False
# ------------------------------------------------------------------
# NetBox
# ------------------------------------------------------------------
def test_netbox(self, on_done=None):
url, token, ignore_ssl = self._netbox_params()
def work(ctx):
ctx.log(f"Teste Verbindung zu {url} …")
return netbox.connect(url, token, ignore_ssl)
def success(nb):
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
logger("netbox").log(25, "Verbindung zu NetBox %s erfolgreich", nb.netbox_version)
self.window.toast(f"Verbindung zu NetBox {nb.netbox_version} erfolgreich")
if on_done:
on_done(True)
def failed(error):
self.state.set_netbox(status="error", message=str(error))
logger("netbox").error("%s", error)
if on_done:
on_done(False)
self.tasks.run(work, title="NetBox-Verbindungstest", area="netbox", on_success=success, on_error=failed)
def load_targets(self, on_done=None):
"""Connect and load clusters, tenants and VRFs (needed by the IPAM tools)."""
if not self.require_netbox_config():
return
connect = self._connector()
def work(ctx):
nb = connect(ctx)
engine = VMSyncEngine(nb, log=area_log("vm"))
engine.load_targets()
return nb, engine
def success(result):
nb, engine = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}", engine)
if on_done:
on_done()
self.tasks.run(work, title="NetBox-Daten laden", area="netbox", on_success=success,
on_error=self._netbox_failed)
# ------------------------------------------------------------------
# Virtual machines
# ------------------------------------------------------------------
def load_vms(self):
if not self.require_netbox_config():
return
sources = [dict(source) for source in self.state.sources if source.get("enabled", True)]
if not sources:
if widgets.confirm(self.window, "Keine aktive Quelle",
"Es ist noch keine aktive VMware- oder Proxmox-Quelle hinterlegt.",
ok_text="Quelle hinzufügen"):
self.window.navigate("connections")
self.window.pages["connections"].add_source()
return
connect = self._connector()
def work(ctx):
nb = connect(ctx)
engine = VMSyncEngine(nb, log=area_log("vm"))
engine.load_targets()
ctx.check_cancelled()
vms, failures = [], []
ctx.progress(0, len(sources), "Lese Quellen …")
with ThreadPoolExecutor(max_workers=min(4, len(sources))) as pool:
futures = {pool.submit(load_source, source, ctx.log): source for source in sources}
for done, future in enumerate(as_completed(futures), start=1):
source = futures[future]
try:
loaded = future.result()
for index, vm in enumerate(loaded):
vm["id"] = f"{source['id']}:{index}:{vm['name']}"
vm["source_id"] = source["id"]
vms.extend(loaded)
ctx.log(f"{source['name']}: {len(loaded)} System(e) geladen", "success")
except Exception as error: # noqa: BLE001
failures.append(f"{source['name']}: {error}")
ctx.log(f"{source['name']}: {error}", "error")
ctx.progress(done, len(sources), source["name"])
vms.sort(key=lambda item: item["name"].casefold())
return nb, engine, vms, failures
def success(result):
nb, engine, vms, failures = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}", engine)
self.state.vms = vms
self.state.vms_loaded_at = time.time()
self.state.vms_changed.emit()
if failures and not vms:
widgets.error(self.window, "Keine VMs geladen", "Keine Quelle konnte gelesen werden.",
"\n".join(failures))
elif failures:
widgets.message(self.window, "Teilweise geladen",
f"{len(vms)} System(e) geladen, {len(failures)} Quelle(n) nicht erreichbar.",
"warning", "\n".join(failures))
else:
self.window.toast(f"{len(vms)} System(e) aus {len(sources)} Quelle(n) geladen")
self.tasks.run(work, title="VMs laden", area="vm", on_success=success, on_error=self._netbox_failed)
# ------------------------------------------------------------------
# Switches
# ------------------------------------------------------------------
def load_devices(self, on_done=None):
if not self.require_netbox_config():
return
connect = self._connector()
def work(ctx):
nb = connect(ctx)
ctx.log("Lade NetBox-Geräte …")
devices = list(nb.dcim.devices.all())
rows = [_device_row(device) for device in devices if getattr(device, "name", None)]
skipped = len(devices) - len(rows)
ctx.log(f"{len(rows)} Geräte geladen" + (f" ({skipped} ohne Namen übersprungen)" if skipped else ""),
"success")
return nb, sorted(rows, key=lambda row: row["name"].casefold())
def success(result):
nb, rows = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
self.state.netbox_devices = rows
if on_done:
on_done(rows)
self.tasks.run(work, title="NetBox-Geräte laden", area="switch", on_success=success,
on_error=self._netbox_failed)
def discover_switches(self, switches):
switches = [dict(switch) for switch in switches if switch.get("enabled", True)]
if not switches:
widgets.message(self.window, "Keine aktiven Switche", "Die ausgewählten Switche sind deaktiviert.", "info")
return
enable_lldp = bool(self.state.settings.get("enable_lldp"))
parallel = max(1, int(self.state.settings.get("parallel_ssh", 4)))
known_hosts = known_hosts_path()
def work(ctx):
snapshots, failures = {}, {}
ctx.progress(0, len(switches), "Verbinde …")
with ThreadPoolExecutor(max_workers=min(parallel, len(switches))) as pool:
futures = {}
for switch in switches:
ctx.log(f"{switch['name']}: lese {switch['host']} aus …")
futures[pool.submit(discover_switch, switch, enable_lldp, known_hosts, ctx.log)] = switch
for done, future in enumerate(as_completed(futures), start=1):
switch = futures[future]
try:
snapshot = future.result()
snapshots[switch["id"]] = snapshot
ctx.log(f"{switch['name']}: {describe_snapshot(snapshot)}", "success")
if snapshot.get("lldp_enabled_automatically"):
ctx.log(f"{switch['name']}: LLDP war deaktiviert und wurde aktiviert", "warning")
elif snapshot.get("lldp_disabled"):
ctx.log(f"{switch['name']}: LLDP ist global deaktiviert – es werden keine Nachbarn "
"erkannt. Bei Bedarf in den Einstellungen „LLDP aktivieren“ erlauben.", "warning")
if not snapshot["interfaces"]:
ctx.log(f"{switch['name']}: keine Schnittstellen erkannt – bitte SSH-Rohdaten prüfen",
"warning")
except Exception as error: # noqa: BLE001
failures[switch["id"]] = str(error)
ctx.log(f"{switch['name']}: {error}", "error")
ctx.progress(done, len(switches), switch["name"])
if ctx.cancelled:
for pending in futures:
pending.cancel()
return snapshots, failures
def success(result):
snapshots, failures = result
by_id = {switch["id"]: switch for switch in self.state.switches}
platform_updates = 0
for switch_id, snapshot in snapshots.items():
self.state.switch_snapshots[switch_id] = snapshot
self.state.switch_status[switch_id] = ("ok", describe_snapshot(snapshot))
stored = by_id.get(switch_id)
if stored and stored.get("platform", "auto") == "auto" and snapshot.get("platform") in PLATFORMS:
stored["platform"] = snapshot["platform"]
platform_updates += 1
for switch_id, problem in failures.items():
self.state.switch_status[switch_id] = ("error", problem)
if platform_updates:
self.state.touch()
self.state.switches_changed.emit()
if failures:
names = {switch["id"]: switch["name"] for switch in switches}
widgets.message(self.window, "Nicht alle Switche ausgelesen",
f"{len(snapshots)} von {len(switches)} Switch(en) erfolgreich ausgelesen.", "warning",
"\n".join(f"{names.get(key, key)}: {value}" for key, value in failures.items()))
else:
self.window.toast(f"{len(snapshots)} Switch(e) ausgelesen")
self.tasks.run(work, title="Switche auslesen", area="switch", on_success=success)
def sync_switches(self, switch_ids, create_cables):
if not self.require_netbox_config():
return
by_id = {switch["id"]: switch for switch in self.state.switches}
items = [(dict(by_id[switch_id]), self.state.switch_snapshots[switch_id])
for switch_id in switch_ids if switch_id in by_id and switch_id in self.state.switch_snapshots]
if not items:
widgets.message(self.window, "Keine Daten", "Bitte die Switche zuerst auslesen.", "info")
return
connect = self._connector()
log = area_log("switch")
def preview(ctx):
nb = connect(ctx)
reports = []
for index, (switch, snapshot) in enumerate(items):
ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: berechne Änderungen …")
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True)))
return nb, reports
def show_preview(result):
nb, reports = result
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}")
def ask():
# Opened after the preview task has fully finished, so the
# follow-up task is not rejected as "still busy".
dialog = SyncPreviewDialog(self.window, reports, create_cables)
if dialog.exec():
self._apply_switch_sync(nb, items, create_cables, log)
QTimer.singleShot(0, ask)
self.tasks.run(preview, title="Änderungen berechnen", area="switch", on_success=show_preview,
on_error=self._netbox_failed)
def _apply_switch_sync(self, nb, items, create_cables, log):
def work(ctx):
reports = []
for index, (switch, snapshot) in enumerate(items):
ctx.check_cancelled()
ctx.progress(index, len(items), switch["name"])
ctx.log(f"{switch['name']}: übertrage nach NetBox …")
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False)
for error in report["errors"]:
ctx.log(f"{switch['name']}: {error}", "error")
reports.append((switch, report))
return reports
def success(reports):
totals = {}
for _switch, report in reports:
for key, value in report.items():
if isinstance(value, int):
totals[key] = totals.get(key, 0) + value
text = (f"{totals.get('interfaces_created', 0)} Interfaces angelegt, "
f"{totals.get('interfaces_updated', 0)} geändert, "
f"{totals.get('ips_created', 0) + totals.get('ips_updated', 0)} IP-Adressen, "
f"{totals.get('cables_created', 0)} Kabel")
log(f"Switch-Synchronisierung: {text}", "success")
errors = [f"{switch['name']}: {error}" for switch, report in reports for error in report["errors"]]
if errors:
widgets.message(self.window, "Mit Problemen abgeschlossen", text + ".", "warning", "\n".join(errors))
else:
self.window.toast(f"NetBox aktualisiert: {text}")
self.tasks.run(work, title="Switche synchronisieren", area="switch", on_success=success)
+91
View File
@@ -0,0 +1,91 @@
"""Application entry point."""
import logging
import sys
import traceback
from logging.handlers import RotatingFileHandler
from PySide6.QtCore import QLibraryInfo, QLocale, Qt, QTranslator
from PySide6.QtGui import QGuiApplication, QIcon
from PySide6.QtWidgets import QApplication
from netbox_sync import APP_NAME, APP_USER_MODEL_ID, APP_VERSION
from netbox_sync.core.config import log_dir
def setup_logging():
from netbox_sync.ui.tasks import QtLogHandler, log_bus
root = logging.getLogger("netbox_sync")
root.setLevel(logging.DEBUG)
root.propagate = False
try:
folder = log_dir()
folder.mkdir(parents=True, exist_ok=True)
file_handler = RotatingFileHandler(folder / "netbox-sync.log", maxBytes=2_000_000, backupCount=5,
encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)s: %(message)s"))
root.addHandler(file_handler)
except OSError:
pass
root.addHandler(QtLogHandler(log_bus))
# Third-party libraries only report problems.
for name in ("paramiko", "urllib3", "pyVmomi"):
logging.getLogger(name).setLevel(logging.WARNING)
logging.getLogger("netbox_sync.app").info("%s %s gestartet", APP_NAME, APP_VERSION)
def install_excepthook(window_getter):
def hook(exc_type, exc, tb):
details = "".join(traceback.format_exception(exc_type, exc, tb))
logging.getLogger("netbox_sync.app").error("Unerwarteter Fehler: %s", exc, exc_info=(exc_type, exc, tb))
from netbox_sync.ui import widgets
try:
widgets.error(window_getter(), "Unerwarteter Fehler",
f"{exc}\n\nDie Anwendung läuft weiter. Details stehen im Protokoll.", details)
except Exception: # noqa: BLE001
sys.__excepthook__(exc_type, exc, tb)
sys.excepthook = hook
def main():
if sys.platform == "win32":
import ctypes
try:
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APP_USER_MODEL_ID)
except (AttributeError, OSError):
pass
QGuiApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
app = QApplication(sys.argv)
app.setApplicationName(APP_NAME)
app.setApplicationDisplayName(APP_NAME)
app.setOrganizationName("NetBox Synchronizer")
app.setApplicationVersion(APP_VERSION)
app.setStyle("Fusion")
translator = QTranslator(app)
if translator.load(QLocale(QLocale.German), "qtbase", "_", QLibraryInfo.path(QLibraryInfo.TranslationsPath)):
app.installTranslator(translator)
from netbox_sync.ui.resources import resource_path
from netbox_sync.ui.theme import base_font, theme
app.setFont(base_font())
app.setWindowIcon(QIcon(str(resource_path("app.ico"))))
setup_logging()
theme.apply("system")
from netbox_sync.ui.main_window import MainWindow
window = MainWindow()
window.apply_theme()
hints = QGuiApplication.styleHints()
if hasattr(hints, "colorSchemeChanged"):
hints.colorSchemeChanged.connect(lambda _scheme: theme.mode == "system" and theme.apply())
install_excepthook(lambda: window)
window.show()
return app.exec()
if __name__ == "__main__":
sys.exit(main())
+619
View File
@@ -0,0 +1,619 @@
"""Modal dialogs for editing connections and reviewing changes."""
import uuid
from PySide6.QtCore import QThreadPool, Qt
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import (
QButtonGroup,
QComboBox,
QDialog,
QFileDialog,
QFormLayout,
QGridLayout,
QHBoxLayout,
QLineEdit,
QPlainTextEdit,
QPushButton,
QSpinBox,
QTabWidget,
QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
)
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.switches import PLATFORMS, forget_host_key
from netbox_sync.core.virtualization import test_source
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.tasks import Task
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import (
Badge,
Banner,
PasswordField,
SearchField,
SearchableComboBox,
Table,
button,
checkbox,
form_dialog_buttons,
label,
repolish,
)
def _mark_invalid(widget, invalid):
widget.setProperty("invalid", bool(invalid))
repolish(widget)
class _Dialog(QDialog):
def __init__(self, parent, title, subtitle=None, width=560):
super().__init__(parent)
self.setWindowTitle(title)
self.setMinimumWidth(width)
self.root = QVBoxLayout(self)
self.root.setContentsMargins(24, 22, 24, 20)
self.root.setSpacing(16)
header = QVBoxLayout()
header.setSpacing(4)
header.addWidget(label(title, object_name="PageTitle"))
if subtitle:
header.addWidget(label(subtitle, muted=True, wrap=True))
self.root.addLayout(header)
self.error_banner = Banner("", "error")
self.error_banner.hide()
def show_error(self, text):
self.error_banner.set(text, "error")
self.error_banner.show()
def ask_text(parent, title, text, default="", validator=None, ok_text="OK"):
dialog = _Dialog(parent, title, text, width=440)
field = QLineEdit(default)
field.selectAll()
dialog.root.addWidget(field)
dialog.root.addWidget(dialog.error_banner)
buttons, _ok = form_dialog_buttons(dialog, ok_text)
dialog.root.addWidget(buttons)
result = {}
def accept():
value = field.text().strip()
problem = "Bitte einen Namen eingeben." if not value else (validator(value) if validator else None)
if problem:
_mark_invalid(field, True)
dialog.show_error(problem)
return
result["value"] = value
QDialog.accept(dialog)
dialog.accept = accept
return result.get("value") if dialog.exec() == QDialog.Accepted else None
# --------------------------------------------------------------------------
# Virtualization source
# --------------------------------------------------------------------------
class SourceDialog(_Dialog):
TEXTS = {
"vmware": {
"endpoint": ("Host / vCenter", "vcenter.example.de oder 192.0.2.10"),
"identity": ("Benutzer", "[email protected]"),
"secret": ("Passwort", ""),
"help": "Ein Benutzer mit Leserechten auf alle VMs genügt.",
},
"proxmox": {
"endpoint": ("Proxmox-URL", "https://pve.example.de:8006"),
"identity": ("API-Token-ID", "benutzer@pve!netbox"),
"secret": ("API-Token-Secret", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"),
"help": "Dem Benutzer und dem API-Token mindestens die Rolle <b>PVEAuditor</b> auf <code>/vms</code> zuweisen.",
},
}
def __init__(self, parent, source=None):
source = source or {}
super().__init__(parent, "Quelle bearbeiten" if source else "Quelle hinzufügen",
"Von hier werden virtuelle Maschinen gelesen. Zugangsdaten werden verschlüsselt gespeichert.")
self.source_id = source.get("id", uuid.uuid4().hex)
self.result = None
self._task = None
type_row = QHBoxLayout()
type_row.setSpacing(8)
self.type_group = QButtonGroup(self)
self.type_buttons = {}
for key, text in (("vmware", "VMware vSphere"), ("proxmox", "Proxmox VE")):
widget = QPushButton(text)
widget.setCheckable(True)
widget.setCursor(Qt.PointingHandCursor)
widget.setMinimumHeight(38)
self.type_group.addButton(widget)
self.type_buttons[key] = widget
type_row.addWidget(widget)
widget.toggled.connect(self._update_type)
self.root.addLayout(type_row)
form = QFormLayout()
form.setHorizontalSpacing(16)
form.setVerticalSpacing(10)
form.setLabelAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.name = QLineEdit(source.get("name", ""))
self.name.setPlaceholderText("z. B. vCenter Rechenzentrum")
self.endpoint = QLineEdit(source.get("host", source.get("url", "")))
self.identity = QLineEdit(source.get("username", source.get("token_id", "")))
self.secret = PasswordField()
self.secret.setText(source.get("password", source.get("token_secret", "")))
self.endpoint_label = label()
self.identity_label = label()
self.secret_label = label()
form.addRow("Anzeigename", self.name)
form.addRow(self.endpoint_label, self.endpoint)
form.addRow(self.identity_label, self.identity)
form.addRow(self.secret_label, self.secret)
self.root.addLayout(form)
self.help = label("", muted=True, wrap=True)
self.help.setTextFormat(Qt.RichText)
self.root.addWidget(self.help)
options = QVBoxLayout()
options.setSpacing(6)
self.enabled = checkbox("Quelle beim Laden berücksichtigen", source.get("enabled", True))
self.ignore_ssl = checkbox("Selbstsigniertes Zertifikat akzeptieren (TLS-Prüfung deaktivieren)",
source.get("ignore_ssl", False))
self.include_lxc = checkbox("LXC-Container mit einlesen", source.get("include_lxc", True))
for widget in (self.enabled, self.ignore_ssl, self.include_lxc):
options.addWidget(widget)
self.root.addLayout(options)
test_row = QHBoxLayout()
self.test_button = button("Verbindung testen", "zap", on_click=self.run_test)
self.test_result = Badge()
test_row.addWidget(self.test_button)
test_row.addWidget(self.test_result)
test_row.addStretch(1)
self.root.addLayout(test_row)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Speichern")
self.root.addWidget(buttons)
self.type_buttons[source.get("type", "vmware")].setChecked(True)
self._update_type()
(self.endpoint if self.name.text() else self.name).setFocus()
@property
def source_type(self):
return "proxmox" if self.type_buttons["proxmox"].isChecked() else "vmware"
def _update_type(self, *_args):
texts = self.TEXTS[self.source_type]
for key, widget, field in (("endpoint", self.endpoint_label, self.endpoint),
("identity", self.identity_label, self.identity),
("secret", self.secret_label, self.secret)):
widget.setText(texts[key][0])
field.setPlaceholderText(texts[key][1])
self.help.setText(texts["help"])
self.include_lxc.setVisible(self.source_type == "proxmox")
for key, widget in self.type_buttons.items():
widget.setProperty("variant", "primary" if key == self.source_type else None)
repolish(widget)
self.test_result.set("")
def collect(self):
fields = {"name": self.name, "endpoint": self.endpoint, "identity": self.identity, "secret": self.secret}
missing = [widget for widget in fields.values() if not widget.text().strip()]
for widget in fields.values():
_mark_invalid(widget, widget in missing)
if missing:
self.show_error("Bitte die markierten Felder ausfüllen.")
missing[0].setFocus()
return None
result = {
"id": self.source_id,
"type": self.source_type,
"name": self.name.text().strip(),
"enabled": self.enabled.isChecked(),
"ignore_ssl": self.ignore_ssl.isChecked(),
}
endpoint = self.endpoint.text().strip()
if self.source_type == "vmware":
result.update({"host": endpoint, "username": self.identity.text().strip(), "password": self.secret.text()})
else:
if not endpoint.startswith(("http://", "https://")):
endpoint = f"https://{endpoint}"
result.update({
"url": endpoint.rstrip("/"), "token_id": self.identity.text().strip(),
"token_secret": self.secret.text().strip(), "include_lxc": self.include_lxc.isChecked(),
})
return result
def run_test(self):
source = self.collect()
if not source:
return
self.error_banner.hide()
self.test_button.setEnabled(False)
self.test_result.set("Teste …", "neutral")
self._task = Task(lambda _ctx: test_source(source), "vm", "Verbindungstest")
self._task.signals.succeeded.connect(lambda text: self.test_result.set(text, "success"))
self._task.signals.failed.connect(self._test_failed)
self._task.signals.finished.connect(lambda: self.test_button.setEnabled(True))
QThreadPool.globalInstance().start(self._task)
def _test_failed(self, error):
self.test_result.set("Fehlgeschlagen", "error")
self.show_error(f"Verbindung fehlgeschlagen: {error}")
def accept(self):
self.result = self.collect()
if self.result:
super().accept()
# --------------------------------------------------------------------------
# Switches
# --------------------------------------------------------------------------
def _platform_combo(current="auto", include_per_device=False):
combo = QComboBox()
if include_per_device:
combo.addItem("Je Gerät vorschlagen (empfohlen)", None)
for key, text in PLATFORMS.items():
combo.addItem(text, key)
combo.setCurrentIndex(max(0, combo.findData(current)))
return combo
class SwitchDialog(_Dialog):
"""Edit one switch access."""
def __init__(self, parent, switch, devices=None):
super().__init__(parent, "Switch bearbeiten", "SSH-Zugang zu einem bestehenden NetBox-Gerät.")
self.switch = switch
self.devices = {item["id"]: item for item in devices or []}
self.result = None
form = QFormLayout()
form.setHorizontalSpacing(16)
form.setVerticalSpacing(10)
if self.devices:
self.device = SearchableComboBox("Gerät suchen …")
self.device.set_items(
[(item["label"], item["id"]) for item in sorted(self.devices.values(), key=lambda d: d["name"].casefold())],
switch.get("device_id"),
)
form.addRow("NetBox-Gerät", self.device)
else:
self.device = None
form.addRow("NetBox-Gerät", label(f"<b>{switch.get('name', '')}</b>"))
self.platform = _platform_combo(switch.get("platform", "auto"))
self.host = QLineEdit(switch.get("host", ""))
self.port = QSpinBox()
self.port.setRange(1, 65535)
self.port.setValue(int(switch.get("port", 22)))
self.username = QLineEdit(switch.get("username", ""))
self.password = PasswordField()
self.password.setText(switch.get("password", ""))
form.addRow("Plattform", self.platform)
form.addRow("Host / IP", self.host)
form.addRow("SSH-Port", self.port)
form.addRow("Benutzer", self.username)
form.addRow("Passwort", self.password)
self.root.addLayout(form)
self.enabled = checkbox("Switch aktiv", switch.get("enabled", True))
self.root.addWidget(self.enabled)
forget = button("Gespeicherten SSH-Hostschlüssel vergessen", "shield", "ghost", on_click=self.forget_key,
tooltip="Nötig, wenn ein Switch ausgetauscht wurde und sich sein Hostschlüssel geändert hat.")
self.root.addWidget(forget, 0, Qt.AlignLeft)
self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self)
self.root.addWidget(buttons)
def forget_key(self):
removed = forget_host_key(known_hosts_path(), self.host.text().strip(), self.port.value())
text = "Hostschlüssel entfernt. Beim nächsten Auslesen wird der neue Schlüssel gespeichert." if removed \
else "Für diesen Host war kein Schlüssel gespeichert."
self.error_banner.set(text, "success" if removed else "info")
self.error_banner.show()
def accept(self):
fields = (self.host, self.username, self.password)
for widget in fields:
_mark_invalid(widget, not widget.text().strip())
device_id = self.device.valid_data() if self.device else self.switch.get("device_id")
if self.device:
_mark_invalid(self.device, device_id is None)
if device_id is None or any(not widget.text().strip() for widget in fields):
self.show_error("Bitte Gerät und alle Zugangsdaten angeben.")
return
result = dict(self.switch)
result.update({
"device_id": device_id,
"name": self.devices[device_id]["name"] if self.devices else self.switch.get("name", ""),
"platform": self.platform.currentData(),
"host": self.host.text().strip(),
"port": self.port.value(),
"username": self.username.text().strip(),
"password": self.password.text(),
"enabled": self.enabled.isChecked(),
})
self.result = result
super().accept()
class AddSwitchesDialog(_Dialog):
"""Pick several NetBox devices at once and give them shared SSH credentials."""
def __init__(self, parent, devices, existing_device_ids):
super().__init__(parent, "Switche hinzufügen",
"Wähle vorhandene NetBox-Geräte aus. Host und Plattform werden aus NetBox vorgeschlagen.",
width=980)
self.resize(1080, 720)
self.result = []
self.rows = [dict(device, added=device["id"] in existing_device_ids) for device in devices]
filters = QHBoxLayout()
filters.setSpacing(8)
self.search = SearchField("Name, Standort, Modell, IP …")
self.tenant = QComboBox()
self.site = QComboBox()
self.role = QComboBox()
for combo, key, everything in ((self.tenant, "tenant", "Alle Mandanten"), (self.site, "site", "Alle Standorte"),
(self.role, "role", "Alle Rollen")):
combo.addItem(everything, None)
for value in sorted({row[key] or "—" for row in self.rows}, key=str.casefold):
combo.addItem(value, value)
combo.setMinimumWidth(160)
self.only_switches = checkbox("Nur Switch-Rollen")
has_switch_role = any("switch" in (row["role"] or "").casefold() for row in self.rows)
self.only_switches.setChecked(has_switch_role)
self.only_switches.setVisible(has_switch_role)
filters.addWidget(self.search, 2)
filters.addWidget(self.tenant, 1)
filters.addWidget(self.site, 1)
filters.addWidget(self.role, 1)
filters.addWidget(self.only_switches)
self.root.addLayout(filters)
columns = [
Column("name", "Gerät", 200),
Column("site", "Standort", 130),
Column("tenant", "Mandant", 130),
Column("role", "Rolle", 120),
Column("model", "Modell", 170),
Column("host", "SSH-Host", 130),
Column("platform", "Plattform", 160, value=lambda row: PLATFORMS[row["platform"]],
color=lambda row: "text_faint" if row["platform"] == "auto" else None),
Column("added", "", 110, value=lambda row: "bereits im Profil" if row["added"] else "",
color=lambda row: "text_faint"),
]
self.model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
self.model.set_rows(self.rows)
self.proxy = FilterProxy(self.model)
self.table = Table(stretch_column=None)
self.table.setModel(self.proxy)
self.table.sortByColumn(0, Qt.AscendingOrder)
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.doubleClicked.connect(self._toggle_row)
self.root.addWidget(self.table, 1)
selection_row = QHBoxLayout()
selection_row.addWidget(button("Alle sichtbaren auswählen", variant="ghost", on_click=self.select_visible))
selection_row.addWidget(button("Auswahl aufheben", variant="ghost", on_click=lambda: self.model.set_checked(
set(self.model.checked), False)))
selection_row.addStretch(1)
self.selection_label = label("", muted=True)
selection_row.addWidget(self.selection_label)
self.root.addLayout(selection_row)
credentials = QWidget()
grid = QGridLayout(credentials)
grid.setContentsMargins(0, 0, 0, 0)
grid.setHorizontalSpacing(12)
grid.setVerticalSpacing(6)
self.username = QLineEdit()
self.username.setPlaceholderText("SSH-Benutzer")
self.password = PasswordField("Passwort")
self.port = QSpinBox()
self.port.setRange(1, 65535)
self.port.setValue(22)
self.platform = _platform_combo(include_per_device=True)
self.platform.setCurrentIndex(0)
for column, (title, widget) in enumerate((("Benutzer", self.username), ("Passwort", self.password),
("SSH-Port", self.port), ("Plattform", self.platform))):
grid.addWidget(label(title, muted=True), 0, column)
grid.addWidget(widget, 1, column)
grid.setColumnStretch(0, 2)
grid.setColumnStretch(1, 2)
grid.setColumnStretch(3, 2)
self.root.addWidget(label("Gemeinsame Zugangsdaten", object_name="CardTitle"))
self.root.addWidget(credentials)
self.root.addWidget(self.error_banner)
buttons, self.ok_button = form_dialog_buttons(self, "Hinzufügen")
self.root.addWidget(buttons)
self.search.textChanged.connect(self.proxy.set_text)
for combo, key in ((self.tenant, "tenant"), (self.site, "site"), (self.role, "role")):
combo.currentIndexChanged.connect(lambda _i, c=combo, k=key: self.proxy.set_predicate(
k, None if c.currentData() is None else (lambda row, v=c.currentData(), k=k: (row[k] or "—") == v)))
self.only_switches.toggled.connect(self._apply_switch_filter)
self._apply_switch_filter(self.only_switches.isChecked())
self.model.checked_changed.connect(self._update_selection)
self._update_selection()
self.search.setFocus()
def _apply_switch_filter(self, enabled):
self.proxy.set_predicate("switch_role", (lambda row: "switch" in (row["role"] or "").casefold()) if enabled else None)
def _toggle_row(self, index):
row = self.proxy.row_at(index)
self.model.set_checked({row["id"]}, row["id"] not in self.model.checked)
def select_visible(self):
self.model.set_checked({row["id"] for row in self.proxy.visible_rows() if not row["added"]})
def _update_selection(self):
count = len(self.model.checked)
self.selection_label.setText(f"{count} Gerät(e) ausgewählt")
self.ok_button.setText(f"{count} Switch(e) hinzufügen" if count else "Hinzufügen")
self.ok_button.setEnabled(count > 0)
def accept(self):
chosen = self.model.checked_rows()
username = self.username.text().strip()
password = self.password.text()
_mark_invalid(self.username, not username)
_mark_invalid(self.password, not password)
if not chosen:
self.show_error("Bitte mindestens ein Gerät auswählen.")
return
if not username or not password:
self.show_error("Bitte Benutzer und Passwort für den SSH-Zugang angeben.")
return
platform = self.platform.currentData()
self.result = [{
"id": uuid.uuid4().hex,
"name": row["name"],
"device_id": row["id"],
"platform": platform or row["platform"],
"host": row["host"] or row["name"],
"port": self.port.value(),
"username": username,
"password": password,
"enabled": True,
} for row in chosen]
super().accept()
# --------------------------------------------------------------------------
# Sync preview and raw data
# --------------------------------------------------------------------------
class SyncPreviewDialog(_Dialog):
def __init__(self, parent, reports, create_cables):
super().__init__(parent, "Änderungen prüfen",
"Diese Änderungen werden in NetBox vorgenommen. Es wurde noch nichts geschrieben.",
width=760)
self.resize(860, 620)
totals = {}
for _switch, report in reports:
for key, value in report.items():
if isinstance(value, int):
totals[key] = totals.get(key, 0) + value
summary = QHBoxLayout()
summary.setSpacing(8)
items = [
(f"{totals.get('interfaces_created', 0)} Interfaces neu", "info"),
(f"{totals.get('interfaces_updated', 0)} Interfaces geändert", "info"),
(f"{totals.get('ips_created', 0) + totals.get('ips_updated', 0)} IP-Adressen", "info"),
]
if create_cables:
items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
errors = sum(len(report["errors"]) for _switch, report in reports)
if errors:
items.append((f"{errors} Probleme", "error"))
for text, kind in items:
summary.addWidget(Badge(text, kind))
summary.addStretch(1)
self.root.addLayout(summary)
tree = QTreeWidget()
tree.setHeaderHidden(True)
tree.setRootIsDecorated(True)
tree.setUniformRowHeights(True)
tree.setAlternatingRowColors(True)
total_changes = 0
for switch, report in reports:
changes = report["changes"]
total_changes += len(changes)
unchanged = report["interfaces_unchanged"]
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"])
top.setIcon(0, icon("network", theme.color("accent")))
font = top.font(0)
font.setBold(True)
top.setFont(0, font)
for error in report["errors"]:
child = QTreeWidgetItem([error])
child.setIcon(0, icon("warning", theme.color("danger")))
top.addChild(child)
for change in changes[:2000]:
top.addChild(QTreeWidgetItem([change]))
tree.addTopLevelItem(top)
top.setExpanded(len(reports) == 1 or bool(report["errors"]))
self.root.addWidget(tree, 1)
if total_changes == 0:
self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success"))
buttons, ok = form_dialog_buttons(self, f"{total_changes} Änderung(en) übernehmen")
ok.setEnabled(total_changes > 0)
self.root.addWidget(buttons)
class RawDataDialog(_Dialog):
SECTIONS = {
"interfaces": "Schnittstellen", "ipv4_interfaces": "IPv4", "ipv6_interfaces": "IPv6",
"neighbors": "LLDP", "cdp_neighbors": "CDP", "lldp_status": "LLDP-Status",
}
def __init__(self, parent, items, selected_id=None):
super().__init__(parent, "SSH-Rohdaten", "Unveränderte Ausgaben der Switch-CLI – hilfreich bei der Fehlersuche.",
width=900)
self.resize(1040, 700)
self.items = items
top = QHBoxLayout()
self.switch_combo = QComboBox()
for switch, _snapshot in items:
self.switch_combo.addItem(f"{switch['name']} ({switch['host']})", switch["id"])
if selected_id:
self.switch_combo.setCurrentIndex(max(0, self.switch_combo.findData(selected_id)))
top.addWidget(self.switch_combo, 1)
top.addWidget(button("Kopieren", "copy", on_click=self.copy_current))
top.addWidget(button("Alles speichern …", "download", on_click=self.save_all))
self.root.addLayout(top)
self.tabs = QTabWidget()
self.editors = {}
for key, title in self.SECTIONS.items():
editor = QPlainTextEdit()
editor.setObjectName("LogView")
editor.setReadOnly(True)
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
self.tabs.addTab(editor, title)
self.editors[key] = editor
self.root.addWidget(self.tabs, 1)
close = button("Schließen", variant="primary", on_click=self.accept)
self.root.addWidget(close, 0, Qt.AlignRight)
self.switch_combo.currentIndexChanged.connect(self.show_switch)
self.show_switch()
def _current(self):
return self.items[max(0, self.switch_combo.currentIndex())]
def show_switch(self, *_args):
_switch, snapshot = self._current()
raw = snapshot.get("raw", {})
for key, editor in self.editors.items():
editor.setPlainText(str(raw.get(key) or "(keine Ausgabe)"))
def copy_current(self):
editor = self.tabs.currentWidget()
QGuiApplication.clipboard().setText(editor.toPlainText())
def save_all(self):
path, _filter = QFileDialog.getSaveFileName(self, "SSH-Rohdaten speichern", "ssh-rohdaten.txt", "Text (*.txt)")
if not path:
return
sections = []
for switch, snapshot in self.items:
sections.append(f"{'=' * 20} {switch['name']} ({switch['host']}) {'=' * 20}")
raw = snapshot.get("raw", {})
for key, title in self.SECTIONS.items():
sections.extend((f"\n--- {title.upper()} ---", str(raw.get(key) or "(keine Ausgabe)")))
with open(path, "w", encoding="utf-8") as stream:
stream.write("\n".join(sections))
+102
View File
@@ -0,0 +1,102 @@
"""Line icons (Lucide, ISC licence) rendered in the current theme colour."""
import tempfile
from functools import lru_cache
from pathlib import Path
from PySide6.QtCore import QByteArray, QRectF, Qt
from PySide6.QtGui import QIcon, QPainter, QPixmap
from PySide6.QtSvg import QSvgRenderer
_PATHS = {
"dashboard": '<rect width="7" height="9" x="3" y="3" rx="1"/><rect width="7" height="5" x="14" y="3" rx="1"/>'
'<rect width="7" height="9" x="14" y="12" rx="1"/><rect width="7" height="5" x="3" y="16" rx="1"/>',
"plug": '<path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/>',
"server": '<rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/>'
'<path d="M6 6h.01"/><path d="M6 18h.01"/>',
"network": '<rect x="16" y="16" width="6" height="6" rx="1"/><rect x="2" y="16" width="6" height="6" rx="1"/>'
'<rect x="9" y="2" width="6" height="6" rx="1"/><path d="M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3"/>'
'<path d="M12 12V8"/>',
"globe": '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
"list": '<path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/>'
'<path d="M3 18h.01"/>',
"settings": '<path d="M21 4h-7"/><path d="M10 4H3"/><path d="M21 12h-9"/><path d="M8 12H3"/><path d="M21 20h-5"/>'
'<path d="M12 20H3"/><path d="M14 2v4"/><path d="M8 10v4"/><path d="M16 18v4"/>',
"plus": '<path d="M5 12h14"/><path d="M12 5v14"/>',
"pencil": '<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/>',
"trash": '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',
"refresh": '<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/>'
'<path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>',
"play": '<polygon points="6 3 20 12 6 21 6 3"/>',
"search": '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',
"check": '<path d="M20 6 9 17l-5-5"/>',
"x": '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
"chevron-down": '<path d="m6 9 6 6 6-6"/>',
"chevron-up": '<path d="m18 15-6-6-6 6"/>',
"chevron-right": '<path d="m9 18 6-6-6-6"/>',
"eye": '<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>',
"eye-off": '<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 '
'13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/>'
'<path d="M2 2l20 20"/>',
"upload": '<path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M12 12v9"/><path d="m16 16-4-4-4 4"/>',
"download": '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>',
"copy": '<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
"folder": '<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 '
'2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/>',
"more": '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',
"warning": '<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/>'
'<path d="M12 17h.01"/>',
"success": '<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>',
"error": '<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',
"info": '<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',
"terminal": '<path d="m4 17 6-6-6-6"/><path d="M12 19h8"/>',
"building": '<path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/>'
'<path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/><path d="M10 6h4"/><path d="M10 10h4"/>'
'<path d="M10 14h4"/><path d="M10 18h4"/>',
"database": '<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/>',
"zap": '<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 '
'.78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>',
"arrow-right": '<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>',
"arrow-left": '<path d="M19 12H5"/><path d="m12 19-7-7 7-7"/>',
"link": '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>'
'<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>',
"stop": '<rect width="14" height="14" x="5" y="5" rx="2"/>',
"shield": '<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 '
'6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>',
"dot": '<circle cx="12" cy="12" r="5" fill="currentColor"/>',
"radio-dot": '<circle cx="12" cy="12" r="5" fill="currentColor" stroke="none"/>',
}
def _svg(name, color, stroke=2.0):
body = _PATHS[name]
return (
f'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" '
f'stroke="{color}" stroke-width="{stroke}" stroke-linecap="round" stroke-linejoin="round">'
f'{body.replace("currentColor", color)}</svg>'
)
@lru_cache(maxsize=512)
def icon(name, color="#475569", stroke=2.0):
renderer = QSvgRenderer(QByteArray(_svg(name, color, stroke).encode("utf-8")))
result = QIcon()
for size in (16, 20, 24, 32, 48, 64):
pixmap = QPixmap(size, size)
pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
painter.setRenderHint(QPainter.Antialiasing)
renderer.render(painter, QRectF(0, 0, size, size))
painter.end()
result.addPixmap(pixmap)
return result
def svg_file(name, color, stroke=2.0):
"""Write an icon to a temp file so that Qt style sheets can reference it."""
folder = Path(tempfile.gettempdir()) / "netbox-synchronizer-theme"
folder.mkdir(parents=True, exist_ok=True)
path = folder / f"{name}-{color.lstrip('#')}-{stroke}.svg"
if not path.exists():
path.write_text(_svg(name, color, stroke), encoding="utf-8")
return path.as_posix()
+637
View File
@@ -0,0 +1,637 @@
"""Step-by-step VM import: target → networks → review → run."""
import ipaddress
import time
from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
QComboBox,
QDialog,
QFormLayout,
QGridLayout,
QHBoxLayout,
QHeaderView,
QLabel,
QLineEdit,
QPlainTextEdit,
QProgressBar,
QStackedWidget,
QTableWidget,
QTableWidgetItem,
QVBoxLayout,
QWidget,
)
from netbox_sync.core.vm_sync import prefix_choices, vrf_label
from netbox_sync.ui.icons import icon
from netbox_sync.ui.tasks import log_bus
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Banner, SearchableComboBox, button, checkbox, hline, label, repolish
NEW_VRF = "__new__"
GLOBAL_VRF = "__global__"
STEPS = ("Ziel", "Netzwerke", "Prüfen", "Import")
def _vrf_items(engine, tenant_id):
items = [(vrf_label(vrf), vrf.id) for vrf in engine.tenant_vrfs(tenant_id)]
items.append(("Global (ohne VRF)", GLOBAL_VRF))
items.append(("➕ Neue VRF anlegen …", NEW_VRF))
return items
class ImportWizard(QDialog):
def __init__(self, parent, state, tasks, vms):
super().__init__(parent)
self.state = state
self.tasks = tasks
self.engine = state.engine
self.vms = vms
self.missing_networks = []
self.network_rows = []
self.plan = None
self.running = False
self.finished_import = False
self.result_summary = None
self._vrf_chosen = False
self.target = None
self.setWindowTitle("VMs nach NetBox importieren")
self.resize(980, 680)
self.setMinimumSize(820, 560)
root = QVBoxLayout(self)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
header = QWidget()
header.setObjectName("Card")
header.setStyleSheet("#Card { border-radius: 0; border-left: none; border-right: none; border-top: none; }")
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(28, 18, 28, 18)
title_box = QVBoxLayout()
title_box.setSpacing(2)
title_box.addWidget(label("VMs nach NetBox importieren", object_name="PageTitle"))
new, existing = self.engine.classify_vms(vms)
title_box.addWidget(label(f"{len(vms)} VM(s) ausgewählt · {new} neu · {existing} bereits in NetBox", muted=True))
header_layout.addLayout(title_box, 1)
self.step_labels = []
for index, title in enumerate(STEPS):
if index:
arrow = QLabel()
arrow.setPixmap(icon("chevron-right", theme.color("text_faint")).pixmap(14, 14))
header_layout.addWidget(arrow)
step = label(f"{index + 1} {title}", object_name="WizardStep")
self.step_labels.append(step)
header_layout.addWidget(step)
root.addWidget(header)
self.pages = QStackedWidget()
self.pages.setObjectName("Pages")
body = QVBoxLayout()
body.setContentsMargins(28, 22, 28, 12)
body.addWidget(self.pages, 1)
root.addLayout(body, 1)
footer = QHBoxLayout()
footer.setContentsMargins(28, 12, 28, 20)
self.back_button = button("Zurück", "arrow-left", on_click=self.go_back)
self.cancel_button = button("Abbrechen", variant="ghost", on_click=self.reject)
self.next_button = button("Weiter", "arrow-right", "primary", on_click=self.go_next)
self.next_button.setLayoutDirection(Qt.RightToLeft)
footer.addWidget(self.cancel_button)
footer.addStretch(1)
footer.addWidget(self.back_button)
footer.addWidget(self.next_button)
root.addLayout(footer)
self.pages.addWidget(self._build_target_page())
self.pages.addWidget(self._build_network_page())
self.pages.addWidget(self._build_review_page())
self.pages.addWidget(self._build_run_page())
self._show_page(0)
# ------------------------------------------------------------------
# Page 1 – target
# ------------------------------------------------------------------
def _build_target_page(self):
page = QWidget()
layout = QVBoxLayout(page)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(16)
layout.addWidget(label("Wohin sollen die VMs?", object_name="CardTitle"))
form = QFormLayout()
form.setHorizontalSpacing(18)
form.setVerticalSpacing(8)
form.setLabelAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.cluster = SearchableComboBox("Cluster suchen …")
self.cluster.set_items(sorted(self.engine.clusters, key=str.casefold))
self.cluster.setMinimumWidth(420)
form.addRow("NetBox-Cluster", self.cluster)
self.tenant = SearchableComboBox("Mandant suchen …")
self.tenant.set_items(sorted(self.engine.tenants, key=str.casefold))
self.tenant_hint = label("", muted=True, wrap=True)
tenant_box = QVBoxLayout()
tenant_box.setSpacing(4)
tenant_box.addWidget(self.tenant)
tenant_box.addWidget(self.tenant_hint)
form.addRow("Mandant", tenant_box)
self.vrf = QComboBox()
self.new_vrf_name = QLineEdit()
self.new_vrf_name.setPlaceholderText("Name der neuen VRF")
vrf_box = QVBoxLayout()
vrf_box.setSpacing(6)
vrf_box.addWidget(self.vrf)
vrf_box.addWidget(self.new_vrf_name)
form.addRow("VRF für IP-Adressen", vrf_box)
layout.addLayout(form)
layout.addWidget(Banner(
"Der Mandant wird an VMs, IP-Adressen und Präfixen gesetzt. Hat der Cluster in NetBox einen Mandanten, "
"ist dieser vorausgewählt.", "info"))
self.target_error = Banner("", "error")
self.target_error.hide()
layout.addWidget(self.target_error)
layout.addStretch(1)
self.cluster.currentIndexChanged.connect(self._cluster_changed)
self.tenant.currentIndexChanged.connect(self._tenant_changed)
self.vrf.currentIndexChanged.connect(self._vrf_changed)
self.vrf.activated.connect(lambda _index: setattr(self, "_vrf_chosen", True))
self.cluster.lineEdit().editingFinished.connect(self._cluster_changed)
self._tenant_changed()
return page
def _cluster_changed(self, *_args):
cluster = self.cluster.valid_data()
if not cluster:
return
inherited = self.engine.cluster_tenants.get(cluster)
if inherited:
self.tenant.select_data(inherited["name"])
self.tenant_hint.setText(f"Vom Cluster „{cluster}“ übernommen.")
else:
self.tenant_hint.setText(f"Der Cluster „{cluster}“ hat keinen Mandanten – bitte auswählen.")
self._tenant_changed()
def _tenant_changed(self, *_args):
tenant = self.tenant.valid_data()
tenant_id = self.engine.tenants.get(tenant) if tenant else None
current = self.vrf.currentData()
self.vrf.blockSignals(True)
self.vrf.clear()
for text, data in _vrf_items(self.engine, tenant_id):
self.vrf.addItem(text, data)
index = self.vrf.findData(current) if self._vrf_chosen else -1
self.vrf.setCurrentIndex(index if index >= 0 else 0)
self.vrf.blockSignals(False)
if tenant and not self.new_vrf_name.isModified():
cluster = self.cluster.valid_data() or "VMs"
self.new_vrf_name.setText(f"{tenant} - {cluster}")
self._vrf_changed()
def _vrf_changed(self, *_args):
self.new_vrf_name.setVisible(self.vrf.currentData() == NEW_VRF)
def _target(self):
cluster = self.cluster.valid_data()
tenant = self.tenant.valid_data()
vrf = self.vrf.currentData()
if not cluster:
return None, "Bitte einen NetBox-Cluster auswählen."
if not tenant:
return None, "Bitte einen Mandanten auswählen."
if vrf == NEW_VRF and not self.new_vrf_name.text().strip():
return None, "Bitte einen Namen für die neue VRF eingeben."
return {
"cluster": cluster,
"cluster_id": self.engine.clusters[cluster],
"tenant": tenant,
"tenant_id": self.engine.tenants[tenant],
"vrf_mode": "new" if vrf == NEW_VRF else ("global" if vrf == GLOBAL_VRF else "existing"),
"vrf_id": vrf if isinstance(vrf, int) else None,
"vrf_name": self.new_vrf_name.text().strip() if vrf == NEW_VRF else self.vrf.currentText(),
}, None
# ------------------------------------------------------------------
# Page 2 – networks
# ------------------------------------------------------------------
def _build_network_page(self):
page = QWidget()
layout = QVBoxLayout(page)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(12)
layout.addWidget(label("Neue Netzwerke", object_name="CardTitle"))
self.network_info = label("", muted=True, wrap=True)
layout.addWidget(self.network_info)
bulk = QHBoxLayout()
bulk.addWidget(label("VRF für alle markierten Netze:", muted=True))
self.bulk_vrf = QComboBox()
self.bulk_vrf.setMinimumWidth(260)
bulk.addWidget(self.bulk_vrf)
bulk.addWidget(button("Übernehmen", on_click=self._apply_bulk_vrf))
bulk.addStretch(1)
self.bulk_row = QWidget()
self.bulk_row.setLayout(bulk)
layout.addWidget(self.bulk_row)
self.network_table = QTableWidget(0, 5)
self.network_table.setHorizontalHeaderLabels(["Anlegen", "Netzwerk", "Größe", "VRF", "Gefunden bei"])
self.network_table.verticalHeader().setVisible(False)
self.network_table.verticalHeader().setDefaultSectionSize(44)
self.network_table.setShowGrid(False)
self.network_table.setAlternatingRowColors(True)
self.network_table.setSelectionMode(QTableWidget.NoSelection)
self.network_table.setFocusPolicy(Qt.NoFocus)
header = self.network_table.horizontalHeader()
header.setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)
header.setSectionResizeMode(0, QHeaderView.Fixed)
header.setSectionResizeMode(4, QHeaderView.Stretch)
self.network_table.setColumnWidth(0, 76)
self.network_table.setColumnWidth(1, 190)
self.network_table.setColumnWidth(2, 90)
self.network_table.setColumnWidth(3, 330)
layout.addWidget(self.network_table, 1)
self.no_networks = Banner("Alle erkannten Netzwerke sind bereits in NetBox vorhanden – es müssen keine "
"Präfixe angelegt werden.", "success")
layout.addWidget(self.no_networks)
self.network_error = Banner("", "error")
self.network_error.hide()
layout.addWidget(self.network_error)
return page
def _fill_networks(self, missing):
target = self.target
self.missing_networks = missing
self.network_rows = []
self.network_table.setRowCount(0)
has_rows = bool(missing)
self.network_table.setVisible(has_rows)
self.bulk_row.setVisible(has_rows)
self.no_networks.setVisible(not has_rows)
self.network_info.setText(
"Für diese IP-Adressen gibt es in NetBox noch kein passendes Präfix. Größe und VRF prüfen; "
"nicht markierte Netze werden nicht angelegt." if has_rows else ""
)
vrf_items = _vrf_items(self.engine, target["tenant_id"])
if target["vrf_mode"] == "new":
vrf_items.insert(0, (f"{target['vrf_name']} (neu)", "__target_new__"))
default = {"new": "__target_new__", "global": GLOBAL_VRF}.get(target["vrf_mode"], target["vrf_id"])
self.bulk_vrf.clear()
for text, data in vrf_items:
self.bulk_vrf.addItem(text, data)
self.bulk_vrf.setCurrentIndex(max(0, self.bulk_vrf.findData(default)))
for row_index, item in enumerate(missing):
self.network_table.insertRow(row_index)
enabled = checkbox("")
enabled.setChecked(True)
holder = QWidget()
holder_layout = QHBoxLayout(holder)
holder_layout.setContentsMargins(18, 0, 0, 0)
holder_layout.addWidget(enabled)
self.network_table.setCellWidget(row_index, 0, holder)
network_item = QTableWidgetItem()
self.network_table.setItem(row_index, 1, network_item)
size = QComboBox()
for length in prefix_choices(item["host_address"], item["detected_prefixlen"]):
size.addItem(f"/{length}", length)
size.setCurrentIndex(max(0, size.findData(item["suggested_prefixlen"])))
self.network_table.setCellWidget(row_index, 2, size)
vrf_widget = QWidget()
vrf_layout = QHBoxLayout(vrf_widget)
vrf_layout.setContentsMargins(0, 3, 6, 3)
vrf_layout.setSpacing(6)
vrf = QComboBox()
for text, data in vrf_items:
vrf.addItem(text, data)
vrf.setCurrentIndex(max(0, vrf.findData(default)))
new_name = QLineEdit(f"{target['tenant']} - {item['suggested_network'].network_address}")
new_name.setPlaceholderText("Name der neuen VRF")
vrf_layout.addWidget(vrf, 1)
vrf_layout.addWidget(new_name, 1)
self.network_table.setCellWidget(row_index, 3, vrf_widget)
vms = sorted(item["vms"], key=str.casefold)
found = QTableWidgetItem(", ".join(vms[:4]) + (f" +{len(vms) - 4}" if len(vms) > 4 else ""))
found.setToolTip("\n".join(vms))
self.network_table.setItem(row_index, 4, found)
row = {"item": item, "enabled": enabled, "size": size, "vrf": vrf, "new_name": new_name,
"network_item": network_item}
self.network_rows.append(row)
size.currentIndexChanged.connect(lambda _i, r=row: self._update_network_row(r))
vrf.currentIndexChanged.connect(lambda _i, r=row: self._update_network_row(r))
enabled.toggled.connect(lambda _c, r=row: self._update_network_row(r))
self._update_network_row(row)
def _update_network_row(self, row):
network = ipaddress.ip_network(f"{row['item']['host_address']}/{row['size'].currentData()}", strict=False)
row["network"] = str(network)
row["network_item"].setText(str(network))
row["new_name"].setVisible(row["vrf"].currentData() == NEW_VRF)
active = row["enabled"].isChecked()
for widget in (row["size"], row["vrf"], row["new_name"]):
widget.setEnabled(active)
def _apply_bulk_vrf(self):
data = self.bulk_vrf.currentData()
for row in self.network_rows:
if row["enabled"].isChecked():
row["vrf"].setCurrentIndex(max(0, row["vrf"].findData(data)))
def _network_plan(self):
decisions = {}
for row in self.network_rows:
if not row["enabled"].isChecked():
continue
data = row["vrf"].currentData()
network = row["network"]
if data == NEW_VRF:
name = row["new_name"].text().strip()
if not name:
return None, f"Bitte für {network} einen VRF-Namen eingeben."
decision = {"network": network, "vrf_id": None, "create_vrf": True, "vrf_name": name}
elif data == "__target_new__":
decision = {"network": network, "vrf_id": None, "create_vrf": True, "vrf_name": self.target["vrf_name"]}
elif data == GLOBAL_VRF:
decision = {"network": network, "vrf_id": None, "create_vrf": False, "vrf_name": None}
else:
decision = {"network": network, "vrf_id": data, "create_vrf": False, "vrf_name": None}
existing = decisions.get(network)
if existing and existing != decision:
return None, f"{network} wurde mehrfach mit unterschiedlichen VRFs ausgewählt."
decisions[network] = decision
return list(decisions.values()), None
# ------------------------------------------------------------------
# Page 3 – review
# ------------------------------------------------------------------
def _build_review_page(self):
page = QWidget()
layout = QVBoxLayout(page)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(14)
layout.addWidget(label("Bitte prüfen", object_name="CardTitle"))
layout.addWidget(label("Mit „Import starten“ werden die folgenden Änderungen in NetBox geschrieben.", muted=True))
self.review_grid = QGridLayout()
self.review_grid.setHorizontalSpacing(24)
self.review_grid.setVerticalSpacing(10)
layout.addLayout(self.review_grid)
layout.addWidget(hline())
self.review_networks = label("", muted=True, wrap=True, selectable=True)
layout.addWidget(self.review_networks)
self.tenant_warning = Banner("", "warning")
layout.addWidget(self.tenant_warning)
layout.addStretch(1)
return page
def _fill_review(self):
while self.review_grid.count():
item = self.review_grid.takeAt(0)
if item.widget():
item.widget().deleteLater()
target = self.target
new, existing = self.engine.classify_vms(self.vms)
vrf_text = {"new": f"{target['vrf_name']} (wird angelegt)", "global": "Global (ohne VRF)"}.get(
target["vrf_mode"], target["vrf_name"])
new_vrfs = sorted({decision["vrf_name"] for decision in self.plan if decision.get("create_vrf")}
- {target["vrf_name"] if target["vrf_mode"] == "new" else None})
rows = [
("Cluster", target["cluster"]),
("Mandant", target["tenant"]),
("Standard-VRF", vrf_text),
("Virtuelle Maschinen", f"{len(self.vms)} gesamt · {new} werden angelegt · {existing} aktualisiert"),
("Neue Präfixe", str(len(self.plan)) if self.plan else "keine"),
]
if new_vrfs:
rows.append(("Zusätzliche neue VRFs", ", ".join(new_vrfs)))
for index, (key, value) in enumerate(rows):
key_label = label(key, object_name="SummaryKey")
value_label = label(value, object_name="SummaryValue", wrap=True, selectable=True)
self.review_grid.addWidget(key_label, index, 0, Qt.AlignTop)
self.review_grid.addWidget(value_label, index, 1)
self.review_grid.setColumnStretch(1, 1)
if self.plan:
networks = ", ".join(f"{decision['network']}" for decision in self.plan[:12])
more = f" und {len(self.plan) - 12} weitere" if len(self.plan) > 12 else ""
self.review_networks.setText(f"Neue Präfixe: {networks}{more}")
else:
self.review_networks.setText("Es werden keine neuen Präfixe angelegt.")
inherited = self.engine.cluster_tenants.get(target["cluster"], {}).get("name")
if inherited and inherited != target["tenant"]:
self.tenant_warning.set(
f"Achtung: Der Cluster gehört in NetBox zum Mandanten <b>{inherited}</b>, "
f"importiert wird aber für <b>{target['tenant']}</b>.", "warning")
self.tenant_warning.show()
else:
self.tenant_warning.hide()
# ------------------------------------------------------------------
# Page 4 – run
# ------------------------------------------------------------------
def _build_run_page(self):
page = QWidget()
layout = QVBoxLayout(page)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(12)
self.run_title = label("Import läuft …", object_name="CardTitle")
layout.addWidget(self.run_title)
self.run_status = label("", muted=True)
layout.addWidget(self.run_status)
self.run_progress = QProgressBar()
layout.addWidget(self.run_progress)
self.run_log = QPlainTextEdit()
self.run_log.setObjectName("LogView")
self.run_log.setReadOnly(True)
layout.addWidget(self.run_log, 1)
self.run_result = Banner("", "success")
self.run_result.hide()
layout.addWidget(self.run_result)
return page
def _append_log(self, entry):
if not self.running or entry.area != "vm" or entry.level == "debug":
return
stamp = time.strftime("%H:%M:%S", time.localtime(entry.timestamp))
prefix = {"warning": "⚠ ", "error": "✖ ", "success": "✔ "}.get(entry.level, " ")
self.run_log.appendPlainText(f"{stamp} {prefix}{entry.text}")
def _start_import(self):
target = self.target
plan = self.plan
vms = list(self.vms)
engine = self.engine
self.running = True
log_bus.entry.connect(self._append_log)
self.run_progress.setRange(0, len(vms))
self.run_progress.setValue(0)
def work(ctx):
vrf_id = target["vrf_id"]
if target["vrf_mode"] == "new":
vrf_id = engine.get_or_create_tenant_vrf(target["vrf_name"], target["tenant_id"])
for decision in plan:
if decision.get("create_vrf") and decision["vrf_name"] == target["vrf_name"] and vrf_id:
decision.update(vrf_id=vrf_id, create_vrf=False)
engine.apply_network_plan(plan, target["tenant_id"])
results = {"created": 0, "updated": 0, "failed": []}
for index, vm in enumerate(vms):
if ctx.cancelled:
results["cancelled"] = True
break
ctx.progress(index, len(vms), vm["name"])
try:
outcome = engine.sync_vm(vm, target["cluster_id"], target["tenant_id"], vrf_id)
results[outcome] += 1
except Exception as error: # noqa: BLE001
results["failed"].append(f"{vm['name']}: {error}")
ctx.log(f"{vm['name']}: {error}", "error")
ctx.progress(len(vms), len(vms), "")
return results
self.tasks.run(work, title="VM-Import", area="vm", on_success=self._import_done,
on_error=self._import_failed, on_progress=self._import_progress, on_finished=self._import_finished)
def _import_progress(self, value, maximum, text):
self.run_progress.setMaximum(max(1, maximum))
self.run_progress.setValue(value)
self.run_status.setText(f"{value} von {maximum} · {text}" if text else f"{value} von {maximum}")
def _import_done(self, results):
failed = results["failed"]
summary = f"{results['created']} VM(s) angelegt, {results['updated']} aktualisiert"
if results.get("cancelled"):
self.run_title.setText("Import abgebrochen")
self.run_result.set(summary + ". Der Import wurde nach der laufenden VM beendet.", "warning")
elif failed:
self.run_title.setText("Import mit Fehlern abgeschlossen")
self.run_result.set(summary + f", <b>{len(failed)} fehlgeschlagen</b>:<br>" + "<br>".join(failed[:8]), "warning")
else:
self.run_title.setText("Import abgeschlossen")
self.run_result.set(summary + ".", "success")
self.run_result.show()
self.state.vms_changed.emit()
self.result_summary = (summary, "warning" if failed else "success")
def _import_failed(self, error):
self.run_title.setText("Import fehlgeschlagen")
self.run_result.set(str(error), "error")
self.run_result.show()
def _import_finished(self):
self.running = False
self.finished_import = True
try:
log_bus.entry.disconnect(self._append_log)
except (RuntimeError, TypeError):
pass
self.next_button.setText("Fertig")
self.next_button.setIcon(icon("check", "#FFFFFF"))
self.next_button.setEnabled(True)
self.cancel_button.hide()
# ------------------------------------------------------------------
# Navigation
# ------------------------------------------------------------------
def _show_page(self, index):
self.pages.setCurrentIndex(index)
for step, widget in enumerate(self.step_labels):
widget.setProperty("active", step == index)
widget.setProperty("done", step < index)
repolish(widget)
self.back_button.setVisible(0 < index < 3)
self.next_button.setText({2: "Import starten", 3: "Abbrechen"}.get(index, "Weiter"))
self.next_button.setIcon(icon({2: "play", 3: "stop"}.get(index, "arrow-right"), "#FFFFFF"))
self.next_button.setLayoutDirection(Qt.LeftToRight if index >= 2 else Qt.RightToLeft)
self.cancel_button.setVisible(index < 3)
def go_back(self):
index = self.pages.currentIndex()
if index == 2 and not self.missing_networks:
index = 1
self._show_page(max(0, index - 1))
def go_next(self):
index = self.pages.currentIndex()
if index == 0:
target, problem = self._target()
if problem:
self.target_error.set(problem, "error")
self.target_error.show()
return
self.target_error.hide()
self.target = target
self._detect_networks()
elif index == 1:
plan, problem = self._network_plan()
if problem:
self.network_error.set(problem, "error")
self.network_error.show()
return
self.network_error.hide()
self.plan = plan
self._fill_review()
self._show_page(2)
elif index == 2:
self._show_page(3)
self._start_import()
elif index == 3:
if self.finished_import:
self.accept()
else:
self.tasks.cancel()
self.next_button.setEnabled(False)
self.run_status.setText("Wird nach der aktuellen VM beendet …")
def _detect_networks(self):
target = self.target
engine = self.engine
vms = list(self.vms)
# A VRF that does not exist yet cannot contain prefixes; -1 keeps global
# prefixes from being mistaken for prefixes of the new VRF.
default_vrf = -1 if target["vrf_mode"] == "new" else target["vrf_id"]
self.next_button.setEnabled(False)
self.next_button.setText("Prüfe Netzwerke …")
def work(_ctx):
return engine.detect_missing_networks(vms, target["tenant_id"], default_vrf)
def done(missing):
self._fill_networks(missing)
if missing:
self._show_page(1)
else:
self.plan = []
self._fill_review()
self._show_page(2)
def failed(error):
self.target_error.set(f"Netzwerkprüfung fehlgeschlagen: {error}", "error")
self.target_error.show()
self._show_page(0)
def finished():
self.next_button.setEnabled(True)
if self.pages.currentIndex() == 0:
self._show_page(0)
self.tasks.run(work, title="Netzwerkprüfung", area="vm", on_success=done, on_error=failed,
on_finished=finished, cancellable=False)
def reject(self):
if self.running:
return
super().reject()
def closeEvent(self, event):
if self.running:
event.ignore()
return
super().closeEvent(event)
+418
View File
@@ -0,0 +1,418 @@
"""Main window: sidebar navigation, profile switcher, pages and status bar."""
from PySide6.QtCore import QSettings, QSize, Qt
from PySide6.QtGui import QAction, QKeySequence, QPixmap, QShortcut
from PySide6.QtWidgets import (
QButtonGroup,
QComboBox,
QFrame,
QHBoxLayout,
QLabel,
QMainWindow,
QMenu,
QProgressBar,
QPushButton,
QStackedWidget,
QToolButton,
QVBoxLayout,
QWidget,
)
from netbox_sync import APP_NAME, APP_VERSION
from netbox_sync.ui import widgets
from netbox_sync.ui.actions import Actions
from netbox_sync.ui.dialogs import ask_text
from netbox_sync.ui.icons import icon
from netbox_sync.ui.pages.connections import ConnectionsPage
from netbox_sync.ui.pages.ipam import IpamPage
from netbox_sync.ui.pages.log import LogPage
from netbox_sync.ui.pages.overview import OverviewPage
from netbox_sync.ui.pages.settings import SettingsPage
from netbox_sync.ui.pages.switches import SwitchesPage
from netbox_sync.ui.pages.vms import VMsPage
from netbox_sync.ui.resources import resource_path
from netbox_sync.ui.state import AppState
from netbox_sync.ui.tasks import TaskManager, log_bus
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Badge, Toast, button, label
NAVIGATION = (
("overview", "Übersicht", "dashboard"),
("connections", "Verbindungen", "plug"),
("vms", "Virtuelle Maschinen", "server"),
("switches", "Switche", "network"),
("ipam", "VRFs && Netze", "globe"),
("log", "Protokoll", "list"),
)
class NavButton(QPushButton):
def __init__(self, text, icon_name):
super().__init__(text)
self.setProperty("nav", True)
self.setCheckable(True)
self.setCursor(Qt.PointingHandCursor)
self.setIconSize(QSize(18, 18))
self.icon_name = icon_name
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 10, 0)
layout.addStretch(1)
self.badge = Badge("", "error")
self.badge.hide()
layout.addWidget(self.badge)
self.toggled.connect(self.update_icon)
self.update_icon()
def update_icon(self, *_args):
color = "#FFFFFF" if self.isChecked() else theme.color("sidebar_text")
self.setIcon(icon(self.icon_name, color))
def set_badge(self, count):
self.badge.set(str(count) if count else "", "error")
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle(APP_NAME)
self.setMinimumSize(1080, 700)
self.state = AppState()
self.tasks = TaskManager()
self.actions = Actions(self)
self.pages = {}
self.nav_buttons = {}
self.unseen_errors = 0
central = QWidget()
root = QHBoxLayout(central)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
root.addWidget(self._build_sidebar())
right = QVBoxLayout()
right.setContentsMargins(0, 0, 0, 0)
right.setSpacing(0)
self.stack = QStackedWidget()
self.stack.setObjectName("Pages")
right.addWidget(self.stack, 1)
right.addWidget(self._build_status_bar())
root.addLayout(right, 1)
self.setCentralWidget(central)
self.toast_widget = Toast(central)
for key, page_class in (("overview", OverviewPage), ("connections", ConnectionsPage), ("vms", VMsPage),
("switches", SwitchesPage), ("ipam", IpamPage), ("log", LogPage),
("settings", SettingsPage)):
page = page_class(self)
self.pages[key] = page
self.stack.addWidget(page)
self.tasks.busy_changed.connect(self._busy_changed)
self.tasks.progress.connect(self._progress)
self.tasks.started.connect(lambda title: self.task_label.setText(title + " …"))
log_bus.entry.connect(self._log_entry)
self.state.profiles_changed.connect(self._refresh_profiles)
self.state.profile_switched.connect(self._refresh_profiles)
self.state.netbox_changed.connect(self._refresh_netbox_pill)
self.state.profile_edited.connect(self._refresh_netbox_pill)
self.state.save_failed.connect(lambda text: self.toast(f"Speichern fehlgeschlagen: {text}", "error", 8000))
theme.changed.connect(self._theme_changed)
for index, (key, _title, _icon) in enumerate((*NAVIGATION, ("settings", "", ""))):
QShortcut(QKeySequence(f"Ctrl+{index + 1}"), self, activated=lambda k=key: self.navigate(k))
QShortcut(QKeySequence("F5"), self, activated=self._reload_current)
QShortcut(QKeySequence("Ctrl+F"), self, activated=self._focus_search)
self._restore_geometry()
self.state.load()
self.navigate("overview" if self.state.profile is None or not self.state.netbox_configured() else "vms")
self._busy_changed(False)
# ------------------------------------------------------------------
# Layout
# ------------------------------------------------------------------
def _build_sidebar(self):
sidebar = QFrame()
sidebar.setObjectName("Sidebar")
sidebar.setFixedWidth(250)
layout = QVBoxLayout(sidebar)
layout.setContentsMargins(14, 18, 14, 14)
layout.setSpacing(4)
brand = QHBoxLayout()
brand.setSpacing(10)
logo = QLabel()
logo.setPixmap(QPixmap(str(resource_path("app.png"))).scaled(
34, 34, Qt.KeepAspectRatio, Qt.SmoothTransformation))
logo.setStyleSheet("background: #FFFFFF; border-radius: 9px; padding: 3px;")
logo.setFixedSize(40, 40)
logo.setAlignment(Qt.AlignCenter)
brand.addWidget(logo)
titles = QVBoxLayout()
titles.setSpacing(0)
titles.addWidget(label("NetBox Synchronizer", object_name="AppTitle"))
titles.addWidget(label("VMs & Switche → NetBox", object_name="AppSubtitle"))
brand.addLayout(titles, 1)
layout.addLayout(brand)
layout.addSpacing(22)
layout.addWidget(label("KUNDENPROFIL", object_name="SectionLabel"))
profile_row = QHBoxLayout()
profile_row.setSpacing(6)
self.profile_combo = QComboBox()
self.profile_combo.setMinimumHeight(34)
self.profile_combo.currentTextChanged.connect(self._profile_selected)
profile_row.addWidget(self.profile_combo, 1)
self.profile_menu_button = QToolButton()
self.profile_menu_button.setIcon(icon("more", "#B6C3D6"))
self.profile_menu_button.setToolTip("Profil verwalten")
self.profile_menu_button.setFixedSize(34, 34)
self.profile_menu_button.setPopupMode(QToolButton.InstantPopup)
self.profile_menu_button.setCursor(Qt.PointingHandCursor)
menu = QMenu(self)
self.profile_actions = {
"new": QAction("Neues Profil …", self, triggered=self.new_profile),
"duplicate": QAction("Duplizieren …", self, triggered=self.duplicate_profile),
"rename": QAction("Umbenennen …", self, triggered=self.rename_profile),
"delete": QAction("Löschen …", self, triggered=self.delete_profile),
}
menu.addAction(self.profile_actions["new"])
menu.addAction(self.profile_actions["duplicate"])
menu.addAction(self.profile_actions["rename"])
menu.addSeparator()
menu.addAction(self.profile_actions["delete"])
self.profile_menu = menu
self.profile_menu_button.setMenu(menu)
profile_row.addWidget(self.profile_menu_button)
layout.addLayout(profile_row)
layout.addSpacing(20)
self.nav_group = QButtonGroup(self)
self.nav_group.setExclusive(True)
for key, text, icon_name in NAVIGATION:
nav = NavButton(text, icon_name)
nav.clicked.connect(lambda _checked=False, k=key: self.navigate(k))
self.nav_group.addButton(nav)
self.nav_buttons[key] = nav
layout.addWidget(nav)
layout.addStretch(1)
settings = NavButton("Einstellungen", "settings")
settings.clicked.connect(lambda: self.navigate("settings"))
self.nav_group.addButton(settings)
self.nav_buttons["settings"] = settings
layout.addWidget(settings)
layout.addSpacing(6)
layout.addWidget(label(f"Version {APP_VERSION}", object_name="VersionLabel"))
return sidebar
def _build_status_bar(self):
bar = QFrame()
bar.setObjectName("StatusBar")
bar.setFixedHeight(38)
layout = QHBoxLayout(bar)
layout.setContentsMargins(16, 0, 10, 0)
layout.setSpacing(10)
self.status_icon = QLabel()
self.status_icon.setFixedSize(14, 14)
layout.addWidget(self.status_icon)
self.status_message = QLabel("Bereit")
self.status_message.setMinimumWidth(200)
layout.addWidget(self.status_message, 1)
self.task_label = QLabel("")
layout.addWidget(self.task_label)
self.progress_bar = QProgressBar()
self.progress_bar.setFixedWidth(180)
layout.addWidget(self.progress_bar)
self.cancel_button = button("Abbrechen", "stop", "ghost", on_click=self._cancel_task)
layout.addWidget(self.cancel_button)
self.netbox_pill = Badge("", "neutral")
self.netbox_pill.setCursor(Qt.PointingHandCursor)
self.netbox_pill.mousePressEvent = lambda _event: self.navigate("connections")
layout.addWidget(self.netbox_pill)
return bar
# ------------------------------------------------------------------
# Navigation & feedback
# ------------------------------------------------------------------
def navigate(self, key):
page = self.pages[key]
self.stack.setCurrentWidget(page)
self.nav_buttons[key].setChecked(True)
for nav in self.nav_buttons.values():
nav.update_icon()
if key == "log":
self.unseen_errors = 0
self.nav_buttons["log"].set_badge(0)
page.on_show()
def current_page(self):
return self.stack.currentWidget()
def toast(self, text, kind="success", duration=4500):
self.toast_widget.show_message(text, kind, duration)
def _reload_current(self):
page = self.current_page()
if page is self.pages["vms"] and not self.tasks.busy:
page.load()
elif page is self.pages["switches"] and not self.tasks.busy:
page.discover()
def _focus_search(self):
search = getattr(self.current_page(), "search", None)
if search is not None:
search.setFocus()
search.selectAll()
def _log_entry(self, entry):
if entry.level == "debug":
return
tokens = {"error": "danger", "warning": "warning", "success": "success"}
self.status_icon.setPixmap(icon({"error": "error", "warning": "warning", "success": "success"}.get(
entry.level, "info"), theme.color(tokens.get(entry.level, "text_faint"))).pixmap(14, 14))
metrics = self.status_message.fontMetrics()
self.status_message.setText(metrics.elidedText(entry.text, Qt.ElideRight, max(200, self.status_message.width())))
self.status_message.setToolTip(entry.text)
if entry.level == "error" and self.current_page() is not self.pages["log"]:
self.unseen_errors += 1
self.nav_buttons["log"].set_badge(self.unseen_errors)
def _busy_changed(self, busy):
self.progress_bar.setVisible(busy)
self.cancel_button.setVisible(busy and getattr(self.tasks.current, "cancellable", False))
self.cancel_button.setEnabled(True)
self.task_label.setVisible(busy)
if busy:
self.progress_bar.setRange(0, 0)
for page in self.pages.values():
page.set_busy(busy)
for action in self.profile_actions.values():
action.setEnabled(not busy)
self.profile_combo.setEnabled(not busy)
def _progress(self, value, maximum, text):
if maximum:
self.progress_bar.setRange(0, maximum)
self.progress_bar.setValue(value)
if self.tasks.current:
suffix = f" ({value}/{maximum})" if maximum else ""
self.task_label.setText(f"{self.tasks.current.title}{suffix}")
def _cancel_task(self):
self.tasks.cancel()
self.cancel_button.setEnabled(False)
self.task_label.setText("Wird abgebrochen …")
def _refresh_netbox_pill(self):
if self.state.profile is None or not self.state.netbox_configured():
self.netbox_pill.set("NetBox: nicht eingerichtet", "warning")
elif self.state.netbox_status == "ok":
self.netbox_pill.set(f"NetBox {self.state.netbox_version} · verbunden", "success")
elif self.state.netbox_status == "error":
self.netbox_pill.set("NetBox: Fehler", "error")
self.netbox_pill.setToolTip(self.state.netbox_message)
else:
self.netbox_pill.set("NetBox: nicht verbunden", "neutral")
def apply_theme(self):
theme.apply(self.state.settings.get("theme", "system"))
def _theme_changed(self):
for nav in self.nav_buttons.values():
nav.update_icon()
# ------------------------------------------------------------------
# Profiles
# ------------------------------------------------------------------
def _refresh_profiles(self):
names = self.state.profile_names()
self.profile_combo.blockSignals(True)
self.profile_combo.clear()
self.profile_combo.addItems(names)
if not names:
self.profile_combo.setPlaceholderText("Kein Profil")
self.profile_combo.setCurrentText(self.state.active)
self.profile_combo.blockSignals(False)
has_profile = self.state.profile is not None
for key in ("duplicate", "rename", "delete"):
self.profile_actions[key].setEnabled(has_profile)
for key in ("connections", "vms", "switches", "ipam"):
self.nav_buttons[key].setEnabled(has_profile)
self.setWindowTitle(f"{self.state.active} – {APP_NAME}" if has_profile else APP_NAME)
self._refresh_netbox_pill()
def _profile_selected(self, name):
if name and name != self.state.active:
self.state.switch_profile(name)
self.toast(f"Profil „{name}“ geöffnet", "info", 2500)
def _validate_name(self, current=None):
def check(value):
if value != current and value in self.state.profiles:
return "Ein Profil mit diesem Namen existiert bereits."
return None
return check
def new_profile(self):
name = ask_text(self, "Neues Kundenprofil", "Name des Kunden oder der Umgebung, z. B. „Muster GmbH“.",
validator=self._validate_name(), ok_text="Anlegen")
if name:
self.state.create_profile(name)
self.navigate("connections")
self.toast(f"Profil „{name}“ angelegt – jetzt NetBox-Zugang eintragen", "info")
def duplicate_profile(self):
source = self.state.active
if not source:
return
name = ask_text(self, "Profil duplizieren", f"Kopie von „{source}“ inklusive aller Zugänge anlegen.",
f"{source} (Kopie)", validator=self._validate_name(), ok_text="Duplizieren")
if name:
self.state.create_profile(name, copy_from=source)
def rename_profile(self):
current = self.state.active
if not current:
return
name = ask_text(self, "Profil umbenennen", "Neuer Name für das Kundenprofil.", current,
validator=self._validate_name(current), ok_text="Umbenennen")
if name and name != current:
self.state.rename_profile(current, name)
def delete_profile(self):
name = self.state.active
if name and widgets.confirm(self, "Profil löschen",
f"Kundenprofil „{name}“ mit allen gespeicherten Zugängen endgültig löschen?",
ok_text="Löschen", destructive=True):
self.state.delete_profile(name)
self.toast(f"Profil „{name}“ gelöscht", "info")
# ------------------------------------------------------------------
# Window state
# ------------------------------------------------------------------
def _restore_geometry(self):
settings = QSettings()
geometry = settings.value("window/geometry")
if geometry is not None:
self.restoreGeometry(geometry)
else:
self.resize(1320, 860)
def resizeEvent(self, event):
super().resizeEvent(event)
if self.toast_widget.isVisible():
self.toast_widget.reposition()
def closeEvent(self, event):
if self.tasks.busy and not widgets.confirm(
self, "Vorgang läuft noch", f"„{self.tasks.current.title}“ ist noch nicht abgeschlossen. "
"Trotzdem beenden?", ok_text="Beenden", destructive=True):
event.ignore()
return
self.tasks.cancel()
self.state.save_now()
QSettings().setValue("window/geometry", self.saveGeometry())
super().closeEvent(event)
+185
View File
@@ -0,0 +1,185 @@
"""Table models with check boxes, natural sorting and multi-criteria filtering."""
import re
from dataclasses import dataclass, field
from typing import Any, Callable
from PySide6.QtCore import QAbstractTableModel, QModelIndex, QSortFilterProxyModel, Qt, Signal
from PySide6.QtGui import QColor
from netbox_sync.ui.icons import icon
from netbox_sync.ui.theme import theme
SORT_ROLE = Qt.UserRole + 1
ROW_ROLE = Qt.UserRole + 2
def natural_key(value):
"""Sort key Qt can compare: numbers stay numbers, text gets zero-padded digits (1/1/2 < 1/1/10)."""
if value is None or value == "":
return ""
if isinstance(value, bool):
return int(value)
if isinstance(value, (int, float)):
return float(value)
return re.sub(r"\d+", lambda match: match.group(0).zfill(12), str(value).casefold())
@dataclass
class Column:
key: str
title: str
width: int = 120
align: str = "left"
value: Callable[[dict], Any] = None
color: Callable[[dict], str] = None # theme token
dot: Callable[[dict], str] = None # theme token for a status dot
tooltip: Callable[[dict], str] = None
sort: Callable[[dict], Any] = None
extra: dict = field(default_factory=dict)
def display(self, row):
return self.value(row) if self.value else row.get(self.key, "")
class RowTableModel(QAbstractTableModel):
"""List-of-dicts model. With ``checkable`` the first column gets a check box."""
checked_changed = Signal()
def __init__(self, columns, checkable=False, row_id=lambda row: id(row)):
super().__init__()
self.columns = columns
self.checkable = checkable
self.row_id = row_id
self.rows = []
self.checked = set()
theme.changed.connect(self._repaint)
def _repaint(self):
if self.rows:
self.dataChanged.emit(self.index(0, 0), self.index(len(self.rows) - 1, len(self.columns) - 1))
def set_rows(self, rows, keep_checked=True):
self.beginResetModel()
self.rows = list(rows)
valid = {self.row_id(row) for row in self.rows}
self.checked = (self.checked & valid) if keep_checked else set()
self.endResetModel()
self.checked_changed.emit()
def refresh(self):
self._repaint()
def rowCount(self, parent=QModelIndex()):
return 0 if parent.isValid() else len(self.rows)
def columnCount(self, parent=QModelIndex()):
return 0 if parent.isValid() else len(self.columns)
def headerData(self, section, orientation, role=Qt.DisplayRole):
if orientation != Qt.Horizontal:
return None
column = self.columns[section]
if role == Qt.DisplayRole:
return column.title
if role == Qt.TextAlignmentRole:
return (Qt.AlignRight if column.align == "right" else Qt.AlignLeft) | Qt.AlignVCenter
return None
def flags(self, index):
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if self.checkable and index.column() == 0:
flags |= Qt.ItemIsUserCheckable
return flags
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return None
row = self.rows[index.row()]
column = self.columns[index.column()]
if role == Qt.DisplayRole:
value = column.display(row)
return "" if value is None else str(value)
if role == SORT_ROLE:
return natural_key(column.sort(row) if column.sort else column.display(row))
if role == ROW_ROLE:
return row
if role == Qt.CheckStateRole and self.checkable and index.column() == 0:
return Qt.Checked if self.row_id(row) in self.checked else Qt.Unchecked
if role == Qt.TextAlignmentRole:
return (Qt.AlignRight if column.align == "right" else Qt.AlignLeft) | Qt.AlignVCenter
if role == Qt.ForegroundRole and column.color:
token = column.color(row)
return QColor(theme.color(token)) if token else None
if role == Qt.DecorationRole and column.dot:
token = column.dot(row)
return icon("dot", theme.color(token)) if token else None
if role == Qt.ToolTipRole and column.tooltip:
return column.tooltip(row)
return None
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.CheckStateRole and self.checkable and index.column() == 0:
row_id = self.row_id(self.rows[index.row()])
if Qt.CheckState(value) == Qt.Checked:
self.checked.add(row_id)
else:
self.checked.discard(row_id)
self.dataChanged.emit(index, index, [Qt.CheckStateRole])
self.checked_changed.emit()
return True
return False
def set_checked(self, row_ids, checked=True):
row_ids = set(row_ids)
if checked:
self.checked |= row_ids
else:
self.checked -= row_ids
if self.rows:
self.dataChanged.emit(self.index(0, 0), self.index(len(self.rows) - 1, 0), [Qt.CheckStateRole])
self.checked_changed.emit()
def checked_rows(self):
return [row for row in self.rows if self.row_id(row) in self.checked]
class FilterProxy(QSortFilterProxyModel):
"""Free-text search across all columns plus arbitrary row predicates."""
def __init__(self, source):
super().__init__()
self.setSourceModel(source)
self.setSortRole(SORT_ROLE)
self.setFilterCaseSensitivity(Qt.CaseInsensitive)
self.text = ""
self.predicates = {}
def set_text(self, text):
self.text = text.strip().casefold()
self.invalidateFilter()
def set_predicate(self, name, predicate):
if predicate is None:
self.predicates.pop(name, None)
else:
self.predicates[name] = predicate
self.invalidateFilter()
def filterAcceptsRow(self, source_row, source_parent):
model = self.sourceModel()
row = model.rows[source_row]
if any(not predicate(row) for predicate in self.predicates.values()):
return False
if not self.text:
return True
haystack = " ".join(str(column.display(row) or "") for column in model.columns).casefold()
return all(term in haystack for term in self.text.split())
def visible_rows(self):
model = self.sourceModel()
return [model.rows[self.mapToSource(self.index(row, 0)).row()] for row in range(self.rowCount())]
def row_at(self, proxy_index):
return self.sourceModel().rows[self.mapToSource(proxy_index).row()]
+46
View File
@@ -0,0 +1,46 @@
"""Main window pages."""
from PySide6.QtWidgets import QFrame, QScrollArea, QVBoxLayout, QWidget
from netbox_sync.ui.widgets import PageHeader
class Page(QWidget):
"""Common page frame: header plus content area, optionally scrollable."""
title = ""
subtitle = ""
def __init__(self, window, scrollable=False):
super().__init__()
self.window = window
self.state = window.state
self.tasks = window.tasks
self.actions = window.actions
self.setObjectName("PageRoot")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
if scrollable:
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setFrameShape(QFrame.NoFrame)
inner = QWidget()
inner.setObjectName("PageRoot")
scroll.setWidget(inner)
outer.addWidget(scroll)
host = inner
else:
host = self
self.body = QVBoxLayout() if host is self else QVBoxLayout(host)
if host is self:
outer.addLayout(self.body)
self.body.setContentsMargins(32, 26, 32, 24)
self.body.setSpacing(18)
self.header = PageHeader(self.title, self.subtitle)
self.body.addWidget(self.header)
def on_show(self):
"""Called whenever the page becomes visible."""
def set_busy(self, busy):
"""Disable actions that would conflict with a running task."""
+253
View File
@@ -0,0 +1,253 @@
import copy
import uuid
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QFormLayout, QHBoxLayout, QLineEdit, QMenu, QStackedWidget
from netbox_sync.core.virtualization import SOURCE_TYPES, source_endpoint
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import SourceDialog
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Badge, Card, EmptyState, PasswordField, Table, button, checkbox, label
class ConnectionsPage(Page):
title = "Verbindungen"
subtitle = "NetBox-Ziel und Virtualisierungsquellen des Kundenprofils. Änderungen werden automatisch gespeichert."
def __init__(self, window):
super().__init__(window)
self._loading = False
# NetBox ----------------------------------------------------------
netbox_card = Card("NetBox", "Ziel aller Synchronisierungen. Benötigt einen API-Token mit Schreibrechten.")
self.status_badge = Badge()
netbox_card.add_action(self.status_badge)
form = QFormLayout()
form.setHorizontalSpacing(18)
form.setVerticalSpacing(10)
form.setLabelAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.url = QLineEdit()
self.url.setPlaceholderText("https://netbox.example.de")
self.token = PasswordField("API-Token")
self.ignore_ssl = checkbox("Selbstsigniertes Zertifikat akzeptieren (TLS-Prüfung deaktivieren)")
form.addRow("URL", self.url)
form.addRow("API-Token", self.token)
form.addRow("", self.ignore_ssl)
netbox_card.add(form)
test_row = QHBoxLayout()
self.test_button = button("Verbindung testen", "zap", on_click=self.test_netbox)
self.status_text = label("", muted=True, wrap=True)
test_row.addWidget(self.test_button)
test_row.addWidget(self.status_text, 1)
netbox_card.add(test_row)
self.body.addWidget(netbox_card)
# Sources ---------------------------------------------------------
sources_card = Card("Virtualisierungsquellen", "VMware vCenter/ESXi und Proxmox VE – beliebig viele pro Profil.")
self.add_button = sources_card.add_action(button("Quelle hinzufügen", "plus", "primary", on_click=self.add_source))
self.sources_card = sources_card
columns = [
Column("enabled", "Aktiv", 70, value=lambda row: ""),
Column("name", "Name", 220),
Column("type", "Typ", 140, value=lambda row: SOURCE_TYPES.get(row.get("type"), row.get("type"))),
Column("endpoint", "Endpunkt", 320, value=source_endpoint),
Column("tls", "TLS", 140, value=lambda row: "nicht geprüft" if row.get("ignore_ssl") else "geprüft",
color=lambda row: "warning" if row.get("ignore_ssl") else "text_muted"),
]
self.model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
self.model.checked_changed.connect(self._enabled_changed)
self.proxy = FilterProxy(self.model)
self.table = Table(stretch_column=3)
self.table.setModel(self.proxy)
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.doubleClicked.connect(lambda _index: self.edit_source())
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.customContextMenuRequested.connect(self._context_menu)
self.table.selectionModel().selectionChanged.connect(self._update_buttons)
self.sources_stack = QStackedWidget()
self.sources_empty = EmptyState("server", "Noch keine Quelle",
"Füge einen vCenter-, ESXi- oder Proxmox-Zugang hinzu, um VMs zu laden.",
"Quelle hinzufügen", self.add_source)
self.sources_stack.addWidget(self.sources_empty)
self.sources_stack.addWidget(self.table)
sources_card.add(self.sources_stack, 1)
toolbar = QHBoxLayout()
self.edit_button = button("Bearbeiten", "pencil", on_click=self.edit_source)
self.duplicate_button = button("Duplizieren", "copy", on_click=self.duplicate_source)
self.remove_button = button("Entfernen", "trash", "danger", on_click=self.remove_source)
toolbar.addWidget(self.edit_button)
toolbar.addWidget(self.duplicate_button)
toolbar.addStretch(1)
toolbar.addWidget(self.remove_button)
self.source_toolbar = toolbar
sources_card.add(toolbar)
self.body.addWidget(sources_card, 1)
self._save_timer = QTimer(self)
self._save_timer.setSingleShot(True)
self._save_timer.setInterval(400)
self._save_timer.timeout.connect(self._store_netbox)
self.url.textEdited.connect(self._save_timer.start)
self.token.textEdited.connect(self._save_timer.start)
self.ignore_ssl.toggled.connect(self._store_netbox)
self.url.editingFinished.connect(self._normalize_url)
self.state.profile_switched.connect(self.load_profile)
self.state.netbox_changed.connect(self.update_status)
self.load_profile()
# ------------------------------------------------------------------
def load_profile(self):
profile = self.state.profile
self._loading = True
self.setEnabled(profile is not None)
self.url.setText(profile.get("netbox_url", "") if profile else "")
self.token.setText(profile.get("netbox_token", "") if profile else "")
self.ignore_ssl.setChecked(bool(profile.get("netbox_ignore_ssl")) if profile else False)
self._loading = False
self.refresh_sources()
self.update_status()
def _normalize_url(self):
text = self.url.text().strip().rstrip("/")
if text and not text.startswith(("http://", "https://")):
text = f"https://{text}"
if text.endswith("/api"):
text = text[:-4]
if text != self.url.text():
self.url.setText(text)
self._store_netbox()
def _store_netbox(self, *_args):
if self._loading:
return
self._save_timer.stop()
self.state.edit_profile(
netbox_url=self.url.text().strip(),
netbox_token=self.token.text().strip(),
netbox_ignore_ssl=self.ignore_ssl.isChecked(),
)
def update_status(self):
status = self.state.netbox_status
configured = self.state.netbox_configured()
if not configured:
self.status_badge.set("Nicht eingerichtet", "warning")
self.status_text.setText("")
elif status == "ok":
self.status_badge.set(f"Verbunden · {self.state.netbox_version}", "success")
self.status_text.setText("")
elif status == "error":
self.status_badge.set("Fehler", "error")
self.status_text.setText(self.state.netbox_message)
else:
self.status_badge.set("Nicht getestet", "neutral")
self.status_text.setText("")
self.status_text.setProperty("muted", status != "error")
self.status_text.setStyleSheet(f"color: {theme.color('danger')};" if status == "error" else "")
def test_netbox(self):
self._store_netbox()
if not self.state.netbox_configured():
self.status_text.setText("Bitte URL und API-Token eintragen.")
return
self.status_badge.set("Teste …", "neutral")
self.actions.test_netbox()
def set_busy(self, busy):
self.test_button.setEnabled(not busy)
# ------------------------------------------------------------------
# Sources
# ------------------------------------------------------------------
def refresh_sources(self):
sources = self.state.sources
self.model.checked = {source["id"] for source in sources if source.get("enabled", True)}
self.model.set_rows(sources)
has_sources = bool(sources)
self.sources_stack.setCurrentIndex(1 if has_sources else 0)
self.add_button.setVisible(has_sources)
for widget in (self.edit_button, self.duplicate_button, self.remove_button):
widget.setVisible(has_sources)
self._update_buttons()
def _enabled_changed(self):
changed = False
for source in self.state.sources:
enabled = source["id"] in self.model.checked
if source.get("enabled", True) != enabled:
source["enabled"] = enabled
changed = True
if changed:
self.state.touch()
def _selected(self):
rows = self.table.selectionModel().selectedRows()
return self.proxy.row_at(rows[0]) if rows else None
def _update_buttons(self, *_args):
selected = self._selected() is not None
for widget in (self.edit_button, self.duplicate_button, self.remove_button):
widgets.set_enabled(widget, selected, "Bitte zuerst eine Quelle in der Tabelle auswählen.")
def add_source(self):
if self.state.profile is None:
return
dialog = SourceDialog(self.window)
if dialog.exec() and dialog.result:
self.state.sources.append(dialog.result)
self.state.touch()
self.refresh_sources()
self.window.toast(f"Quelle „{dialog.result['name']}“ hinzugefügt")
def edit_source(self):
source = self._selected()
if not source:
return
dialog = SourceDialog(self.window, source)
if dialog.exec() and dialog.result:
index = self.state.sources.index(source)
self.state.sources[index] = dialog.result
self.state.touch()
self.refresh_sources()
def duplicate_source(self):
source = self._selected()
if not source:
return
clone = copy.deepcopy(source)
clone["id"] = uuid.uuid4().hex
clone["name"] = f"{source['name']} (Kopie)"
dialog = SourceDialog(self.window, clone)
if dialog.exec() and dialog.result:
self.state.sources.append(dialog.result)
self.state.touch()
self.refresh_sources()
def remove_source(self):
source = self._selected()
if not source:
return
if widgets.confirm(self.window, "Quelle entfernen", f"Quelle „{source['name']}“ aus dem Profil entfernen?",
ok_text="Entfernen", destructive=True):
self.state.sources.remove(source)
self.state.touch()
self.refresh_sources()
def _context_menu(self, position):
if not self._selected():
return
menu = QMenu(self)
menu.addAction(icon("pencil", theme.color("text_muted")), "Bearbeiten …", self.edit_source)
menu.addAction(icon("copy", theme.color("text_muted")), "Duplizieren …", self.duplicate_source)
menu.addSeparator()
menu.addAction(icon("trash", theme.color("danger")), "Entfernen", self.remove_source)
menu.exec(self.table.viewport().mapToGlobal(position))
+183
View File
@@ -0,0 +1,183 @@
import ipaddress
from PySide6.QtWidgets import (
QComboBox,
QFormLayout,
QHBoxLayout,
QPlainTextEdit,
QStackedWidget,
QVBoxLayout,
QWidget,
)
from netbox_sync.core.vm_sync import vrf_label
from netbox_sync.ui import widgets
from netbox_sync.ui.pages import Page
from netbox_sync.ui.widgets import Banner, Card, EmptyState, SearchableComboBox, button, label
GLOBAL = "__global__"
class IpamPage(Page):
title = "VRFs & Netze"
subtitle = "Mehrere VRFs oder Präfixe für einen Mandanten in einem Schritt in NetBox anlegen."
def __init__(self, window):
super().__init__(window)
self.stack = QStackedWidget()
self.empty = EmptyState("globe", "NetBox-Daten werden benötigt",
"Für dieses Werkzeug werden Mandanten und VRFs aus NetBox geladen.",
"NetBox-Daten laden", lambda: self.actions.load_targets())
self.stack.addWidget(self.empty)
content = QWidget()
layout = QHBoxLayout(content)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(18)
tenant_row = QFormLayout()
self.tenant = SearchableComboBox("Mandant suchen …")
self.tenant.setMinimumWidth(320)
tenant_row.addRow("Mandant", self.tenant)
vrf_card = Card("VRFs anlegen", "Ein Name pro Zeile. Bereits vorhandene VRFs des Mandanten werden übersprungen.")
self.vrf_names = QPlainTextEdit()
self.vrf_names.setPlaceholderText("Kunde - Produktion\nKunde - DMZ\nKunde - Management")
vrf_card.add(self.vrf_names, 1)
self.vrf_button = button("VRFs anlegen", "plus", "primary", on_click=self.create_vrfs)
vrf_card.add(self.vrf_button)
prefix_card = Card("Präfixe anlegen", "Ein Netz pro Zeile, z. B. 10.10.100.0/24 oder 2001:db8:10::/64.")
form = QFormLayout()
self.vrf = QComboBox()
form.addRow("Ziel-VRF", self.vrf)
prefix_card.add(form)
self.prefixes = QPlainTextEdit()
self.prefixes.setPlaceholderText("10.10.100.0/24\n10.10.101.0/24")
prefix_card.add(self.prefixes, 1)
self.prefix_hint = label("", muted=True, wrap=True)
prefix_card.add(self.prefix_hint)
self.prefix_button = button("Präfixe anlegen", "plus", "primary", on_click=self.create_prefixes)
prefix_card.add(self.prefix_button)
layout.addWidget(vrf_card, 1)
layout.addWidget(prefix_card, 1)
outer = QWidget()
outer_layout = QVBoxLayout(outer)
outer_layout.setContentsMargins(0, 0, 0, 0)
outer_layout.setSpacing(16)
outer_layout.addLayout(tenant_row)
self.result = Banner("", "success", closable=True)
self.result.hide()
outer_layout.addWidget(self.result)
outer_layout.addWidget(content, 1)
self.stack.addWidget(outer)
self.body.addWidget(self.stack, 1)
self.tenant.currentIndexChanged.connect(self.refresh_vrfs)
self.prefixes.textChanged.connect(self._validate_prefixes)
self.state.netbox_changed.connect(self.refresh)
self.state.profile_switched.connect(self.refresh)
self.refresh()
def on_show(self):
if self.state.engine is None and self.state.netbox_configured() and not self.tasks.busy:
self.actions.load_targets()
def refresh(self):
engine = self.state.engine
self.stack.setCurrentIndex(1 if engine else 0)
if not engine:
return
current = self.tenant.valid_data()
self.tenant.set_items(sorted(engine.tenants, key=str.casefold), current)
self.refresh_vrfs()
def refresh_vrfs(self, *_args):
engine = self.state.engine
tenant = self.tenant.valid_data()
current = self.vrf.currentData()
self.vrf.clear()
if engine and tenant:
for vrf in engine.tenant_vrfs(engine.tenants[tenant]):
self.vrf.addItem(vrf_label(vrf), vrf.id)
self.vrf.addItem("Global (ohne VRF)", GLOBAL)
self.vrf.setCurrentIndex(max(0, self.vrf.findData(current)))
@staticmethod
def _lines(widget):
return list(dict.fromkeys(line.strip() for line in widget.toPlainText().splitlines() if line.strip()))
def _validate_prefixes(self):
invalid, adjusted = [], []
for line in self._lines(self.prefixes):
try:
network = ipaddress.ip_network(line, strict=False)
if str(network) != line:
adjusted.append(f"{line} → {network}")
except ValueError:
invalid.append(line)
parts = []
if invalid:
parts.append("Ungültig: " + ", ".join(invalid[:5]))
if adjusted:
parts.append("Wird korrigiert: " + ", ".join(adjusted[:5]))
self.prefix_hint.setText(" · ".join(parts))
def set_busy(self, busy):
self.vrf_button.setEnabled(not busy)
self.prefix_button.setEnabled(not busy)
def _tenant_or_warn(self):
tenant = self.tenant.valid_data()
if not tenant:
widgets.message(self.window, "Mandant fehlt", "Bitte zuerst einen Mandanten auswählen.", "info")
return tenant
def create_vrfs(self):
tenant = self._tenant_or_warn()
names = self._lines(self.vrf_names)
if not tenant or not names:
return
engine = self.state.engine
def done(result):
created, reused, errors = result
self.refresh_vrfs()
text = f"VRFs für {tenant}: {created} angelegt, {reused} bereits vorhanden."
if errors:
self.result.set(text + "<br>" + "<br>".join(errors), "warning")
else:
self.vrf_names.clear()
self.result.set(text, "success")
self.result.show()
self.tasks.run(lambda _ctx: engine.create_vrfs_batch(tenant, names), title="VRFs anlegen", area="ipam",
on_success=done)
def create_prefixes(self):
tenant = self._tenant_or_warn()
networks = self._lines(self.prefixes)
if not tenant or not networks:
return
vrf_data = self.vrf.currentData()
vrf_id = None if vrf_data == GLOBAL else vrf_data
vrf_name = self.vrf.currentText()
if not widgets.confirm(self.window, "Präfixe anlegen",
f"{len(networks)} Präfix(e) für {tenant} in „{vrf_name}“ anlegen?", ok_text="Anlegen"):
return
engine = self.state.engine
def done(result):
created, reused, canonical, errors = result
text = f"Präfixe: {created} angelegt, {reused} bereits vorhanden (Mandant aktualisiert)."
if errors:
self.prefixes.setPlainText("\n".join(error.split(":")[0] for error in errors))
self.result.set(text + "<br>Fehler:<br>" + "<br>".join(errors), "warning")
else:
self.prefixes.clear()
self.result.set(text, "success")
self.result.show()
self.tasks.run(lambda _ctx: engine.create_prefixes_batch(tenant, vrf_id, networks), title="Präfixe anlegen",
area="ipam", on_success=done)
+121
View File
@@ -0,0 +1,121 @@
import html
import os
import time
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QComboBox, QFileDialog, QHBoxLayout, QPlainTextEdit
from netbox_sync.core.config import log_dir
from netbox_sync.ui.pages import Page
from netbox_sync.ui.tasks import AREAS, log_bus
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Card, SearchField, button
MAX_ENTRIES = 10000
LEVEL_RANK = {"debug": 0, "info": 1, "success": 1, "warning": 2, "error": 3}
LEVEL_TEXT = {"info": "INFO", "success": "OK", "warning": "WARNUNG", "error": "FEHLER", "debug": "DEBUG"}
class LogPage(Page):
title = "Protokoll"
subtitle = "Alle Aktivitäten dieser Sitzung. Zusätzlich wird ein Logfile im Benutzerprofil geschrieben."
def __init__(self, window):
super().__init__(window)
self.entries = []
card = Card(padding=0, spacing=0)
toolbar = QHBoxLayout()
toolbar.setContentsMargins(16, 14, 16, 12)
toolbar.setSpacing(8)
self.search = SearchField("Protokoll durchsuchen …")
self.level = QComboBox()
for text, value in (("Alle Meldungen", 0), ("Nur Warnungen und Fehler", 2), ("Nur Fehler", 3)):
self.level.addItem(text, value)
self.area = QComboBox()
self.area.addItem("Alle Bereiche", None)
for key, text in AREAS.items():
self.area.addItem(text, key)
toolbar.addWidget(self.search, 2)
toolbar.addWidget(self.level)
toolbar.addWidget(self.area)
toolbar.addStretch(1)
toolbar.addWidget(button("Kopieren", "copy", on_click=self.copy))
toolbar.addWidget(button("Exportieren …", "download", on_click=self.export))
toolbar.addWidget(button("Log-Ordner", "folder", on_click=self.open_folder))
toolbar.addWidget(button("Leeren", "trash", "ghost", on_click=self.clear))
card.add(toolbar)
self.view = QPlainTextEdit()
self.view.setObjectName("LogView")
self.view.setReadOnly(True)
self.view.setMaximumBlockCount(MAX_ENTRIES)
card.add(self.view, 1)
self.body.addWidget(card, 1)
self.search.textChanged.connect(self.render)
self.level.currentIndexChanged.connect(self.render)
self.area.currentIndexChanged.connect(self.render)
log_bus.entry.connect(self.add)
theme.changed.connect(self.render)
def _accepts(self, entry):
if LEVEL_RANK.get(entry.level, 1) < self.level.currentData():
return False
area = self.area.currentData()
if area and entry.area != area:
return False
query = self.search.text().strip().casefold()
return not query or query in entry.text.casefold()
def _html(self, entry):
colors = {"warning": theme.color("warning"), "error": theme.color("danger"), "success": theme.color("success")}
stamp = time.strftime("%H:%M:%S", time.localtime(entry.timestamp))
level = LEVEL_TEXT.get(entry.level, entry.level.upper())
color = colors.get(entry.level, theme.color("text"))
muted = theme.color("text_faint")
area = AREAS.get(entry.area, entry.area)
return (f'<span style="color:{muted}">{stamp}</span>&nbsp;&nbsp;'
f'<span style="color:{color}; font-weight:600">{level:<8}</span>&nbsp;'
f'<span style="color:{muted}">[{html.escape(area)}]</span>&nbsp;'
f'<span style="color:{color}">{html.escape(entry.text)}</span>')
def add(self, entry):
self.entries.append(entry)
if len(self.entries) > MAX_ENTRIES:
del self.entries[: len(self.entries) - MAX_ENTRIES]
if self._accepts(entry):
self.view.appendHtml(self._html(entry))
def render(self, *_args):
self.view.clear()
self.view.appendHtml("<br>".join(self._html(entry) for entry in self.entries if self._accepts(entry)))
self.view.verticalScrollBar().setValue(self.view.verticalScrollBar().maximum())
def _plain(self):
lines = []
for entry in self.entries:
if self._accepts(entry):
stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(entry.timestamp))
lines.append(f"{stamp} {LEVEL_TEXT.get(entry.level, entry.level):<8} [{AREAS.get(entry.area, entry.area)}] "
f"{entry.text}")
return "\n".join(lines)
def copy(self):
QGuiApplication.clipboard().setText(self._plain())
self.window.toast("Protokoll in die Zwischenablage kopiert", "info")
def export(self):
name = time.strftime("netbox-sync-protokoll-%Y%m%d-%H%M.txt")
path, _filter = QFileDialog.getSaveFileName(self, "Protokoll exportieren", name, "Text (*.txt)")
if path:
with open(path, "w", encoding="utf-8") as stream:
stream.write(self._plain())
self.window.toast("Protokoll gespeichert")
def open_folder(self):
folder = log_dir()
folder.mkdir(parents=True, exist_ok=True)
os.startfile(folder) # noqa: S606 - Windows Explorer
def clear(self):
self.entries.clear()
self.view.clear()
+187
View File
@@ -0,0 +1,187 @@
import time
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QLabel, QVBoxLayout, QWidget
from netbox_sync.ui.icons import icon
from netbox_sync.ui.pages import Page
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Card, EmptyState, StatTile, button, hline, label
def _ago(timestamp):
if not timestamp:
return ""
minutes = int((time.time() - timestamp) / 60)
if minutes < 1:
return "gerade eben"
if minutes < 60:
return f"vor {minutes} min"
return time.strftime("um %H:%M Uhr", time.localtime(timestamp))
class Step(QWidget):
def __init__(self, number, title, text, action_text, on_action, optional=False):
super().__init__()
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 6, 0, 6)
layout.setSpacing(14)
self.circle = QLabel(str(number))
self.circle.setObjectName("StepCircle")
self.circle.setAlignment(Qt.AlignCenter)
self.number = number
layout.addWidget(self.circle, 0, Qt.AlignTop)
texts = QVBoxLayout()
texts.setSpacing(2)
heading = title + (" <span style='font-weight:400'>(optional)</span>" if optional else "")
self.title = label(heading)
self.title.setTextFormat(Qt.RichText)
self.title.setStyleSheet("font-weight: 600;")
texts.addWidget(self.title)
self.text = label(text, muted=True, wrap=True)
texts.addWidget(self.text)
layout.addLayout(texts, 1)
self.action = button(action_text, on_click=on_action)
layout.addWidget(self.action, 0, Qt.AlignVCenter)
self.done = False
theme.changed.connect(self._render)
def set_done(self, done, primary=False):
self.done = done
self.action.setProperty("variant", "primary" if primary and not done else None)
self.action.style().unpolish(self.action)
self.action.style().polish(self.action)
self._render()
def _render(self):
self.circle.setProperty("done", self.done)
if self.done:
self.circle.setText("")
self.circle.setPixmap(icon("check", theme.color("success"), 2.6).pixmap(16, 16))
else:
self.circle.clear()
self.circle.setText(str(self.number))
self.circle.style().unpolish(self.circle)
self.circle.style().polish(self.circle)
class OverviewPage(Page):
title = "Übersicht"
subtitle = "Status des aktiven Kundenprofils und die nächsten Schritte."
def __init__(self, window):
super().__init__(window, scrollable=True)
self.empty = EmptyState(
"building", "Willkommen beim NetBox Synchronizer",
"Lege zuerst ein Kundenprofil an. Darin werden die NetBox-Instanz, VMware-/Proxmox-Quellen und "
"Switch-Zugänge eines Kunden gespeichert – Passwörter verschlüsselt mit Windows DPAPI.",
"Erstes Kundenprofil anlegen", window.new_profile,
)
self.body.addWidget(self.empty, 1)
self.content = QWidget()
content = QVBoxLayout(self.content)
content.setContentsMargins(0, 0, 0, 0)
content.setSpacing(18)
tiles = QGridLayout()
tiles.setSpacing(16)
self.netbox_tile = StatTile("database", "NetBox")
self.vm_tile = StatTile("server", "Virtualisierung")
self.switch_tile = StatTile("network", "Switche")
self.netbox_tile.clicked.connect(lambda: window.navigate("connections"))
self.vm_tile.clicked.connect(lambda: window.navigate("vms"))
self.switch_tile.clicked.connect(lambda: window.navigate("switches"))
for column, tile in enumerate((self.netbox_tile, self.vm_tile, self.switch_tile)):
tiles.addWidget(tile, 0, column)
tiles.setColumnStretch(column, 1)
content.addLayout(tiles)
steps = Card("Erste Schritte", "In vier Schritten von der leeren NetBox zur gepflegten Dokumentation.")
self.steps = [
Step(1, "NetBox verbinden", "URL und API-Token hinterlegen und die Verbindung testen.",
"Einrichten", lambda: window.navigate("connections")),
Step(2, "Virtualisierungsquelle hinzufügen", "vCenter, ESXi-Host oder Proxmox-Cluster anbinden.",
"Quelle hinzufügen", self._add_source),
Step(3, "VMs laden und importieren",
"VMs auswählen, Cluster und Mandant festlegen – neue Netze werden vor dem Anlegen angezeigt.",
"Zu den VMs", lambda: window.navigate("vms")),
Step(4, "Switche dokumentieren",
"Bestehende NetBox-Geräte per SSH auslesen: Schnittstellen, IP-Adressen und LLDP-Verkabelung.",
"Zu den Switchen", lambda: window.navigate("switches"), optional=True),
]
for index, step in enumerate(self.steps):
if index:
steps.add(hline())
steps.add(step)
content.addWidget(steps)
tips = Card("Gut zu wissen")
for text in (
"Alle Eingaben werden automatisch gespeichert – es gibt keinen Speichern-Knopf mehr.",
"Lange Vorgänge laufen im Hintergrund. Das Fenster bleibt bedienbar, unten rechts lässt sich abbrechen.",
"Vor jedem Schreibvorgang zeigt die Anwendung eine Zusammenfassung der Änderungen.",
"Das Protokoll enthält alle Details und wird zusätzlich als Datei gespeichert.",
):
row = QHBoxLayout()
dot = QLabel("•")
dot.setProperty("muted", True)
row.addWidget(dot, 0, Qt.AlignTop)
row.addWidget(label(text, muted=True, wrap=True), 1)
tips.add(row)
content.addWidget(tips)
content.addStretch(1)
self.body.addWidget(self.content, 1)
for signal in (self.state.profile_switched, self.state.profile_edited, self.state.netbox_changed,
self.state.vms_changed, self.state.switches_changed):
signal.connect(self.refresh)
self.refresh()
def _add_source(self):
self.window.navigate("connections")
self.window.pages["connections"].add_source()
def on_show(self):
self.refresh()
def refresh(self):
profile = self.state.profile
self.empty.setVisible(profile is None)
self.content.setVisible(profile is not None)
if profile is None:
self.header.subtitle.setText("Noch kein Kundenprofil vorhanden.")
return
self.header.subtitle.setText(f"Kundenprofil „{profile['name']}“")
configured = self.state.netbox_configured()
status = self.state.netbox_status
if not configured:
self.netbox_tile.set("Nicht eingerichtet", "URL und API-Token fehlen.", "Einrichten", "warning")
elif status == "ok":
self.netbox_tile.set(f"NetBox {self.state.netbox_version}", profile["netbox_url"], "Verbunden", "success")
elif status == "error":
self.netbox_tile.set("Fehler", self.state.netbox_message, "Fehler", "error")
else:
self.netbox_tile.set("Bereit", profile["netbox_url"], "Nicht getestet", "neutral")
sources = self.state.sources
active = sum(1 for source in sources if source.get("enabled", True))
if self.state.vms:
new = sum(1 for vm in self.state.vms if self.state.engine and vm["name"] not in self.state.engine.existing_vms)
self.vm_tile.set(f"{len(self.state.vms)} VMs", f"{new} noch nicht in NetBox · geladen {_ago(self.state.vms_loaded_at)}",
f"{active} Quelle(n)", "info")
else:
self.vm_tile.set(f"{len(sources)} Quelle(n)", "VMs noch nicht geladen." if sources else "Noch keine Quelle.",
"", "neutral")
switches = self.state.switches
scanned = len([key for key in self.state.switch_snapshots if any(s["id"] == key for s in switches)])
errors = sum(1 for status_, _text in self.state.switch_status.values() if status_ == "error")
detail = f"{scanned} ausgelesen" if scanned else ("Noch nicht ausgelesen." if switches else "Noch keine Switche.")
self.switch_tile.set(f"{len(switches)} Switch(e)", detail,
f"{errors} Fehler" if errors else "", "error" if errors else "neutral")
done = [configured and status != "error", bool(sources), bool(self.state.vms), bool(switches)]
first_open = next((index for index, value in enumerate(done) if not value), None)
for index, step in enumerate(self.steps):
step.set_done(done[index], primary=index == first_open)
+111
View File
@@ -0,0 +1,111 @@
import os
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QButtonGroup, QFormLayout, QHBoxLayout, QRadioButton, QSpinBox
from netbox_sync import APP_NAME, APP_PUBLISHER, APP_VERSION
from netbox_sync.core.config import config_dir, config_path, known_hosts_path, log_dir
from netbox_sync.ui import widgets
from netbox_sync.ui.pages import Page
from netbox_sync.ui.widgets import Card, button, checkbox, label
class SettingsPage(Page):
title = "Einstellungen"
subtitle = "Gelten für alle Kundenprofile."
def __init__(self, window):
super().__init__(window, scrollable=True)
appearance = Card("Darstellung")
row = QHBoxLayout()
self.theme_group = QButtonGroup(self)
self.theme_buttons = {}
for key, text in (("system", "Wie Windows"), ("light", "Hell"), ("dark", "Dunkel")):
radio = QRadioButton(text)
radio.setCursor(Qt.PointingHandCursor)
self.theme_group.addButton(radio)
self.theme_buttons[key] = radio
row.addWidget(radio)
radio.toggled.connect(lambda checked, k=key: checked and self._set_theme(k))
row.addStretch(1)
appearance.add(row)
self.body.addWidget(appearance)
switches = Card("Switche", "Verhalten beim Auslesen per SSH.")
form = QFormLayout()
form.setHorizontalSpacing(18)
self.parallel = QSpinBox()
self.parallel.setRange(1, 16)
self.parallel.setSuffix(" gleichzeitig")
self.parallel.setFixedWidth(160)
form.addRow("SSH-Sitzungen", self.parallel)
switches.add(form)
self.enable_lldp = checkbox("LLDP automatisch aktivieren, wenn es auf einem Switch deaktiviert ist",
tooltip="Ändert die laufende Konfiguration des Switches.")
switches.add(self.enable_lldp)
switches.add(label("Ohne diese Option wird die Switch-Konfiguration nie verändert; es werden nur "
"„show“-/„display“-Befehle ausgeführt.", muted=True, wrap=True))
keys = QHBoxLayout()
keys.addWidget(label("SSH-Hostschlüssel werden beim ersten Kontakt gespeichert und danach geprüft.",
muted=True, wrap=True), 1)
keys.addWidget(button("Alle vergessen", "trash", "danger", on_click=self.forget_keys))
switches.add(keys)
self.body.addWidget(switches)
data = Card("Daten & Dateien")
for caption, path, opener in (
("Konfiguration", config_path(), config_dir()),
("Protokolle", log_dir(), log_dir()),
):
line = QHBoxLayout()
line.addWidget(label(caption), 0)
line.addSpacing(12)
line.addWidget(label(str(path), muted=True, selectable=True), 1)
line.addWidget(button("Öffnen", "folder", on_click=lambda _c=False, p=opener: self._open(p)))
data.add(line)
data.add(label("Passwörter und Tokens sind mit Windows DPAPI an dieses Benutzerkonto gebunden und können "
"nicht auf einem anderen Rechner entschlüsselt werden.", muted=True, wrap=True))
self.body.addWidget(data)
about = Card("Über")
about.add(label(f"<b>{APP_NAME}</b> Version {APP_VERSION}"))
about.add(label(f"© {APP_PUBLISHER}", muted=True))
self.body.addWidget(about)
self.body.addStretch(1)
self.parallel.valueChanged.connect(lambda value: self.state.update_settings(parallel_ssh=value))
self.enable_lldp.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
self.state.settings_changed.connect(self.load)
self.load()
def load(self):
settings = self.state.settings
for widget in (self.parallel, self.enable_lldp, *self.theme_buttons.values()):
widget.blockSignals(True)
self.parallel.setValue(int(settings.get("parallel_ssh", 4)))
self.enable_lldp.setChecked(bool(settings.get("enable_lldp")))
self.theme_buttons.get(settings.get("theme", "system"), self.theme_buttons["system"]).setChecked(True)
for widget in (self.parallel, self.enable_lldp, *self.theme_buttons.values()):
widget.blockSignals(False)
def _set_theme(self, mode):
if self.state.settings.get("theme") != mode:
self.state.update_settings(theme=mode)
self.window.apply_theme()
@staticmethod
def _open(path):
path.mkdir(parents=True, exist_ok=True)
os.startfile(path) # noqa: S606 - Windows Explorer
def forget_keys(self):
path = known_hosts_path()
if not path.exists():
self.window.toast("Es sind keine Hostschlüssel gespeichert.", "info")
return
if widgets.confirm(self.window, "Hostschlüssel vergessen",
"Alle gespeicherten SSH-Hostschlüssel löschen? Beim nächsten Auslesen werden sie ohne "
"Prüfung neu übernommen.", ok_text="Löschen", destructive=True):
path.unlink()
self.window.toast("Gespeicherte Hostschlüssel gelöscht")
+340
View File
@@ -0,0 +1,340 @@
import time
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
from netbox_sync.core.switches import PLATFORMS
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.theme import theme
from netbox_sync.ui.widgets import Card, EmptyState, SearchField, Table, button, checkbox, label
def _speed(value):
if not value:
return ""
return f"{value / 1000:g} Gbit/s" if value >= 1000 else f"{value} Mbit/s"
class SwitchesPage(Page):
title = "Switche"
subtitle = ("Bestehende NetBox-Geräte per SSH auslesen und Schnittstellen, IP-Adressen und LLDP/CDP-Verkabelung "
"dokumentieren. Unterstützt Aruba CX, ArubaOS-Switch/ProCurve und HPE Comware.")
def __init__(self, window):
super().__init__(window)
splitter = QSplitter(Qt.Vertical)
splitter.setChildrenCollapsible(False)
# Switch list -------------------------------------------------------
list_card = Card("Switch-Zugänge", "Haken setzen, um Switche auszulesen oder zu synchronisieren.")
self.add_button = list_card.add_action(button("Switche hinzufügen …", "plus", on_click=self.add_switches))
self.discover_button = list_card.add_action(button("Auslesen", "play", "primary", on_click=self.discover))
columns = [
Column("name", "NetBox-Gerät", 200),
Column("platform", "Plattform", 180, value=lambda row: PLATFORMS.get(row.get("platform"), row.get("platform"))),
Column("host", "SSH-Host", 150, value=lambda row: f"{row.get('host', '')}:{row.get('port', 22)}"),
Column("enabled", "Aktiv", 70, value=lambda row: "ja" if row.get("enabled", True) else "nein",
color=lambda row: None if row.get("enabled", True) else "text_faint"),
Column("status", "Letztes Auslesen", 300, value=self._status_text, dot=self._status_dot,
tooltip=self._status_text),
]
self.switch_model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
self.switch_proxy = FilterProxy(self.switch_model)
self.switch_table = Table()
self.switch_table.setModel(self.switch_proxy)
for index, column in enumerate(columns):
self.switch_table.setColumnWidth(index, column.width)
self.switch_table.doubleClicked.connect(lambda _index: self.edit_switch())
self.switch_table.setContextMenuPolicy(Qt.CustomContextMenu)
self.switch_table.customContextMenuRequested.connect(self._context_menu)
self.switch_stack = QStackedWidget()
self.switch_empty = EmptyState("network", "Noch keine Switche im Profil",
"Wähle vorhandene Geräte aus NetBox aus und hinterlege den SSH-Zugang – "
"mehrere Switche lassen sich in einem Schritt hinzufügen.",
"Switche hinzufügen", self.add_switches)
self.switch_stack.addWidget(self.switch_empty)
self.switch_stack.addWidget(self.switch_table)
list_card.add(self.switch_stack, 1)
toolbar = QHBoxLayout()
self.select_all_button = button("Alle auswählen", variant="ghost", on_click=self.select_all)
self.edit_button = button("Bearbeiten", "pencil", on_click=self.edit_switch)
self.remove_button = button("Entfernen", "trash", "danger", on_click=self.remove_switches)
toolbar.addWidget(self.select_all_button)
toolbar.addStretch(1)
self.lldp_option = checkbox("LLDP bei Bedarf aktivieren",
tooltip="Ist LLDP auf einem Switch global deaktiviert, wird es per Konfigurations"
"befehl eingeschaltet. Das ändert die laufende Konfiguration des Switches!")
toolbar.addWidget(self.lldp_option)
toolbar.addSpacing(12)
toolbar.addWidget(self.edit_button)
toolbar.addWidget(self.remove_button)
list_card.add(toolbar)
splitter.addWidget(list_card)
# Results -------------------------------------------------------------
result_card = Card("Ergebnisse", "Erkannte Schnittstellen und Nachbarn der ausgelesenen Switche.")
self.raw_button = result_card.add_action(button("SSH-Rohdaten", "terminal", on_click=self.show_raw))
self.sync_button = result_card.add_action(button("Nach NetBox übertragen …", "upload", "primary",
on_click=self.sync))
filters = QHBoxLayout()
self.search = SearchField("Schnittstelle, IP, Nachbar …")
self.switch_filter = QComboBox()
self.switch_filter.setMinimumWidth(200)
self.only_neighbors = checkbox("Nur mit Nachbar")
self.only_up = checkbox("Nur aktive Ports")
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
filters.addWidget(self.search, 2)
filters.addWidget(self.switch_filter, 1)
filters.addWidget(self.only_up)
filters.addWidget(self.only_neighbors)
filters.addStretch(1)
filters.addWidget(self.cables_option)
result_card.add(filters)
result_columns = [
Column("switch", "Switch", 140),
Column("name", "Schnittstelle", 150),
Column("state", "Status", 125, value=lambda row: ("Up" if row["connected"] else "Down")
if row["enabled"] else "Deaktiviert",
dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")),
Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")),
sort=lambda row: row.get("speed_mbps") or 0),
Column("ips", "IP-Adressen", 160, value=lambda row: ", ".join(row.get("ip_addresses", []))),
Column("neighbor", "Nachbar", 170, value=lambda row: (row.get("neighbor") or {}).get("system_name", "")),
Column("remote_port", "Nachbar-Port", 110, value=lambda row: (row.get("neighbor") or {}).get("remote_port", "")),
Column("protocol", "Quelle", 70, value=lambda row: (row.get("neighbor") or {}).get("protocol", ""),
color=lambda row: "text_muted"),
]
self.result_model = RowTableModel(result_columns)
self.result_proxy = FilterProxy(self.result_model)
self.result_table = Table()
self.result_table.setModel(self.result_proxy)
for index, column in enumerate(result_columns):
self.result_table.setColumnWidth(index, column.width)
self.result_stack = QStackedWidget()
self.result_empty = EmptyState("terminal", "Noch nichts ausgelesen",
"Switche oben anhaken und „Auslesen“ wählen. Mehrere Switche werden parallel "
"abgefragt.")
self.result_stack.addWidget(self.result_empty)
self.result_stack.addWidget(self.result_table)
result_card.add(self.result_stack, 1)
self.result_summary = label("", muted=True)
result_card.add(self.result_summary)
splitter.addWidget(result_card)
splitter.setStretchFactor(0, 2)
splitter.setStretchFactor(1, 3)
self.body.addWidget(splitter, 1)
self.search.textChanged.connect(self.result_proxy.set_text)
self.switch_filter.currentIndexChanged.connect(self._apply_result_filters)
self.only_neighbors.toggled.connect(self._apply_result_filters)
self.only_up.toggled.connect(self._apply_result_filters)
self.switch_model.checked_changed.connect(self._update_buttons)
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value))
self.state.switches_changed.connect(self.refresh)
self.state.profile_switched.connect(self.refresh)
self.state.profile_edited.connect(self.refresh_switches)
self.state.settings_changed.connect(self._load_settings)
self._load_settings()
self.refresh()
# ------------------------------------------------------------------
def _load_settings(self):
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables")):
widget.blockSignals(True)
widget.setChecked(bool(self.state.settings.get(key)))
widget.blockSignals(False)
def _status_text(self, row):
status = self.state.switch_status.get(row["id"])
if not status:
return "–"
snapshot = self.state.switch_snapshots.get(row["id"])
when = time.strftime("%H:%M", time.localtime(snapshot["discovered_at"])) if snapshot else ""
return f"{when} · {status[1]}" if when else status[1]
def _status_dot(self, row):
status = self.state.switch_status.get(row["id"])
if not status:
return None
return "success" if status[0] == "ok" else "danger"
def refresh(self):
self.refresh_switches()
self.refresh_results()
def refresh_switches(self):
switches = self.state.switches
self.switch_model.set_rows(switches)
self.switch_stack.setCurrentIndex(1 if switches else 0)
for widget in (self.select_all_button, self.edit_button, self.remove_button, self.lldp_option):
widget.setVisible(bool(switches))
self._update_buttons()
def refresh_results(self):
by_id = {switch["id"]: switch for switch in self.state.switches}
rows = []
for switch_id, snapshot in self.state.switch_snapshots.items():
switch = by_id.get(switch_id)
if not switch:
continue
for interface in snapshot["interfaces"]:
rows.append(dict(interface, switch=switch["name"], switch_id=switch_id))
self.result_model.set_rows(rows)
self.result_stack.setCurrentIndex(1 if rows else 0)
current = self.switch_filter.currentData()
self.switch_filter.blockSignals(True)
self.switch_filter.clear()
self.switch_filter.addItem("Alle Switche", None)
for switch_id in self.state.switch_snapshots:
if switch_id in by_id:
self.switch_filter.addItem(by_id[switch_id]["name"], switch_id)
self.switch_filter.setCurrentIndex(max(0, self.switch_filter.findData(current)))
self.switch_filter.blockSignals(False)
self._apply_result_filters()
def _apply_result_filters(self, *_args):
switch_id = self.switch_filter.currentData()
self.result_proxy.set_predicate("switch", (lambda row: row["switch_id"] == switch_id) if switch_id else None)
self.result_proxy.set_predicate("neighbor", (lambda row: bool(row.get("neighbor")))
if self.only_neighbors.isChecked() else None)
self.result_proxy.set_predicate("up", (lambda row: row.get("connected"))
if self.only_up.isChecked() else None)
rows = self.result_proxy.visible_rows()
neighbors = sum(1 for row in rows if row.get("neighbor"))
up = sum(1 for row in rows if row.get("connected"))
self.result_summary.setText(f"{len(rows)} Schnittstellen · {up} aktiv · {neighbors} mit Nachbar")
self._update_buttons()
def _checked(self):
return self.switch_model.checked_rows()
def _selected(self):
rows = self.switch_table.selectionModel().selectedRows()
return [self.switch_proxy.row_at(index) for index in rows]
def _targets(self):
"""Checked switches, or the selected rows when nothing is checked."""
return self._checked() or self._selected()
def _update_buttons(self, *_args):
busy = self.tasks.busy
targets = self._targets()
with_data = [switch for switch in targets if switch["id"] in self.state.switch_snapshots]
widgets.set_enabled(self.discover_button, bool(targets) and not busy,
"Bitte Switche anhaken." if not targets else "Bitte warten …")
self.discover_button.setText(f"{len(targets)} auslesen" if targets else "Auslesen")
widgets.set_enabled(self.sync_button, bool(with_data) and not busy,
"Bitte zuerst Switche auslesen." if not with_data else "Bitte warten …")
self.sync_button.setText(f"{len(with_data)} nach NetBox übertragen …" if with_data else "Nach NetBox übertragen …")
widgets.set_enabled(self.raw_button, bool(self.state.switch_snapshots), "Noch nichts ausgelesen.")
widgets.set_enabled(self.edit_button, len(self._selected()) == 1, "Bitte genau einen Switch markieren.")
widgets.set_enabled(self.remove_button, bool(targets), "Bitte Switche anhaken oder markieren.")
self.add_button.setEnabled(not busy)
def set_busy(self, busy):
self._update_buttons()
def select_all(self):
rows = self.switch_model.rows
all_checked = len(self.switch_model.checked) == len(rows)
self.switch_model.set_checked({row["id"] for row in rows}, not all_checked)
# ------------------------------------------------------------------
# Actions
# ------------------------------------------------------------------
def add_switches(self):
if self.state.profile is None:
return
def open_dialog(devices):
existing = {switch.get("device_id") for switch in self.state.switches}
dialog = AddSwitchesDialog(self.window, devices, existing)
if dialog.exec() and dialog.result:
self.state.switches.extend(dialog.result)
self.state.touch()
self.refresh_switches()
self.switch_model.set_checked({switch["id"] for switch in dialog.result})
self.window.toast(f"{len(dialog.result)} Switch(e) hinzugefügt – jetzt „Auslesen“ wählen")
if self.state.netbox_devices is not None:
open_dialog(self.state.netbox_devices)
else:
self.actions.load_devices(open_dialog)
def edit_switch(self):
selected = self._selected()
if len(selected) != 1:
return
current = selected[0]
dialog = SwitchDialog(self.window, current, self.state.netbox_devices)
if dialog.exec() and dialog.result:
index = self.state.switches.index(current)
self.state.switches[index] = dialog.result
if dialog.result.get("device_id") != current.get("device_id"):
self.state.switch_snapshots.pop(current["id"], None)
self.state.switch_status.pop(current["id"], None)
self.state.touch()
self.refresh()
def remove_switches(self):
targets = self._targets()
if not targets:
return
names = ", ".join(switch["name"] for switch in targets[:5]) + (" …" if len(targets) > 5 else "")
if not widgets.confirm(self.window, "Switche entfernen",
f"{len(targets)} Switch-Zugang/Zugänge aus dem Profil entfernen?\n{names}\n\n"
"Die Geräte in NetBox bleiben unverändert.", ok_text="Entfernen", destructive=True):
return
ids = {switch["id"] for switch in targets}
self.state.profile["switches"] = [switch for switch in self.state.switches if switch["id"] not in ids]
for switch_id in ids:
self.state.switch_snapshots.pop(switch_id, None)
self.state.switch_status.pop(switch_id, None)
self.state.touch()
self.refresh()
def discover(self):
targets = self._targets()
if not targets:
return
if self.lldp_option.isChecked() and not widgets.confirm(
self.window, "Switch-Konfiguration ändern?",
"„LLDP bei Bedarf aktivieren“ ist eingeschaltet. Ist LLDP auf einem Switch deaktiviert, wird es per "
"Konfigurationsbefehl aktiviert (ohne „write memory“).", ok_text="Auslesen", destructive=True):
return
self.actions.discover_switches(targets)
def sync(self):
targets = [switch["id"] for switch in self._targets() if switch["id"] in self.state.switch_snapshots]
self.actions.sync_switches(targets, self.cables_option.isChecked())
def show_raw(self):
by_id = {switch["id"]: switch for switch in self.state.switches}
items = [(by_id[key], snapshot) for key, snapshot in self.state.switch_snapshots.items() if key in by_id]
if not items:
return
selected = self._selected()
RawDataDialog(self.window, items, selected[0]["id"] if selected else None).exec()
def _context_menu(self, position):
if not self._selected():
return
muted = theme.color("text_muted")
menu = QMenu(self)
menu.addAction(icon("play", muted), "Auslesen", self.discover)
menu.addAction(icon("pencil", muted), "Bearbeiten …", self.edit_switch)
if any(switch["id"] in self.state.switch_snapshots for switch in self._selected()):
menu.addAction(icon("terminal", muted), "SSH-Rohdaten …", self.show_raw)
menu.addSeparator()
menu.addAction(icon("trash", theme.color("danger")), "Entfernen", self.remove_switches)
menu.exec(self.switch_table.viewport().mapToGlobal(position))
+202
View File
@@ -0,0 +1,202 @@
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QStackedWidget
from netbox_sync.ui import widgets
from netbox_sync.ui.import_wizard import ImportWizard
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
from netbox_sync.ui.pages import Page
from netbox_sync.ui.widgets import Card, EmptyState, SearchField, Table, button, label
def _ips(vm):
return ", ".join(ip.split("/")[0] for interface in vm.get("interfaces", []) for ip in interface.get("ips", []))
def _interfaces_tooltip(vm):
lines = [f"{vm['name']} · {vm.get('guest_os') or 'unbekanntes OS'}"]
for interface in vm.get("interfaces", []):
ips = ", ".join(interface.get("ips", [])) or "keine IP"
lines.append(f" {interface['name']} {interface.get('mac', '')} {ips}")
if len(lines) == 1:
lines.append(" Keine Netzwerkschnittstellen gemeldet (VMware Tools / QEMU Agent prüfen)")
return "\n".join(lines)
class VMsPage(Page):
title = "Virtuelle Maschinen"
subtitle = "VMs aus allen aktiven Quellen laden, auswählen und nach NetBox übernehmen."
def __init__(self, window):
super().__init__(window)
self.load_button = self.header.add_action(button("VMs laden", "refresh", "primary", on_click=self.load))
self.stack = QStackedWidget()
self.empty = EmptyState("server", "Noch keine VMs geladen",
"Die Anwendung liest alle aktiven Quellen parallel aus und gleicht sie mit NetBox ab.",
"VMs jetzt laden", self.load,
secondary=("Verbindungen prüfen", lambda: window.navigate("connections")))
self.stack.addWidget(self.empty)
card = Card(padding=0, spacing=0)
filters = QHBoxLayout()
filters.setContentsMargins(16, 14, 16, 12)
filters.setSpacing(8)
self.search = SearchField("Name, IP-Adresse, Betriebssystem …")
self.source_filter = QComboBox()
self.status_filter = QComboBox()
for text, value in (("Alle Zustände", None), ("Eingeschaltet", "active"), ("Ausgeschaltet", "offline")):
self.status_filter.addItem(text, value)
self.netbox_filter = QComboBox()
for text, value in (("NetBox: alle", None), ("Nur neue", "new"), ("Nur vorhandene", "existing")):
self.netbox_filter.addItem(text, value)
filters.addWidget(self.search, 3)
filters.addWidget(self.source_filter, 1)
filters.addWidget(self.status_filter, 1)
filters.addWidget(self.netbox_filter, 1)
card.add(filters)
columns = [
Column("name", "Name", 220, tooltip=_interfaces_tooltip),
Column("netbox", "NetBox", 95, value=self._netbox_state,
color=lambda row: "accent" if self._netbox_state(row) == "Neu" else "text_muted"),
Column("source", "Quelle", 140),
Column("kind", "Typ", 55),
Column("status", "Status", 135, value=lambda row: "Eingeschaltet" if row["status"] == "active" else "Aus",
dot=lambda row: "success" if row["status"] == "active" else "text_faint"),
Column("vcpus", "vCPU", 55, align="right"),
Column("memory", "RAM", 75, align="right", value=lambda row: f"{row['memory'] / 1024:g} GB",
sort=lambda row: row["memory"]),
Column("disk", "Disk", 75, align="right",
value=lambda row: f"{row['disk'] / 1024:.0f} GB" if row.get("disk") else "–",
sort=lambda row: row.get("disk") or 0),
Column("ips", "IP-Adressen", 200, value=_ips),
Column("guest_os", "Betriebssystem", 220),
]
self.model = RowTableModel(columns, checkable=True, row_id=lambda row: row["id"])
self.proxy = FilterProxy(self.model)
self.table = Table()
self.table.setModel(self.proxy)
self.table.sortByColumn(0, Qt.AscendingOrder)
for index, column in enumerate(columns):
self.table.setColumnWidth(index, column.width)
self.table.doubleClicked.connect(self._toggle)
card.add(self.table, 1)
footer = QHBoxLayout()
footer.setContentsMargins(16, 10, 16, 12)
footer.setSpacing(8)
footer.addWidget(button("Alle sichtbaren auswählen", variant="ghost", on_click=self.select_visible))
footer.addWidget(button("Nur neue auswählen", variant="ghost", on_click=self.select_new))
footer.addWidget(button("Auswahl aufheben", variant="ghost", on_click=self.clear_selection))
footer.addStretch(1)
self.selection_label = label("", muted=True)
footer.addWidget(self.selection_label)
self.import_button = button("Importieren …", "upload", "primary", on_click=self.start_import)
footer.addWidget(self.import_button)
card.add(footer)
self.stack.addWidget(card)
self.body.addWidget(self.stack, 1)
self.search.textChanged.connect(self.proxy.set_text)
self.source_filter.currentIndexChanged.connect(self._apply_filters)
self.status_filter.currentIndexChanged.connect(self._apply_filters)
self.netbox_filter.currentIndexChanged.connect(self._apply_filters)
self.model.checked_changed.connect(self._update_selection)
self.state.vms_changed.connect(self.refresh)
self.state.profile_switched.connect(self.refresh)
self.refresh()
def _netbox_state(self, vm):
engine = self.state.engine
if engine is None:
return ""
return "Vorhanden" if vm["name"] in engine.existing_vms else "Neu"
def refresh(self):
vms = self.state.vms
self.stack.setCurrentIndex(1 if vms else 0)
current = self.source_filter.currentData()
self.source_filter.blockSignals(True)
self.source_filter.clear()
self.source_filter.addItem("Alle Quellen", None)
for name in sorted({vm["source"] for vm in vms}, key=str.casefold):
self.source_filter.addItem(name, name)
self.source_filter.setCurrentIndex(max(0, self.source_filter.findData(current)))
self.source_filter.blockSignals(False)
self.model.set_rows(vms)
self._apply_filters()
self.load_button.setText("Neu laden" if vms else "VMs laden")
if not vms:
if not self.state.netbox_configured():
self.empty.set_text(text="Zuerst unter „Verbindungen“ NetBox und mindestens eine Quelle einrichten.")
elif not self.state.sources:
self.empty.set_text(text="Es ist noch keine VMware- oder Proxmox-Quelle hinterlegt.")
else:
self.empty.set_text(text="Die Anwendung liest alle aktiven Quellen parallel aus und gleicht sie "
"mit NetBox ab.")
def _apply_filters(self, *_args):
source = self.source_filter.currentData()
status = self.status_filter.currentData()
netbox_state = self.netbox_filter.currentData()
self.proxy.set_predicate("source", (lambda row: row["source"] == source) if source else None)
self.proxy.set_predicate("status", (lambda row: row["status"] == status) if status else None)
if netbox_state:
wanted = "Neu" if netbox_state == "new" else "Vorhanden"
self.proxy.set_predicate("netbox", lambda row: self._netbox_state(row) == wanted)
else:
self.proxy.set_predicate("netbox", None)
self._update_selection()
def _toggle(self, index):
row = self.proxy.row_at(index)
self.model.set_checked({row["id"]}, row["id"] not in self.model.checked)
def select_visible(self):
self.model.set_checked({row["id"] for row in self.proxy.visible_rows()})
def select_new(self):
self.model.set_checked(set(self.model.checked), False)
self.model.set_checked({row["id"] for row in self.proxy.visible_rows() if self._netbox_state(row) == "Neu"})
def clear_selection(self):
self.model.set_checked(set(self.model.checked), False)
def _update_selection(self):
count = len(self.model.checked)
visible = self.proxy.rowCount()
total = len(self.model.rows)
shown = f"{visible} von {total} angezeigt" if visible != total else f"{total} VMs"
self.selection_label.setText(f"{shown} · {count} ausgewählt")
self.import_button.setText(f"{count} VM(s) importieren …" if count else "Importieren …")
self._update_import_button()
def _update_import_button(self):
count = len(self.model.checked)
enabled = count > 0 and not self.tasks.busy and self.state.engine is not None
widgets.set_enabled(self.import_button, enabled,
"Bitte zuerst VMs in der Tabelle anhaken." if not count else "Bitte warten …")
def set_busy(self, busy):
self.load_button.setEnabled(not busy)
self._update_import_button()
def load(self):
self.actions.load_vms()
def start_import(self):
vms = self.model.checked_rows()
if not vms or self.state.engine is None:
return
if not self.state.engine.clusters:
widgets.message(self.window, "Kein Cluster in NetBox",
"In NetBox ist noch kein Cluster angelegt. Bitte zuerst unter Virtualisierung → Cluster "
"einen Cluster anlegen und die VMs neu laden.", "warning")
return
wizard = ImportWizard(self.window, self.state, self.tasks, vms)
wizard.exec()
if wizard.result_summary:
text, kind = wizard.result_summary
self.window.toast(text, kind)
self.model.refresh()
self._apply_filters()
+11
View File
@@ -0,0 +1,11 @@
import sys
from pathlib import Path
def resource_path(name):
"""Locate bundled files both from source and inside a PyInstaller build."""
base = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parents[1]))
candidate = base / "resources" / name
if candidate.exists():
return candidate
return Path(__file__).resolve().parents[1] / "resources" / name
+195
View File
@@ -0,0 +1,195 @@
"""Application state shared by all pages."""
import copy
from PySide6.QtCore import QObject, QTimer, Signal
from netbox_sync.core.config import DEFAULT_SETTINGS, ProfileStore, empty_profile
from netbox_sync.ui.tasks import logger
log = logger("app")
class AppState(QObject):
profiles_changed = Signal() # names added/removed/renamed
profile_switched = Signal() # another profile is active now
profile_edited = Signal() # data inside the active profile changed
settings_changed = Signal()
netbox_changed = Signal() # connection status / lookup data
vms_changed = Signal()
switches_changed = Signal() # switch list or discovery results
save_failed = Signal(str)
def __init__(self, store=None):
super().__init__()
self.store = store or ProfileStore()
self.profiles = {}
self.active = ""
self.settings = dict(DEFAULT_SETTINGS)
self._save_timer = QTimer(self)
self._save_timer.setSingleShot(True)
self._save_timer.setInterval(500)
self._save_timer.timeout.connect(self.save_now)
self.reset_runtime()
# ------------------------------------------------------------------
# Runtime data (never persisted)
# ------------------------------------------------------------------
def reset_runtime(self):
self.nb = None
self.netbox_status = "unknown" # unknown | ok | error
self.netbox_message = "Noch nicht verbunden"
self.netbox_version = ""
self.engine = None
self.vms = []
self.vms_loaded_at = None
self.netbox_devices = None
self.switch_snapshots = {}
self.switch_status = {}
def set_netbox(self, nb=None, status="ok", message="", engine=None):
if nb is not None:
self.nb = nb
self.netbox_version = getattr(nb, "netbox_version", "")
if engine is not None:
self.engine = engine
self.netbox_status = status
self.netbox_message = message
if status == "error":
self.nb = None
self.engine = None
self.netbox_changed.emit()
# ------------------------------------------------------------------
# Persistence
# ------------------------------------------------------------------
def load(self):
try:
self.profiles, active, self.settings = self.store.load()
except Exception as error: # noqa: BLE001
log.error("Konfiguration konnte nicht geladen werden: %s", error)
self.profiles, active = {}, ""
for context in self.store.decrypt_failures:
log.warning("Gespeichertes Geheimnis nicht lesbar (%s) – bitte neu eingeben.", context)
if self.profiles:
self.active = active if active in self.profiles else sorted(self.profiles, key=str.casefold)[0]
self.profiles_changed.emit()
self.profile_switched.emit()
self.settings_changed.emit()
def schedule_save(self):
self._save_timer.start()
def save_now(self):
self._save_timer.stop()
try:
self.store.save(self.profiles, self.active, self.settings)
except Exception as error: # noqa: BLE001
log.error("Speichern fehlgeschlagen: %s", error)
self.save_failed.emit(str(error))
return False
return True
# ------------------------------------------------------------------
# Profiles
# ------------------------------------------------------------------
@property
def profile(self):
return self.profiles.get(self.active)
def profile_names(self):
return sorted(self.profiles, key=str.casefold)
def switch_profile(self, name):
if name == self.active or name not in self.profiles:
return
self.save_now()
self.active = name
self.reset_runtime()
self.schedule_save()
self.profile_switched.emit()
self.netbox_changed.emit()
self.vms_changed.emit()
self.switches_changed.emit()
def create_profile(self, name, copy_from=None):
profile = copy.deepcopy(self.profiles[copy_from]) if copy_from in self.profiles else empty_profile(name)
profile["name"] = name
self.profiles[name] = profile
self.profiles_changed.emit()
self.active = ""
self.switch_profile(name)
self.save_now()
def rename_profile(self, old, new):
if old not in self.profiles or new in self.profiles:
return
profile = self.profiles.pop(old)
profile["name"] = new
self.profiles[new] = profile
if self.active == old:
self.active = new
self.save_now()
self.profiles_changed.emit()
self.profile_switched.emit()
def delete_profile(self, name):
if name not in self.profiles:
return
del self.profiles[name]
names = self.profile_names()
self.active = ""
self.profiles_changed.emit()
if names:
self.switch_profile(names[0])
else:
self.reset_runtime()
self.profile_switched.emit()
self.save_now()
def edit_profile(self, **fields):
profile = self.profile
if profile is None:
return
changed = {key: value for key, value in fields.items() if profile.get(key) != value}
if not changed:
return
profile.update(changed)
if {"netbox_url", "netbox_token", "netbox_ignore_ssl"} & set(changed):
self.nb = None
self.engine = None
self.netbox_devices = None
self.netbox_status = "unknown"
self.netbox_message = "Verbindungsdaten geändert"
self.netbox_changed.emit()
self.schedule_save()
self.profile_edited.emit()
def touch(self):
"""Call after mutating ``profile['sources']`` or ``profile['switches']`` in place."""
self.schedule_save()
self.profile_edited.emit()
def update_settings(self, **values):
self.settings.update(values)
self.schedule_save()
self.settings_changed.emit()
# ------------------------------------------------------------------
# Convenience
# ------------------------------------------------------------------
@property
def sources(self):
return self.profile["sources"] if self.profile else []
@property
def switches(self):
return self.profile["switches"] if self.profile else []
def netbox_configured(self):
profile = self.profile
return bool(profile and profile.get("netbox_url") and profile.get("netbox_token"))
+190
View File
@@ -0,0 +1,190 @@
"""Background tasks and the application-wide activity log."""
import logging
import threading
import time
import traceback
from dataclasses import dataclass, field
from PySide6.QtCore import QObject, QRunnable, QThreadPool, Signal
SUCCESS = 25
logging.addLevelName(SUCCESS, "SUCCESS")
LEVELS = {"debug": logging.DEBUG, "info": logging.INFO, "success": SUCCESS,
"warning": logging.WARNING, "error": logging.ERROR}
LEVEL_NAMES = {value: key for key, value in LEVELS.items()}
AREAS = {"app": "Allgemein", "netbox": "NetBox", "vm": "VMs", "switch": "Switche", "ipam": "IPAM"}
@dataclass
class LogEntry:
timestamp: float
level: str
area: str
text: str
details: str = field(default="")
class LogBus(QObject):
"""Receives log records from any thread and re-emits them in the GUI thread."""
entry = Signal(object)
class QtLogHandler(logging.Handler):
def __init__(self, bus):
super().__init__(level=logging.INFO)
self.bus = bus
def emit(self, record):
if not record.name.startswith("netbox_sync"):
return
area = record.name.split(".")[1] if record.name.count(".") >= 1 else "app"
level = LEVEL_NAMES.get(record.levelno, "info")
details = ""
if record.exc_info:
details = "".join(traceback.format_exception(*record.exc_info))
self.bus.entry.emit(LogEntry(record.created, level, area if area in AREAS else "app",
record.getMessage(), details))
log_bus = LogBus()
def logger(area):
return logging.getLogger(f"netbox_sync.{area}")
def area_log(area):
"""Return a ``log(text, level="info")`` callback for the core modules."""
target = logger(area)
def write(text, level="info"):
target.log(LEVELS.get(level, logging.INFO), text)
return write
class TaskCancelled(Exception):
pass
class TaskContext:
def __init__(self, signals, area):
self._signals = signals
self._cancel = threading.Event()
self.area = area
self.log = area_log(area)
def progress(self, value, maximum=0, text=""):
self._signals.progress.emit(int(value), int(maximum), text)
@property
def cancelled(self):
return self._cancel.is_set()
def check_cancelled(self):
if self._cancel.is_set():
raise TaskCancelled()
def cancel(self):
self._cancel.set()
class _Signals(QObject):
progress = Signal(int, int, str)
succeeded = Signal(object)
failed = Signal(object)
finished = Signal()
class Task(QRunnable):
def __init__(self, function, area, title):
super().__init__()
self.setAutoDelete(False)
self.function = function
self.title = title
self.signals = _Signals()
self.context = TaskContext(self.signals, area)
self.started_at = None
def run(self):
self.started_at = time.monotonic()
try:
result = self.function(self.context)
except TaskCancelled as error:
self.signals.failed.emit(error)
except Exception as error: # noqa: BLE001 - reported to the UI
logger(self.context.area).debug("Task %s fehlgeschlagen", self.title, exc_info=True)
error.traceback_text = traceback.format_exc()
self.signals.failed.emit(error)
else:
self.signals.succeeded.emit(result)
finally:
self.signals.finished.emit()
def cancel(self):
self.context.cancel()
class TaskManager(QObject):
"""Runs one foreground task at a time and exposes busy/progress state."""
busy_changed = Signal(bool)
progress = Signal(int, int, str)
started = Signal(str)
def __init__(self):
super().__init__()
self.pool = QThreadPool.globalInstance()
self.pool.setMaxThreadCount(max(4, self.pool.maxThreadCount()))
self.current = None
self._tasks = set()
@property
def busy(self):
return self.current is not None
def run(self, function, *, title, area="app", on_success=None, on_error=None, on_finished=None,
on_progress=None, cancellable=True):
if self.current is not None:
logger("app").warning("Bitte warten, bis „%s“ abgeschlossen ist.", self.current.title)
return None
task = Task(function, area, title)
task.cancellable = cancellable
self.current = task
self._tasks.add(task)
def finished():
self._tasks.discard(task)
if self.current is task:
self.current = None
self.busy_changed.emit(False)
if on_finished:
on_finished()
def failed(error):
if isinstance(error, TaskCancelled):
logger(area).warning("%s abgebrochen", title)
elif on_error:
on_error(error)
else:
logger(area).error("%s: %s", title, error)
task.signals.progress.connect(self.progress)
if on_progress:
task.signals.progress.connect(on_progress)
if on_success:
task.signals.succeeded.connect(on_success)
task.signals.failed.connect(failed)
task.signals.finished.connect(finished)
self.busy_changed.emit(True)
self.started.emit(title)
self.pool.start(task)
return task
def cancel(self):
if self.current is not None:
self.current.cancel()
+314
View File
@@ -0,0 +1,314 @@
"""Light and dark design tokens plus the application style sheet."""
from string import Template
from PySide6.QtCore import QObject, Qt, Signal
from PySide6.QtGui import QColor, QFont, QPalette
from PySide6.QtWidgets import QApplication
from netbox_sync.ui.icons import svg_file
LIGHT = {
"bg": "#F3F5F9",
"surface": "#FFFFFF",
"surface_alt": "#F8FAFC",
"hover": "#EEF2F7",
"border": "#E2E8F0",
"border_strong": "#CBD5E1",
"text": "#0F172A",
"text_muted": "#64748B",
"text_faint": "#94A3B8",
"accent": "#0A6CF0",
"accent_hover": "#085DCF",
"accent_pressed": "#074EAD",
"accent_soft": "#E7F0FE",
"accent_text": "#FFFFFF",
"success": "#15803D",
"success_soft": "#DCFCE7",
"warning": "#B45309",
"warning_soft": "#FEF3C7",
"danger": "#DC2626",
"danger_soft": "#FEE2E2",
"sidebar": "#0B1F3A",
"sidebar_text": "#B6C3D6",
"sidebar_hover": "#132B4D",
"sidebar_active": "#1B3A66",
"sidebar_accent": "#22D3EE",
"selection": "#DBE8FD",
"log_bg": "#FBFCFE",
}
DARK = {
"bg": "#0E1521",
"surface": "#151E2C",
"surface_alt": "#192334",
"hover": "#1E2A3D",
"border": "#243044",
"border_strong": "#334155",
"text": "#E2E8F0",
"text_muted": "#94A3B8",
"text_faint": "#64748B",
"accent": "#3B8BFF",
"accent_hover": "#5A9DFF",
"accent_pressed": "#2F7BEA",
"accent_soft": "#16294A",
"accent_text": "#FFFFFF",
"success": "#4ADE80",
"success_soft": "#13301F",
"warning": "#FBBF24",
"warning_soft": "#33280F",
"danger": "#F87171",
"danger_soft": "#3A1717",
"sidebar": "#09111D",
"sidebar_text": "#94A3B8",
"sidebar_hover": "#121E31",
"sidebar_active": "#18294A",
"sidebar_accent": "#22D3EE",
"selection": "#1D3357",
"log_bg": "#111926",
}
QSS = Template("""
* { outline: 0; }
QWidget { color: $text; font-size: 10pt; }
QMainWindow, QDialog, #PageRoot, QStackedWidget#Pages { background: $bg; }
QDialog { background: $bg; }
QToolTip { background: $text; color: $surface; border: none; padding: 6px 8px; border-radius: 6px; }
/* ---------- Sidebar ---------- */
#Sidebar { background: $sidebar; }
#Sidebar QLabel { color: $sidebar_text; }
#Sidebar #AppTitle { color: #FFFFFF; font-size: 12pt; font-weight: 600; }
#Sidebar #AppSubtitle { color: $sidebar_text; font-size: 8.5pt; }
#Sidebar #SectionLabel { color: #6B7FA0; font-size: 8pt; font-weight: 600; }
#Sidebar QPushButton[nav="true"] {
color: $sidebar_text; background: transparent; border: none; border-radius: 8px;
padding: 9px 12px; text-align: left; font-size: 10pt;
}
#Sidebar QPushButton[nav="true"]:hover { background: $sidebar_hover; color: #FFFFFF; }
#Sidebar QPushButton[nav="true"]:checked { background: $sidebar_active; color: #FFFFFF; font-weight: 600; }
#Sidebar QPushButton[nav="true"]:disabled { color: #3E5272; }
#Sidebar QComboBox {
background: $sidebar_hover; color: #FFFFFF; border: 1px solid #22385A; border-radius: 8px; padding: 6px 10px;
}
#Sidebar QComboBox::drop-down { border: none; width: 24px; }
#Sidebar QComboBox::down-arrow { image: url($chevron_light); width: 14px; height: 14px; }
#Sidebar QToolButton { background: $sidebar_hover; border: 1px solid #22385A; border-radius: 8px; padding: 5px; }
#Sidebar QToolButton:hover { background: $sidebar_active; }
#Sidebar QToolButton::menu-indicator { image: none; }
#Sidebar #VersionLabel { color: #4F6385; font-size: 8pt; }
#Sidebar QLabel[badge="true"] { background: $danger; color: #FFFFFF; }
/* ---------- Typography ---------- */
#PageTitle { font-size: 17pt; font-weight: 600; color: $text; }
#PageSubtitle { color: $text_muted; font-size: 10pt; }
#CardTitle { font-size: 11pt; font-weight: 600; }
#CardSubtitle, QLabel[muted="true"] { color: $text_muted; }
QLabel[faint="true"] { color: $text_faint; }
#StatValue { font-size: 15pt; font-weight: 600; }
#StatLabel { color: $text_muted; font-size: 9pt; }
#EmptyTitle { font-size: 13pt; font-weight: 600; }
#WizardStep { color: $text_faint; font-weight: 600; }
#WizardStep[active="true"] { color: $accent; }
#WizardStep[done="true"] { color: $success; }
#SummaryKey { color: $text_muted; }
#SummaryValue { font-weight: 600; }
/* ---------- Cards ---------- */
#Card { background: $surface; border: 1px solid $border; border-radius: 12px; }
#Card[flat="true"] { background: transparent; border: none; }
#Banner { border-radius: 10px; border: 1px solid $border; background: $surface_alt; }
#Banner[kind="info"] { background: $accent_soft; border-color: $accent_soft; }
#Banner[kind="warning"] { background: $warning_soft; border-color: $warning_soft; }
#Banner[kind="error"] { background: $danger_soft; border-color: $danger_soft; }
#Banner[kind="success"] { background: $success_soft; border-color: $success_soft; }
#Banner QLabel { background: transparent; }
#Separator { background: $border; max-height: 1px; min-height: 1px; }
/* ---------- Badges ---------- */
QLabel[badge="true"] { border-radius: 9px; padding: 2px 9px; font-size: 8.5pt; font-weight: 600; }
QLabel[badge="true"][kind="neutral"] { background: $hover; color: $text_muted; }
QLabel[badge="true"][kind="info"] { background: $accent_soft; color: $accent; }
QLabel[badge="true"][kind="success"] { background: $success_soft; color: $success; }
QLabel[badge="true"][kind="warning"] { background: $warning_soft; color: $warning; }
QLabel[badge="true"][kind="error"] { background: $danger_soft; color: $danger; }
/* ---------- Buttons ---------- */
QPushButton {
background: $surface; border: 1px solid $border_strong; border-radius: 8px;
padding: 7px 14px; color: $text; font-weight: 500;
}
QPushButton:hover { background: $hover; }
QPushButton:pressed { background: $border; }
QPushButton:disabled { color: $text_faint; border-color: $border; background: $surface_alt; }
QPushButton[variant="primary"] { background: $accent; border-color: $accent; color: $accent_text; font-weight: 600; }
QPushButton[variant="primary"]:hover { background: $accent_hover; border-color: $accent_hover; }
QPushButton[variant="primary"]:pressed { background: $accent_pressed; }
QPushButton[variant="primary"]:disabled { background: $border; border-color: $border; color: $text_faint; }
QPushButton[variant="danger"] { color: $danger; }
QPushButton[variant="danger"]:hover { background: $danger_soft; border-color: $danger; }
QPushButton[variant="ghost"] { background: transparent; border-color: transparent; color: $text_muted; }
QPushButton[variant="ghost"]:hover { background: $hover; color: $text; }
QPushButton[variant="link"] { background: transparent; border: none; color: $accent; padding: 2px 4px; }
QPushButton::menu-indicator { image: url($chevron); subcontrol-origin: padding; subcontrol-position: right center; width: 12px; right: 8px; }
QToolButton { background: transparent; border: none; border-radius: 6px; padding: 4px; }
QToolButton:hover { background: $hover; }
/* ---------- Inputs ---------- */
QLineEdit, QComboBox, QSpinBox, QPlainTextEdit, QTextEdit {
background: $surface; border: 1px solid $border_strong; border-radius: 8px;
padding: 6px 9px; selection-background-color: $accent; selection-color: #FFFFFF;
}
QPlainTextEdit, QTextEdit { padding: 6px; }
QLineEdit:hover, QComboBox:hover, QSpinBox:hover, QPlainTextEdit:hover { border-color: $text_faint; }
QLineEdit:focus, QComboBox:focus, QSpinBox:focus, QPlainTextEdit:focus, QTextEdit:focus { border: 1px solid $accent; }
QLineEdit:disabled, QComboBox:disabled, QSpinBox:disabled { background: $surface_alt; color: $text_faint; }
QLineEdit[invalid="true"] { border-color: $danger; }
QComboBox::drop-down { border: none; width: 26px; }
QComboBox::down-arrow { image: url($chevron); width: 14px; height: 14px; }
QComboBox QAbstractItemView {
background: $surface; border: 1px solid $border_strong; border-radius: 8px; padding: 4px;
selection-background-color: $accent_soft; selection-color: $text; outline: 0;
}
QSpinBox::up-button, QSpinBox::down-button { width: 18px; border: none; background: transparent; }
QSpinBox::up-arrow { image: url($chevron_up); width: 10px; height: 10px; }
QSpinBox::down-arrow { image: url($chevron); width: 10px; height: 10px; }
QCheckBox, QRadioButton { spacing: 8px; background: transparent; }
QCheckBox::indicator, QRadioButton::indicator, QTableView::indicator {
width: 16px; height: 16px; border: 1px solid $border_strong; background: $surface;
}
QCheckBox::indicator, QTableView::indicator { border-radius: 4px; }
QRadioButton::indicator { border-radius: 9px; }
QCheckBox::indicator:hover, QRadioButton::indicator:hover, QTableView::indicator:hover { border-color: $accent; }
QCheckBox::indicator:checked, QTableView::indicator:checked { background: $accent; border-color: $accent; image: url($check); }
QCheckBox::indicator:indeterminate { background: $accent; border-color: $accent; }
QRadioButton::indicator:checked { background: $accent; border-color: $accent; image: url($radio_dot); }
QCheckBox:disabled { color: $text_faint; }
/* ---------- Tables ---------- */
QTableView, QTreeView, QListView {
background: $surface; alternate-background-color: $surface_alt; border: none;
gridline-color: transparent; selection-background-color: $selection; selection-color: $text;
}
QTableView::item, QTreeView::item { padding: 4px 6px; border: none; }
QTableView::item:hover, QTreeView::item:hover { background: $hover; }
QTableView::item:selected, QTreeView::item:selected { background: $selection; color: $text; }
QHeaderView { background: $surface; }
QHeaderView::section {
background: $surface; color: $text_muted; border: none; border-bottom: 1px solid $border;
padding: 8px 6px; font-weight: 600; font-size: 9pt;
}
QHeaderView::section:hover { color: $text; }
QHeaderView::down-arrow { image: url($chevron); width: 10px; height: 10px; }
QHeaderView::up-arrow { image: url($chevron_up); width: 10px; height: 10px; }
QTableCornerButton::section { background: $surface; border: none; }
/* ---------- Misc ---------- */
QScrollBar:vertical { background: transparent; width: 10px; margin: 2px; }
QScrollBar:horizontal { background: transparent; height: 10px; margin: 2px; }
QScrollBar::handle { background: $border_strong; border-radius: 3px; min-height: 30px; min-width: 30px; }
QScrollBar::handle:hover { background: $text_faint; }
QScrollBar::add-line, QScrollBar::sub-line { width: 0; height: 0; }
QScrollBar::add-page, QScrollBar::sub-page { background: transparent; }
QScrollArea { background: transparent; border: none; }
QScrollArea > QWidget > QWidget { background: transparent; }
QSplitter::handle { background: transparent; }
QSplitter::handle:vertical { height: 10px; }
QSplitter::handle:horizontal { width: 10px; }
QProgressBar {
background: $border; border: none; border-radius: 4px; height: 8px; text-align: center; color: transparent;
max-height: 8px;
}
QProgressBar::chunk { background: $accent; border-radius: 4px; }
QMenu { background: $surface; border: 1px solid $border_strong; border-radius: 8px; padding: 5px; }
QMenu::item { padding: 7px 26px 7px 12px; border-radius: 6px; }
QMenu::item:selected { background: $accent_soft; color: $text; }
QMenu::separator { height: 1px; background: $border; margin: 4px 6px; }
QMenu::icon { padding-left: 8px; }
QTabWidget::pane { border: 1px solid $border; border-radius: 10px; background: $surface; top: -1px; }
QTabBar::tab {
background: transparent; color: $text_muted; padding: 8px 14px; border: none;
border-bottom: 2px solid transparent; margin-right: 4px;
}
QTabBar::tab:selected { color: $accent; border-bottom: 2px solid $accent; font-weight: 600; }
QTabBar::tab:hover { color: $text; }
#StatusBar { background: $surface; border-top: 1px solid $border; }
#StatusBar QLabel { color: $text_muted; font-size: 9pt; }
#Toast { background: $text; border-radius: 10px; }
#Toast QLabel { color: $surface; background: transparent; }
#LogView { background: $log_bg; border: none; font-family: "Cascadia Mono", Consolas, monospace; font-size: 9pt; }
#StepCircle { border-radius: 14px; min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
background: $hover; color: $text_muted; font-weight: 600; }
#StepCircle[done="true"] { background: $success_soft; color: $success; }
""")
class ThemeManager(QObject):
"""Applies a theme and tells widgets when colours change."""
changed = Signal()
def __init__(self):
super().__init__()
self.mode = "system"
self.tokens = dict(LIGHT)
self.dark = False
def color(self, name):
return self.tokens[name]
def resolve_dark(self, mode):
if mode == "dark":
return True
if mode == "light":
return False
hints = QApplication.styleHints()
return hasattr(hints, "colorScheme") and hints.colorScheme() == Qt.ColorScheme.Dark
def apply(self, mode=None):
app = QApplication.instance()
if mode:
self.mode = mode
self.dark = self.resolve_dark(self.mode)
self.tokens = dict(DARK if self.dark else LIGHT)
tokens = self.tokens
palette = QPalette()
roles = {
QPalette.Window: tokens["bg"], QPalette.WindowText: tokens["text"],
QPalette.Base: tokens["surface"], QPalette.AlternateBase: tokens["surface_alt"],
QPalette.Text: tokens["text"], QPalette.Button: tokens["surface"],
QPalette.ButtonText: tokens["text"], QPalette.Highlight: tokens["accent"],
QPalette.HighlightedText: "#FFFFFF", QPalette.ToolTipBase: tokens["text"],
QPalette.ToolTipText: tokens["surface"], QPalette.PlaceholderText: tokens["text_faint"],
QPalette.Link: tokens["accent"], QPalette.Mid: tokens["border_strong"],
QPalette.Midlight: tokens["border"], QPalette.Light: tokens["surface"],
QPalette.Dark: tokens["border_strong"],
}
for role, value in roles.items():
palette.setColor(role, QColor(value))
for role in (QPalette.Text, QPalette.WindowText, QPalette.ButtonText):
palette.setColor(QPalette.Disabled, role, QColor(tokens["text_faint"]))
app.setPalette(palette)
style = QSS.substitute(
tokens,
chevron=svg_file("chevron-down", tokens["text_muted"], 2.2),
chevron_up=svg_file("chevron-up", tokens["text_muted"], 2.2),
chevron_light=svg_file("chevron-down", "#B6C3D6", 2.2),
check=svg_file("check", "#FFFFFF", 3.0),
radio_dot=svg_file("radio-dot", "#FFFFFF"),
)
app.setStyleSheet(style)
self.changed.emit()
def base_font():
font = QFont("Segoe UI")
font.setPointSizeF(10)
font.setHintingPreference(QFont.PreferNoHinting)
return font
theme = ThemeManager()
+572
View File
@@ -0,0 +1,572 @@
"""Reusable widgets that give every page the same look and feel."""
from PySide6.QtCore import QEasingCurve, QPropertyAnimation, QSize, Qt, QTimer, Signal
from PySide6.QtWidgets import (
QAbstractItemView,
QCheckBox,
QComboBox,
QCompleter,
QDialog,
QDialogButtonBox,
QFrame,
QGraphicsOpacityEffect,
QHBoxLayout,
QHeaderView,
QLabel,
QLineEdit,
QPlainTextEdit,
QPushButton,
QSizePolicy,
QTableView,
QVBoxLayout,
QWidget,
)
from netbox_sync.ui.icons import icon
from netbox_sync.ui.theme import theme
def repolish(widget):
widget.style().unpolish(widget)
widget.style().polish(widget)
widget.update()
class ThemedIconMixin:
"""Re-render an icon whenever the theme changes."""
def _bind_icon(self, name, color_token, setter):
def apply():
setter(icon(name, theme.color(color_token)))
apply()
theme.changed.connect(apply)
def button(text, icon_name=None, variant=None, on_click=None, tooltip=None, parent=None):
widget = QPushButton(text, parent)
widget.setCursor(Qt.PointingHandCursor)
if variant:
widget.setProperty("variant", variant)
if icon_name:
token = {"primary": "accent_text", "danger": "danger", "link": "accent"}.get(variant, "text_muted")
def apply_icon():
color = "#FFFFFF" if token == "accent_text" else theme.color(token)
if not widget.isEnabled() and variant == "primary":
color = theme.color("text_faint")
widget.setIcon(icon(icon_name, color))
apply_icon()
theme.changed.connect(apply_icon)
widget.setIconSize(QSize(16, 16))
widget._apply_icon = apply_icon
if on_click:
widget.clicked.connect(on_click)
if tooltip:
widget.setToolTip(tooltip)
return widget
def set_enabled(widget, enabled, reason=None):
"""Enable/disable a button and show why it is disabled."""
widget.setEnabled(enabled)
if hasattr(widget, "_default_tooltip") is False:
widget._default_tooltip = widget.toolTip()
widget.setToolTip(widget._default_tooltip if enabled or not reason else reason)
if hasattr(widget, "_apply_icon"):
widget._apply_icon()
def label(text="", muted=False, faint=False, wrap=False, object_name=None, selectable=False):
widget = QLabel(text)
if muted:
widget.setProperty("muted", True)
if faint:
widget.setProperty("faint", True)
if wrap:
widget.setWordWrap(True)
if object_name:
widget.setObjectName(object_name)
if selectable:
widget.setTextInteractionFlags(Qt.TextSelectableByMouse)
return widget
def hline():
line = QFrame()
line.setObjectName("Separator")
line.setFrameShape(QFrame.NoFrame)
return line
class Badge(QLabel):
def __init__(self, text="", kind="neutral"):
super().__init__(text)
self.setProperty("badge", True)
self.setAlignment(Qt.AlignCenter)
self.set(text, kind)
def set(self, text, kind="neutral"):
self.setText(text)
self.setProperty("kind", kind)
self.setVisible(bool(text))
repolish(self)
class Card(QFrame):
def __init__(self, title=None, subtitle=None, parent=None, padding=18, spacing=12):
super().__init__(parent)
self.setObjectName("Card")
self.layout_ = QVBoxLayout(self)
self.layout_.setContentsMargins(padding, padding, padding, padding)
self.layout_.setSpacing(spacing)
self.header = None
self.actions = None
if title:
self.header = QHBoxLayout()
self.header.setSpacing(8)
text_box = QVBoxLayout()
text_box.setSpacing(2)
self.title_label = label(title, object_name="CardTitle")
text_box.addWidget(self.title_label)
if subtitle:
self.subtitle_label = label(subtitle, object_name="CardSubtitle", wrap=True)
text_box.addWidget(self.subtitle_label)
self.header.addLayout(text_box, 1)
self.actions = QHBoxLayout()
self.actions.setSpacing(8)
self.header.addLayout(self.actions)
self.layout_.addLayout(self.header)
def add(self, widget, stretch=0):
if isinstance(widget, QWidget):
self.layout_.addWidget(widget, stretch)
else:
self.layout_.addLayout(widget, stretch)
return widget
def add_action(self, widget):
self.actions.addWidget(widget)
return widget
class PageHeader(QWidget):
def __init__(self, title, subtitle=""):
super().__init__()
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(10)
texts = QVBoxLayout()
texts.setSpacing(3)
self.title = label(title, object_name="PageTitle")
self.subtitle = label(subtitle, object_name="PageSubtitle", wrap=True)
texts.addWidget(self.title)
texts.addWidget(self.subtitle)
layout.addLayout(texts, 1)
self.actions = QHBoxLayout()
self.actions.setSpacing(8)
layout.addLayout(self.actions)
def add_action(self, widget):
self.actions.addWidget(widget)
return widget
class Banner(QFrame):
"""Inline message instead of yet another modal dialog."""
ICONS = {"info": ("info", "accent"), "warning": ("warning", "warning"),
"error": ("error", "danger"), "success": ("success", "success")}
def __init__(self, text="", kind="info", action_text=None, on_action=None, closable=False):
super().__init__()
self.setObjectName("Banner")
layout = QHBoxLayout(self)
layout.setContentsMargins(12, 10, 12, 10)
layout.setSpacing(10)
self.icon_label = QLabel()
self.icon_label.setFixedSize(18, 18)
layout.addWidget(self.icon_label, 0, Qt.AlignTop)
self.text_label = label(text, wrap=True)
self.text_label.setTextFormat(Qt.RichText)
self.text_label.setOpenExternalLinks(False)
layout.addWidget(self.text_label, 1)
self.action = None
if action_text:
self.action = button(action_text, variant="link", on_click=on_action)
layout.addWidget(self.action, 0, Qt.AlignVCenter)
if closable:
close = button("", "x", "ghost", on_click=self.hide)
close.setFixedSize(26, 26)
layout.addWidget(close, 0, Qt.AlignTop)
self.kind = kind
self.set(text, kind)
theme.changed.connect(lambda: self.set(self.text_label.text(), self.kind))
def set(self, text, kind=None):
if kind:
self.kind = kind
self.setProperty("kind", self.kind)
name, token = self.ICONS[self.kind]
self.icon_label.setPixmap(icon(name, theme.color(token)).pixmap(18, 18))
self.text_label.setText(text)
repolish(self)
class EmptyState(QWidget):
def __init__(self, icon_name, title, text, action_text=None, on_action=None, secondary=None):
super().__init__()
layout = QVBoxLayout(self)
layout.setContentsMargins(24, 40, 24, 40)
layout.setSpacing(10)
layout.addStretch(1)
self.icon_label = QLabel()
self.icon_label.setAlignment(Qt.AlignCenter)
icon_name_ = icon_name
def apply():
self.icon_label.setPixmap(icon(icon_name_, theme.color("text_faint"), 1.5).pixmap(56, 56))
apply()
theme.changed.connect(apply)
layout.addWidget(self.icon_label)
self.title_label = label(title, object_name="EmptyTitle")
self.title_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.title_label)
self.text_label = label(text, muted=True, wrap=True)
self.text_label.setAlignment(Qt.AlignCenter)
self.text_label.setMaximumWidth(520)
layout.addWidget(self.text_label, 0, Qt.AlignHCenter)
buttons = QHBoxLayout()
buttons.addStretch(1)
self.action = None
if secondary:
buttons.addWidget(button(secondary[0], secondary[2] if len(secondary) > 2 else None,
on_click=secondary[1]))
if action_text:
self.action = button(action_text, "arrow-right", "primary", on_click=on_action)
buttons.addWidget(self.action)
buttons.addStretch(1)
layout.addSpacing(6)
layout.addLayout(buttons)
layout.addStretch(2)
def set_text(self, title=None, text=None):
if title is not None:
self.title_label.setText(title)
if text is not None:
self.text_label.setText(text)
class StatTile(QFrame):
clicked = Signal()
def __init__(self, icon_name, caption):
super().__init__()
self.setObjectName("Card")
self.setCursor(Qt.PointingHandCursor)
layout = QHBoxLayout(self)
layout.setContentsMargins(18, 16, 18, 16)
layout.setSpacing(14)
self.icon_label = QLabel()
self.icon_label.setFixedSize(40, 40)
self.icon_label.setAlignment(Qt.AlignCenter)
self._icon_name = icon_name
layout.addWidget(self.icon_label, 0, Qt.AlignTop)
texts = QVBoxLayout()
texts.setSpacing(2)
self.caption = label(caption, object_name="StatLabel")
self.value = label("–", object_name="StatValue")
self.detail = label("", muted=True, wrap=True)
texts.addWidget(self.caption)
texts.addWidget(self.value)
texts.addWidget(self.detail)
layout.addLayout(texts, 1)
self.badge = Badge()
layout.addWidget(self.badge, 0, Qt.AlignTop)
self._apply()
theme.changed.connect(self._apply)
def _apply(self):
self.icon_label.setStyleSheet(
f"background: {theme.color('accent_soft')}; border-radius: 10px;"
)
self.icon_label.setPixmap(icon(self._icon_name, theme.color("accent")).pixmap(22, 22))
def set(self, value, detail="", badge_text="", badge_kind="neutral"):
self.value.setText(value)
self.detail.setText(detail)
self.detail.setVisible(bool(detail))
self.badge.set(badge_text, badge_kind)
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.clicked.emit()
super().mouseReleaseEvent(event)
class SearchField(QLineEdit):
def __init__(self, placeholder="Suchen …"):
super().__init__()
self.setPlaceholderText(placeholder)
self.setClearButtonEnabled(True)
self._action = None
def apply():
if self._action:
self.removeAction(self._action)
self._action = self.addAction(icon("search", theme.color("text_faint")), QLineEdit.LeadingPosition)
apply()
theme.changed.connect(apply)
self.setMinimumWidth(220)
class PasswordField(QLineEdit):
def __init__(self, placeholder=""):
super().__init__()
self.setEchoMode(QLineEdit.Password)
self.setPlaceholderText(placeholder)
self._toggle = self.addAction(icon("eye", theme.color("text_muted")), QLineEdit.TrailingPosition)
self._toggle.setToolTip("Anzeigen")
self._toggle.triggered.connect(self.toggle)
theme.changed.connect(self._update_icon)
def toggle(self):
visible = self.echoMode() == QLineEdit.Password
self.setEchoMode(QLineEdit.Normal if visible else QLineEdit.Password)
self._update_icon()
def _update_icon(self):
hidden = self.echoMode() == QLineEdit.Password
self._toggle.setIcon(icon("eye" if hidden else "eye-off", theme.color("text_muted")))
self._toggle.setToolTip("Anzeigen" if hidden else "Verbergen")
class SearchableComboBox(QComboBox):
"""Editable combo box with substring completion – handy for long NetBox lists."""
def __init__(self, placeholder=""):
super().__init__()
self.setEditable(True)
self.setInsertPolicy(QComboBox.NoInsert)
self.lineEdit().setPlaceholderText(placeholder)
completer = QCompleter(self.model(), self)
completer.setFilterMode(Qt.MatchContains)
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.setCompletionMode(QCompleter.PopupCompletion)
self.setCompleter(completer)
self.setMaxVisibleItems(18)
def set_items(self, items, current=None):
self.blockSignals(True)
self.clear()
for item in items:
if isinstance(item, tuple):
self.addItem(item[0], item[1])
else:
self.addItem(item, item)
self.completer().setModel(self.model())
if current is not None:
self.select_data(current)
else:
self.setCurrentIndex(-1)
self.blockSignals(False)
def select_data(self, data):
index = self.findData(data)
self.setCurrentIndex(index)
if index < 0:
self.setEditText("")
def valid_data(self):
"""Return the item data only if the visible text matches an item."""
index = self.findText(self.currentText(), Qt.MatchFixedString)
return self.itemData(index) if index >= 0 else None
def configure_table(view, stretch_column=None, selection=QAbstractItemView.ExtendedSelection):
view.setAlternatingRowColors(True)
view.setSelectionBehavior(QAbstractItemView.SelectRows)
view.setSelectionMode(selection)
view.setShowGrid(False)
view.setWordWrap(False)
view.setSortingEnabled(True)
view.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
view.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
view.verticalHeader().setVisible(False)
view.verticalHeader().setDefaultSectionSize(34)
header = view.horizontalHeader()
header.setHighlightSections(False)
header.setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)
header.setSectionResizeMode(QHeaderView.Interactive)
header.setStretchLastSection(stretch_column is None)
if stretch_column is not None:
header.setSectionResizeMode(stretch_column, QHeaderView.Stretch)
view.setEditTriggers(QAbstractItemView.NoEditTriggers)
return view
class Table(QTableView):
def __init__(self, stretch_column=None):
super().__init__()
configure_table(self, stretch_column)
class Toast(QFrame):
"""Short non-blocking confirmation in the lower right corner."""
def __init__(self, parent):
super().__init__(parent)
self.setObjectName("Toast")
layout = QHBoxLayout(self)
layout.setContentsMargins(14, 11, 16, 11)
layout.setSpacing(10)
self.icon_label = QLabel()
self.icon_label.setFixedSize(18, 18)
layout.addWidget(self.icon_label)
self.text_label = QLabel()
self.text_label.setWordWrap(True)
self.text_label.setMaximumWidth(420)
layout.addWidget(self.text_label)
self.effect = QGraphicsOpacityEffect(self)
self.setGraphicsEffect(self.effect)
self.animation = QPropertyAnimation(self.effect, b"opacity", self)
self.animation.setDuration(220)
self.animation.setEasingCurve(QEasingCurve.OutCubic)
self.timer = QTimer(self)
self.timer.setSingleShot(True)
self.timer.timeout.connect(self.fade_out)
self.hide()
def show_message(self, text, kind="success", duration=4500):
colors = {"success": "#4ADE80", "info": "#60A5FA", "warning": "#FBBF24", "error": "#F87171"}
names = {"success": "success", "info": "info", "warning": "warning", "error": "error"}
self.icon_label.setPixmap(icon(names.get(kind, "info"), colors.get(kind, "#60A5FA")).pixmap(18, 18))
self.text_label.setText(text)
self.adjustSize()
self.reposition()
self.raise_()
self.show()
self.animation.stop()
self.animation.setStartValue(0.0)
self.animation.setEndValue(1.0)
self.animation.start()
self.timer.start(duration)
def reposition(self):
parent = self.parentWidget()
if parent:
self.move(parent.width() - self.width() - 24, parent.height() - self.height() - 52)
def fade_out(self):
self.animation.stop()
self.animation.setStartValue(1.0)
self.animation.setEndValue(0.0)
self.animation.finished.connect(self._hide_once)
self.animation.start()
def _hide_once(self):
self.animation.finished.disconnect(self._hide_once)
self.hide()
def mousePressEvent(self, _event):
self.timer.stop()
self.hide()
class TextDialog(QDialog):
"""Read-only text viewer with copy support."""
def __init__(self, parent, title, text):
super().__init__(parent)
self.setWindowTitle(title)
self.resize(900, 600)
layout = QVBoxLayout(self)
layout.setContentsMargins(16, 16, 16, 16)
editor = QPlainTextEdit(text)
editor.setObjectName("LogView")
editor.setReadOnly(True)
editor.setLineWrapMode(QPlainTextEdit.NoWrap)
layout.addWidget(editor)
buttons = QHBoxLayout()
buttons.addStretch(1)
from PySide6.QtGui import QGuiApplication
buttons.addWidget(button("Kopieren", "copy", on_click=lambda: QGuiApplication.clipboard().setText(text)))
buttons.addWidget(button("Schließen", variant="primary", on_click=self.accept))
layout.addLayout(buttons)
def message(parent, title, text, kind="info", details=None, buttons=("OK",), default=0):
"""Consistent modal message. Returns the index of the clicked button or -1."""
dialog = QDialog(parent)
dialog.setWindowTitle(title)
dialog.setMinimumWidth(460)
dialog.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
layout = QVBoxLayout(dialog)
layout.setContentsMargins(22, 20, 22, 18)
layout.setSpacing(14)
row = QHBoxLayout()
row.setSpacing(14)
icon_label = QLabel()
token = {"info": "accent", "warning": "warning", "error": "danger", "success": "success", "question": "accent"}[kind]
name = {"question": "info"}.get(kind, kind)
icon_label.setPixmap(icon(name, theme.color(token)).pixmap(28, 28))
row.addWidget(icon_label, 0, Qt.AlignTop)
texts = QVBoxLayout()
texts.setSpacing(6)
texts.addWidget(label(title, object_name="CardTitle"))
body = label(text, wrap=True, selectable=True)
body.setMaximumWidth(560)
texts.addWidget(body)
row.addLayout(texts, 1)
layout.addLayout(row)
if details:
detail_view = QPlainTextEdit(details)
detail_view.setObjectName("LogView")
detail_view.setReadOnly(True)
detail_view.setMinimumHeight(140)
detail_view.setMaximumHeight(260)
layout.addWidget(detail_view)
box = QHBoxLayout()
box.addStretch(1)
result = {"index": -1}
for index, text_value in enumerate(buttons):
variant = None
if index == default:
variant = "danger" if kind == "warning" and len(buttons) > 1 else "primary"
widget = button(text_value, variant=variant)
widget.clicked.connect(lambda _checked=False, i=index: (result.update(index=i), dialog.accept()))
if index == default:
widget.setDefault(True)
box.addWidget(widget)
layout.addLayout(box)
dialog.exec()
return result["index"]
def confirm(parent, title, text, ok_text="OK", cancel_text="Abbrechen", destructive=False, details=None):
kind = "warning" if destructive else "question"
index = message(parent, title, text, kind, details, buttons=(cancel_text, ok_text), default=1)
return index == 1
def error(parent, title, text, details=None):
message(parent, title, text, "error", details)
def form_dialog_buttons(dialog, ok_text="Speichern"):
box = QDialogButtonBox()
cancel = button("Abbrechen", on_click=dialog.reject)
ok = button(ok_text, variant="primary", on_click=dialog.accept)
ok.setDefault(True)
box.addButton(cancel, QDialogButtonBox.RejectRole)
box.addButton(ok, QDialogButtonBox.AcceptRole)
return box, ok
def checkbox(text, checked=False, tooltip=None):
widget = QCheckBox(text)
widget.setChecked(checked)
widget.setCursor(Qt.PointingHandCursor)
if tooltip:
widget.setToolTip(tooltip)
return widget