-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.py
More file actions
775 lines (645 loc) · 22.9 KB
/
ui.py
File metadata and controls
775 lines (645 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
#!/usr/bin/env python3
# src/core/ui.py
from __future__ import annotations
import os
import base64
from typing import Iterable, Optional, Callable, List
from PyQt5.QtWidgets import (
QDialog, QVBoxLayout, QLabel, QHBoxLayout, QPushButton,
QLineEdit, QSpinBox, QComboBox, QCheckBox, QColorDialog,
QSizePolicy, QStyle, QStyleOptionButton, QWidget, QFileDialog,
QListView, QFrame, QApplication, QListWidget
)
from PyQt5.QtGui import (
QIcon, QPixmap, QPainter, QColor, QPen, QTransform
)
from PyQt5.QtCore import QRect, Qt, QTimer
from PyQt5.QtSvg import QSvgWidget, QSvgRenderer
# Allow this module to be used both as part of the 'app' package and as a standalone script
try:
from .helper import Helper
from .network.tools import Tools
except ImportError: # likely running as a top-level script
from helper import Helper
from network.tools import Tools
class MsgBox(QDialog):
ICONS = {
"info": "core/icons/info.svg",
"error": "core/icons/error.svg",
"warning": "core/icons/warning.svg",
"question":"core/icons/question.svg",
}
def __init__(
self,
parent=None,
title: str = "",
message: str = "",
icon: Optional[str] = None,
buttons: Iterable[str] = ("OK",),
default: Optional[str] = None,
icon_size: int = 64,
icon_lookup_fn: Optional[Callable[[str], Optional[str]]] = None,
):
super().__init__(parent)
self.setWindowTitle(title)
self.setObjectName("MsgBox")
self.setModal(True)
self._selected: Optional[str] = None
self._icon_lookup = icon_lookup_fn
self._helper = None
if isinstance(buttons, str):
buttons = (buttons,)
else:
buttons = tuple(buttons)
layout = QVBoxLayout(self)
# --- Top area: icon + message ---
top = QHBoxLayout()
layout.addLayout(top)
if icon:
icon_path = self._resolve_icon_path(icon)
if icon_path:
svg = QSvgWidget(icon_path)
svg.setFixedSize(icon_size, icon_size)
svg.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
top.addWidget(svg, alignment=Qt.AlignVCenter)
# message text
msg_label = QLabel(message)
msg_label.setWordWrap(True)
msg_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
top.addWidget(msg_label)
# --- Buttons ---
btn_row = QHBoxLayout()
btn_row.addStretch(1)
self._buttons: dict[str, QPushButton] = {}
for text in buttons:
btn = QPushButton(text)
self._buttons[text] = btn
btn.clicked.connect(lambda _, t=text: self._on_click(t))
btn_row.addWidget(btn)
layout.addLayout(btn_row)
# default selection
if default and default in self._buttons:
self._buttons[default].setDefault(True)
self._buttons[default].setFocus()
# ------------------------------------------------------------------
# Internals
# ------------------------------------------------------------------
def _ensure_helper(self):
"""
Lazily import and instantiate helper.
"""
if self._helper is not None:
return self._helper
try:
self._helper = Helper()
except Exception as e:
print(f"[MsgBox] Failed to initialize helpers: {e}")
self._helper = None
return self._helper
def _resolve_icon_path(self, icon: str) -> Optional[str]:
"""
Resolve an icon name or path using ICONS + optional lookup function.
"""
# Named icon → relative path from ICONS
candidate = self.ICONS.get(icon, icon)
if self._icon_lookup:
resolved = self._icon_lookup(candidate)
if resolved:
return resolved
else:
if self._ensure_helper() is not None:
resolved = self._helper.get_path(candidate)
if resolved and self._helper.file_exists(resolved):
return resolved
return candidate
def _on_click(self, text: str):
self._selected = text
self.accept()
# -------------------------------------------------
# Convenience static helper
# -------------------------------------------------
@staticmethod
def show(
parent=None,
title: str = "",
message: str = "",
icon: Optional[str] = None,
buttons: Iterable[str] = ("OK",),
default: Optional[str] = None,
icon_lookup_fn: Optional[Callable[[str], Optional[str]]] = None,
) -> str:
"""
Show the dialog modally and return the label of the chosen button.
"""
dlg = MsgBox(
parent=parent,
title=title,
message=message,
icon=icon,
buttons=buttons,
default=default,
icon_lookup_fn=icon_lookup_fn,
)
dlg.exec_()
return dlg._selected or default or ""
class SpinningIconLabel(QLabel):
def __init__(self, svg_path: str, size: int = 32, interval_ms: int = 50, parent=None):
super().__init__(parent)
self._size = size
self._svg_path = svg_path
self._angle = 0
self._base_pixmap = QIcon(svg_path).pixmap(size, size)
self.setFixedSize(size, size)
self.setAlignment(Qt.AlignCenter)
self.setScaledContents(True)
self.setStyleSheet("padding: 0; margin: 0; border: none;")
# Timer
self._timer = QTimer(self)
self._timer.timeout.connect(self._tick)
self._timer.start(interval_ms)
def _tick(self):
"""Rotate icon by a fixed number of degrees."""
self._angle = (self._angle + 10) % 360
rotated = self._rotate_pixmap(self._base_pixmap, self._angle)
self.setPixmap(rotated)
def _rotate_pixmap(self, pixmap: QPixmap, angle: float) -> QPixmap:
"""Return a rotated copy of the pixmap."""
transform = QTransform()
transform.rotate(angle)
rotated = pixmap.transformed(transform, Qt.SmoothTransformation)
# Scale back to exact size
return rotated.scaled(self._size, self._size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
def stop(self):
self._timer.stop()
def start(self):
self._timer.start()
class ColorButton(QPushButton):
def __init__(self, initial: str = "#265162", parent=None):
super().__init__(parent)
self._color = QColor(initial)
self.clicked.connect(self._pick)
def _pick(self):
chosen = QColorDialog.getColor(self._color, self, "Choose Color")
if chosen.isValid():
self._color = chosen
self.update() # repaint
def color(self) -> QColor:
return self._color
def hex(self) -> str:
return self._color.name()
def setHex(self, value: str):
if not value:
return
c = QColor(value)
if c.isValid():
self._color = c
self.update() # repaint
def _styleOption(self):
option = QStyleOptionButton()
option.initFrom(self)
option.text = self.text()
option.icon = self.icon()
return option
def paintEvent(self, event):
super().paintEvent(event)
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing, True)
# Get content rect WITHIN QPushButton's styled padding
content = self.style().subElementRect(
QStyle.SE_PushButtonContents,
self._styleOption(),
self
)
pen = QPen(QColor(118, 121, 124))
painter.setPen(pen)
painter.setBrush(self._color)
painter.drawRoundedRect(content, 4, 4)
painter.end()
class PictureButton(QPushButton):
def __init__(self, initial: Optional[str] = None, parent=None, max_size: int = 72):
super().__init__(parent)
self._b64: str = ""
self._max_size = max_size
# Visual setup
self.setFixedSize(max_size + 16, max_size + 24)
self.setStyleSheet("padding: 4px;")
self.setText("Select Logo")
# Initialize from existing config value
if initial:
self._init_from_value(initial)
self.clicked.connect(self._pick)
# ----- public API for Configuration -----
def value(self) -> str:
"""
Return the stored base64 string (or "" if none).
"""
return self._b64
def setValue(self, raw: str):
# Reset visuals first
self._b64 = ""
self.setIcon(QIcon())
self.setText("Select Logo")
if raw:
self._init_from_value(raw)
# ----- internals -----
def _init_from_value(self, raw: str):
raw = raw.strip()
if not raw:
return
# 1) Try as base64
data: Optional[bytes] = None
try:
data = base64.b64decode(raw, validate=True)
except Exception:
data = None
# 2) If not valid base64, treat as path
if data is None:
if os.path.isfile(raw):
try:
with open(raw, "rb") as f:
data = f.read()
except Exception as e:
print(f"[PictureButton] Failed to read logo file '{raw}': {e}")
return
else:
# Unknown format; give up silently
return
# At this point we have `data`
pm = QPixmap()
if not pm.loadFromData(data, "PNG"):
return
self._b64 = base64.b64encode(data).decode("ascii")
self._set_pixmap(pm)
def _pick(self):
path, _ = QFileDialog.getOpenFileName(
self,
"Select Logo",
"",
"PNG Files (*.png)"
)
if not path:
return
try:
with open(path, "rb") as f:
data = f.read()
pm = QPixmap()
if not pm.loadFromData(data, "PNG"):
print(f"[PictureButton] Not a valid PNG: {path}")
return
self._b64 = base64.b64encode(data).decode("ascii")
self._set_pixmap(pm)
except Exception as e:
print(f"[PictureButton] Failed to load logo '{path}': {e}")
def _set_pixmap(self, pm: QPixmap):
scaled = pm.scaled(
self._max_size,
self._max_size,
Qt.KeepAspectRatio,
Qt.SmoothTransformation,
)
self.setIcon(QIcon(scaled))
self.setIconSize(scaled.size())
self.setText("")
self.update()
class FileInput(QWidget):
def __init__(
self,
initial: str = "",
caption: str = "Select File",
directory: str = "",
filter: str = "All Files (*)",
as_base64: bool = False,
on_changed: Optional[Callable[[str], None]] = None,
parent=None,
):
super().__init__(parent)
self._caption = caption
self._directory = directory
self._filter = filter
self._as_base64 = as_base64
self._on_changed = on_changed
self._stored_value: str = initial or ""
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(4)
self._edit = QLineEdit(self)
if not self._as_base64:
if initial:
self._edit.setText(initial)
else:
display = ""
if initial:
if "::" in initial:
fname, _ = initial.split("::", 1)
display = fname
else:
display = "(embedded)"
self._edit.setText(display)
self._btn = QPushButton("...", self)
self._btn.clicked.connect(self._browse)
layout.addWidget(self._edit)
layout.addWidget(self._btn)
def _browse(self):
# Start from configured directory, or from current value's folder
start_dir = self._directory or os.path.dirname(self._edit.text() or "") or ""
path, _ = QFileDialog.getOpenFileName(
self,
self._caption,
start_dir,
self._filter,
)
if path:
self._edit.setText(path)
if self._on_changed:
self._on_changed(path)
def value(self) -> str:
"""
Return either the raw path (default) or a 'filename::base64' value
when as_base64=True.
"""
path_or_name = self._edit.text().strip()
if not self._as_base64:
# Normal mode – return the path from the line edit
return path_or_name
# Base64 mode
# If the text points to an actual file, re-read and encode it
if path_or_name and os.path.isfile(path_or_name):
try:
with open(path_or_name, "rb") as f:
data = f.read()
b64 = base64.b64encode(data).decode("ascii")
fname = os.path.basename(path_or_name)
self._stored_value = f"{fname}::{b64}"
except Exception as e:
print(f"[FileInput] Failed to read '{path_or_name}' for base64: {e}")
# If it's not a real file path, just return the last stored value
return self._stored_value or ""
def setValue(self, value: str):
"""
Update both the stored value and the visible text.
value is expected to be either:
- a path (normal mode), or
- 'filename::base64' / raw base64 (as_base64=True).
"""
if not self._as_base64:
self._edit.setText(value or "")
if self._on_changed:
self._on_changed(value)
return
self._stored_value = value or ""
display = ""
if value:
if "::" in value:
fname, _ = value.split("::", 1)
display = fname
else:
display = "(embedded)"
self._edit.setText(display)
# Only call on_changed if we really want config-file reactions etc.
if self._on_changed:
self._on_changed(value)
class WiFiButton(QPushButton):
def __init__(self, parent=None, label: str = "Connect"):
super().__init__(label, parent)
self._ssid: str = ""
self._tools = None # lazy-loaded network.Tools instance
self.clicked.connect(self._on_click)
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def value(self) -> str:
"""
Return the currently selected SSID (or "" if none).
"""
return self._ssid
def setValue(self, ssid: str):
"""
Set the currently selected SSID and update the button label.
"""
self._ssid = ssid or ""
self.setText(self._ssid or "Connect")
# ------------------------------------------------------------------
# Internals
# ------------------------------------------------------------------
def _ensure_tools(self):
"""
Lazily import and instantiate network.tools.Tools.
"""
if self._tools is not None:
return self._tools
try:
self._tools = Tools()
except Exception as e:
print(f"[WiFiButton] Failed to initialize network Tools: {e}")
self._tools = None
return self._tools
def _on_click(self):
tools = self._ensure_tools()
if tools is None:
MsgBox.show(
parent=self,
title="Wi-Fi",
message="Network tools are not available.",
icon="error",
)
return
# --- 1) Show a small dialog that immediately displays the scanning message ---
dlg = QDialog(self)
dlg.setModal(True)
dlg.setWindowTitle("Wi-Fi Networks")
layout = QVBoxLayout(dlg)
scanning_label = QLabel("Scanning Access Points...")
layout.addWidget(scanning_label)
dlg.show()
QApplication.processEvents()
# Perform the scan (synchronously)
try:
networks = tools.scan_ap()
except Exception as e:
print(f"[WiFiButton] Failed to scan Wi-Fi networks: {e}")
networks = []
# Clear the "Scanning..." UI
while layout.count():
item = layout.takeAt(0)
w = item.widget()
if w is not None:
w.deleteLater()
# --- 2) If no networks found, show a simple message + Close button ---
if not networks:
info = QLabel("No Wi-Fi networks found.")
layout.addWidget(info)
btn_row = QHBoxLayout()
btn_row.addStretch(1)
close_btn = QPushButton("Close", dlg)
close_btn.clicked.connect(dlg.reject)
btn_row.addWidget(close_btn)
layout.addLayout(btn_row)
dlg.exec_()
dlg.deleteLater()
return
# --- 3) Show list of access points + Connect / Cancel buttons ---
list_widget = QListWidget(dlg)
list_widget.addItems(networks)
layout.addWidget(list_widget)
btn_row = QHBoxLayout()
btn_row.addStretch(1)
cancel_btn = QPushButton("Cancel", dlg)
ok_btn = QPushButton("Connect", dlg)
def on_ok():
# Require a selection to accept
if list_widget.currentItem() is not None:
dlg.accept()
cancel_btn.clicked.connect(dlg.reject)
ok_btn.clicked.connect(on_ok)
btn_row.addWidget(cancel_btn)
btn_row.addWidget(ok_btn)
layout.addLayout(btn_row)
def on_item_double_clicked(_item):
dlg.accept()
list_widget.itemDoubleClicked.connect(on_item_double_clicked)
result = dlg.exec_()
selected_ssid = ""
if result == QDialog.Accepted and list_widget.currentItem() is not None:
selected_ssid = list_widget.currentItem().text().strip()
dlg.deleteLater()
self.setValue(selected_ssid)
class StepIndicator(QWidget):
def __init__(self, text: str, parent=None):
super().__init__(parent)
self._state = 'idle'
self.dot = QLabel()
self.dot.setObjectName("statusDot")
self.dot.setFixedSize(16, 16)
self.label = QLabel(text)
lay = QVBoxLayout(self)
lay.setContentsMargins(4, 4, 4, 4)
lay.setSpacing(6)
dot_wrap = QWidget()
dot_wrap.setFixedHeight(20)
dot_lay = QHBoxLayout(dot_wrap)
dot_lay.setContentsMargins(0,0,0,0)
dot_lay.addStretch(1)
dot_lay.addWidget(self.dot, 0, Qt.AlignCenter)
dot_lay.addStretch(1)
lay.addWidget(dot_wrap)
self.label.setAlignment(Qt.AlignCenter)
lay.addWidget(self.label)
self._apply_style()
def set_state(self, state: str):
self._state = state
self._apply_style()
def _apply_style(self):
colors = {
'idle': '#A0A4A8', # grey
'running': '#F5C542', # amber
'ok': '#2FB344', # green
'fail': '#E03131', # red
}
c = colors.get(self._state, '#A0A4A8')
self.dot.setStyleSheet(f"background:{c}; border-radius:7px; border:1px solid rgba(0,0,0,.25);")
class Form:
@staticmethod
def text(text: str = "", placeholder: str = "") -> QLineEdit:
w = QLineEdit()
if text:
w.setText(text)
if placeholder:
w.setPlaceholderText(placeholder)
return w
@staticmethod
def password(text: str = "", placeholder: str = "") -> QLineEdit:
w = QLineEdit()
w.setEchoMode(QLineEdit.Password)
if text:
w.setText(text)
if placeholder:
w.setPlaceholderText(placeholder)
return w
@staticmethod
def checkbox(checked: bool = False) -> QCheckBox:
w = QCheckBox()
w.setChecked(checked)
return w
@staticmethod
def spin(value: int = 0, minimum: int = 0, maximum: int = 65535) -> QSpinBox:
w = QSpinBox()
w.setRange(minimum, maximum)
w.setValue(value)
return w
@staticmethod
def number(value: int = 0, minimum: int = 0, maximum: int = 65535) -> QSpinBox:
w = QSpinBox()
w.setRange(minimum, maximum)
w.setValue(value)
return w
@staticmethod
def integer(value: int = 0, minimum: int = 0, maximum: int = 65535) -> QSpinBox:
w = QSpinBox()
w.setRange(minimum, maximum)
w.setValue(value)
return w
@staticmethod
def select(items: Iterable[str], current: Optional[str] = None) -> QComboBox:
cb = QComboBox()
popup = QListView()
popup.setFrameShape(QFrame.NoFrame)
popup.setFrameShadow(QFrame.Plain)
cb.setView(popup)
vals: List[str] = list(items)
cb.addItems(vals)
if current is not None:
idx = cb.findText(str(current))
if idx >= 0:
cb.setCurrentIndex(idx)
return cb
@staticmethod
def color(initial: str = "#265162") -> ColorButton:
return ColorButton(initial)
@staticmethod
def button(label: str, action: Callable | None, icon: str = "") -> QPushButton:
helper = Helper()
btn = QPushButton(label)
if icon:
icon_path = helper.get_path(f"core/icons/{icon}.svg")
if icon_path:
if helper.file_exists(icon_path):
renderer = QSvgRenderer(icon_path)
pixmap = QPixmap(18, 18)
pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
renderer.render(painter)
painter.end()
icon = QIcon(pixmap)
btn.setIcon(icon)
btn.setIconSize(pixmap.size())
if label:
btn.setText("\u2002" + label)
if action:
btn.clicked.connect(action)
return btn
@staticmethod
def picture(initial: Optional[str] = None) -> PictureButton:
return PictureButton(initial=initial)
@staticmethod
def file(
initial: str = "",
caption: str = "Select File",
directory: str = "",
filter: str = "All Files (*)",
as_base64: bool = False,
on_changed: Optional[Callable[[str], None]] = None,
) -> FileInput:
return FileInput(
initial=initial,
caption=caption,
directory=directory,
filter=filter,
as_base64=as_base64,
on_changed=on_changed,
)
@staticmethod
def wifi(current: str = "") -> WiFiButton:
btn = WiFiButton()
if current:
btn.setValue(current)
return btn