-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUI.py
More file actions
1322 lines (1182 loc) · 67.7 KB
/
UI.py
File metadata and controls
1322 lines (1182 loc) · 67.7 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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import io
import re
import math
import contextlib
from pathlib import Path
from datetime import datetime
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QGridLayout, QLabel, QPushButton, QLineEdit, QComboBox,
QCheckBox, QSpinBox, QDoubleSpinBox, QGroupBox, QTextEdit,
QFileDialog, QProgressBar, QSplitter, QTabWidget, QScrollArea,
QFrame, QSizePolicy, QToolTip, QMessageBox, QAction, QGraphicsOpacityEffect
)
from PyQt5.QtCore import (
Qt, QThread, pyqtSignal, QTimer, QSize, QRectF, QRect,
QPropertyAnimation, QEasingCurve, QPoint
)
from PyQt5.QtGui import (
QColor, QFont, QPainter, QBrush, QPen,
QLinearGradient, QRadialGradient, QDragEnterEvent, QDropEvent,
QTextCursor, QPainterPath, QFontMetrics
)
# ── ultrastack import ─────────────────────────────────────────────────────────
try:
sys.path.insert(0, str(Path(__file__).parent))
import ultrastack as us
ULTRASTACK_AVAILABLE = True
_IMPORT_ERROR = ""
except ImportError as _e:
ULTRASTACK_AVAILABLE = False
_IMPORT_ERROR = str(_e)
DEV_NAME = "Ranasurya Ghosh"
DEV_EMAIL = "ranasuryaghosh@gmail.com"
DEV_GITHUB = "github.com/NuclearVenom"
# ══════════════════════════════════════════════════════════════════════════════
# PALETTE
# ══════════════════════════════════════════════════════════════════════════════
C = {
"bg": "#0d0f14",
"surface": "#13161e",
"surface2": "#1a1e2a",
"surface3": "#222736",
"border": "#2a2f3d",
"border_hi": "#3d4560",
"accent": "#4f7cff",
"accent_glow": "#2d4cb8",
"accent2": "#7c4fff",
"success": "#3ecf8e",
"warning": "#f5a623",
"danger": "#e05252",
"text": "#dde2f0",
"text_dim": "#6b748f",
"text_bright": "#ffffff",
}
STYLESHEET = f"""
QWidget {{
background-color: {C['bg']};
color: {C['text']};
font-family: 'Segoe UI', 'SF Pro Display', 'Helvetica Neue', Arial, sans-serif;
font-size: 14px;
}}
QMainWindow {{ background-color: {C['bg']}; }}
QSplitter::handle {{ background: {C['border']}; width: 2px; height: 2px; }}
QGroupBox {{
background-color: {C['surface']};
border: 1px solid {C['border']};
border-radius: 10px;
margin-top: 16px;
padding: 14px 12px 12px 12px;
font-size: 12px; font-weight: 600;
color: {C['text_dim']}; letter-spacing: 0.8px;
}}
QGroupBox::title {{
subcontrol-origin: margin; subcontrol-position: top left;
padding: 2px 10px; color: {C['text_dim']}; background: transparent;
}}
QTabWidget::pane {{
border: 1px solid {C['border']}; border-radius: 8px;
background: {C['surface']}; margin-top: -1px;
}}
QTabBar::tab {{
background: {C['surface2']}; color: {C['text_dim']};
border: 1px solid {C['border']}; border-bottom: none;
border-radius: 6px 6px 0 0; padding: 8px 16px;
margin-right: 2px; font-size: 13px; font-weight: 500;
}}
QTabBar::tab:selected {{ background: {C['surface']}; color: {C['text']}; border-color: {C['border_hi']}; }}
QTabBar::tab:hover:!selected {{ background: {C['surface3']}; color: {C['text']}; }}
QPushButton {{
background-color: {C['surface3']}; color: {C['text']};
border: 1px solid {C['border']}; border-radius: 7px;
padding: 8px 16px; font-size: 13px; font-weight: 500;
}}
QPushButton:hover {{ background-color: {C['border_hi']}; border-color: {C['accent']}; color: {C['text_bright']}; }}
QPushButton:pressed {{ background-color: {C['accent_glow']}; }}
QPushButton:disabled {{ background-color: {C['surface']}; color: {C['text_dim']}; border-color: {C['border']}; }}
QPushButton#danger {{ background: {C['surface3']}; color: {C['danger']}; border: 1px solid {C['danger']}; }}
QPushButton#danger:hover {{ background: {C['danger']}; color: white; }}
QLineEdit, QTextEdit {{
background-color: {C['surface2']}; color: {C['text']};
border: 1px solid {C['border']}; border-radius: 7px;
padding: 7px 10px; selection-background-color: {C['accent']};
}}
QLineEdit:focus, QTextEdit:focus {{ border-color: {C['accent']}; }}
QLineEdit:hover {{ border-color: {C['border_hi']}; }}
QComboBox {{
background-color: {C['surface2']}; color: {C['text']};
border: 1px solid {C['border']}; border-radius: 7px; padding: 7px 10px;
}}
QComboBox:hover {{ border-color: {C['border_hi']}; }}
QComboBox:focus {{ border-color: {C['accent']}; }}
QComboBox::drop-down {{ border: none; width: 24px; }}
QComboBox::down-arrow {{
border-left: 4px solid transparent; border-right: 4px solid transparent;
border-top: 6px solid {C['text_dim']}; margin-right: 8px;
}}
QComboBox QAbstractItemView {{
background-color: {C['surface2']}; color: {C['text']};
border: 1px solid {C['border_hi']}; border-radius: 6px;
selection-background-color: {C['accent']}; outline: none;
}}
QSpinBox, QDoubleSpinBox {{
background-color: {C['surface2']}; color: {C['text']};
border: 1px solid {C['border']}; border-radius: 7px; padding: 6px 8px;
}}
QSpinBox:focus, QDoubleSpinBox:focus {{ border-color: {C['accent']}; }}
QSpinBox::up-button, QSpinBox::down-button,
QDoubleSpinBox::up-button, QDoubleSpinBox::down-button {{
background: {C['surface3']}; border: none; border-radius: 3px; width: 18px;
}}
QCheckBox {{ color: {C['text']}; spacing: 10px; font-size: 14px; }}
QCheckBox::indicator {{
width: 18px; height: 18px; border: 2px solid {C['border_hi']};
border-radius: 5px; background: {C['surface2']};
}}
QCheckBox::indicator:checked {{ background: {C['accent']}; border-color: {C['accent']}; }}
QCheckBox::indicator:hover {{ border-color: {C['accent']}; }}
QScrollArea {{ border: none; background: transparent; }}
QScrollBar:vertical {{ background: {C['surface']}; width: 7px; margin: 0; }}
QScrollBar::handle:vertical {{ background: {C['border_hi']}; border-radius: 3px; min-height: 30px; }}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{ height: 0; }}
QScrollBar:horizontal {{ background: {C['surface']}; height: 7px; }}
QScrollBar::handle:horizontal {{ background: {C['border_hi']}; border-radius: 3px; }}
QProgressBar {{
background-color: {C['surface2']}; border: 1px solid {C['border']};
border-radius: 6px; height: 10px; text-align: center;
font-size: 11px; color: {C['text_dim']};
}}
QProgressBar::chunk {{
background: qlineargradient(x1:0,y1:0,x2:1,y2:0,stop:0 {C['accent']},stop:1 {C['accent2']});
border-radius: 5px;
}}
QStatusBar {{
background: {C['surface']}; color: {C['text_dim']};
border-top: 1px solid {C['border']}; font-size: 12px; padding: 2px 8px;
}}
QToolTip {{
background-color: {C['surface3']}; color: {C['text']};
border: 1px solid {C['accent']}; border-radius: 6px;
padding: 7px 11px; font-size: 12px;
}}
QLabel {{ background: transparent; color: {C['text']}; }}
QLabel#title {{ font-size: 25px; font-weight: 700; color: {C['text_bright']}; letter-spacing: 2px; }}
QLabel#subtitle {{ font-size: 13px; color: #a0aac8; letter-spacing: 0.4px; }}
QLabel#sectionhead {{ font-size: 11px; font-weight: 700; color: {C['text_dim']}; letter-spacing: 1.2px; }}
QTextEdit#console {{
background: #080a0f; color: #a0c4ff;
border: 1px solid {C['border']}; border-radius: 8px;
font-family: 'Cascadia Code','Fira Code','JetBrains Mono','Consolas',monospace;
font-size: 12px; padding: 10px;
}}
QTextEdit#syslog {{
background: #070810; color: {C['text_dim']};
border: 1px solid {C['border']}; border-radius: 6px;
font-family: 'Cascadia Code','Fira Code','Consolas',monospace;
font-size: 12px; padding: 8px;
}}
QLabel#dropzone {{
background-color: {C['surface2']}; border: 2px dashed {C['border_hi']};
border-radius: 10px; color: {C['text_dim']}; font-size: 13px; padding: 18px;
}}
QLabel#dropzone:hover {{
border-color: {C['accent']}; color: {C['text']}; background-color: {C['surface3']};
}}
QFrame[frameShape="4"], QFrame[frameShape="5"] {{ color: {C['border']}; }}
QMenuBar {{ background: {C['surface']}; border-bottom: 1px solid {C['border']}; }}
QMenuBar::item {{ padding: 6px 12px; color: {C['text_dim']}; }}
QMenuBar::item:selected {{ background: {C['surface3']}; color: {C['text']}; }}
QMenu {{
background: {C['surface2']}; border: 1px solid {C['border_hi']};
border-radius: 8px; padding: 4px;
}}
QMenu::item {{ padding: 8px 20px; border-radius: 5px; color: {C['text']}; }}
QMenu::item:selected {{ background: {C['accent']}; color: white; }}
"""
# ══════════════════════════════════════════════════════════════════════════════
# HELPERS
# ══════════════════════════════════════════════════════════════════════════════
def tip(w, text: str):
w.setToolTip(text); w.setToolTipDuration(9000)
def labeled_row(label_text: str, widget, tip_text: str = "",
label_width: int = 145) -> QHBoxLayout:
row = QHBoxLayout()
lbl = QLabel(label_text)
lbl.setFixedWidth(label_width)
lbl.setStyleSheet(f"color:{C['text_dim']}; font-size:13px;")
row.addWidget(lbl); row.addWidget(widget, 1)
if tip_text: tip(widget, tip_text); tip(lbl, tip_text)
return row
def section_label(text: str) -> QLabel:
lbl = QLabel(text); lbl.setObjectName("sectionhead"); return lbl
def h_line() -> QFrame:
f = QFrame(); f.setFrameShape(QFrame.HLine); f.setFrameShadow(QFrame.Sunken); return f
# ══════════════════════════════════════════════════════════════════════════════
# SPLASH SCREEN
# ══════════════════════════════════════════════════════════════════════════════
class SplashScreen(QWidget):
done = pyqtSignal()
W, H = 550, 300
MARGIN = 0
TITLE_Y = 138
STATUS_TOP = 180
LINE_H = 26
MAX_LINES = 5
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setFixedSize(self.W, self.H)
screen = QApplication.primaryScreen().geometry()
self.move(screen.center().x() - self.W // 2,
screen.center().y() - self.H // 2)
import random
rng = random.Random(7)
# (x, y, drift_speed, base_brightness, twinkle_range, phase)
self._stars = [
(rng.uniform(0, self.W),
rng.uniform(0, self.H),
rng.uniform(0.10, 0.45),
rng.randint(50, 120),
rng.randint(0, 35),
rng.uniform(0, 6.28))
for _ in range(120)
]
self._tick_n = 0
self._pulse = 0.0
self._pulse_d = 1
self._lines = [] # list of (full_text, chars_shown)
self._type_idx = -1 # index of line being typed
self._type_pos = 0
self._cur_vis = True # cursor blink state
self._fade = 1.0
self._frame_t = QTimer(self)
self._frame_t.timeout.connect(self._frame_tick)
self._frame_t.start(22)
self._type_t = QTimer(self)
self._type_t.timeout.connect(self._type_tick)
self._type_t.start(28)
self._cur_t = QTimer(self)
self._cur_t.timeout.connect(self._cur_tick)
self._cur_t.start(520)
self._fade_t = QTimer(self)
self._fade_t.timeout.connect(self._fade_tick)
# ── ticks ─────────────────────────────────────────────────────────────────
def _frame_tick(self):
self._tick_n += 1
drifted = []
for x, y, spd, bb, br, ph in self._stars:
y = (y + spd) % (self.H + 4)
drifted.append((x, y, spd, bb, br, ph))
self._stars = drifted
self._pulse += 0.022 * self._pulse_d
if self._pulse >= 1.0: self._pulse_d = -1
if self._pulse <= 0.0: self._pulse_d = 1
self.update()
def _type_tick(self):
if 0 <= self._type_idx < len(self._lines):
full, shown = self._lines[self._type_idx]
if shown < len(full):
self._lines[self._type_idx] = (full, shown + 1)
self.update()
def _cur_tick(self):
self._cur_vis = not self._cur_vis
self.update()
def _fade_tick(self):
self._fade -= 0.055
if self._fade <= 0.0:
self._fade = 0.0
self._fade_t.stop()
self._frame_t.stop()
self._type_t.stop()
self._cur_t.stop()
self.done.emit()
self.hide()
self.update()
# ── public ────────────────────────────────────────────────────────────────
def set_status(self, text: str):
self._lines.append((text, 0))
if len(self._lines) > self.MAX_LINES:
self._lines = self._lines[-self.MAX_LINES:]
self._type_idx = len(self._lines) - 1
self._type_pos = 0
self.update()
def fade_out(self):
self._fade_t.start(18)
# ── paint ─────────────────────────────────────────────────────────────────
def paintEvent(self, _):
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
p.setOpacity(self._fade)
w, h = self.W, self.H
# Rounded clipping path
radius = 10
path = QPainterPath()
path.addRoundedRect(QRectF(0, 0, w, h), radius, radius)
p.setClipPath(path)
# Pure black background
p.setPen(Qt.NoPen)
p.setBrush(QBrush(QColor("#000000")))
p.drawRoundedRect(QRectF(0, 0, w, h), radius, radius)
# Drifting micro-stars
for x, y, spd, bb, br, ph in self._stars:
twinkle = int(br * math.sin(ph + self._tick_n * 0.05))
bright = max(28, min(185, bb + twinkle))
r = 0.65 if spd < 0.22 else 0.4
col = QColor(bright, bright, bright + 12)
p.setPen(col)
p.setBrush(QBrush(col))
p.drawEllipse(QRectF(x - r, y - r, r * 2, r * 2))
# Soft glow halo behind title
glow_a = int(16 + 10 * self._pulse)
glow = QRadialGradient(w / 2, self.TITLE_Y, 140)
glow.setColorAt(0.0, QColor(55, 95, 255, glow_a))
glow.setColorAt(1.0, QColor(55, 95, 255, 0))
p.setPen(Qt.NoPen)
p.setBrush(QBrush(glow))
p.drawEllipse(QRectF(w / 2 - 140, self.TITLE_Y - 42, 280, 84))
# ULTRASTACK title
tf = QFont("Segoe UI", 28, QFont.Bold)
tf.setLetterSpacing(QFont.AbsoluteSpacing, 5)
p.setFont(tf)
# soft glow layer
p.setPen(QColor(90, 140, 255, 45))
p.drawText(QRect(2, self.TITLE_Y - 22, w, 44),
Qt.AlignHCenter | Qt.AlignVCenter, "ULTRASTACK")
# crisp white layer
p.setPen(QColor(230, 236, 255))
p.drawText(QRect(0, self.TITLE_Y - 22, w, 44),
Qt.AlignHCenter | Qt.AlignVCenter, "ULTRASTACK")
# Thin gradient underline
ul_w = 110
ul_x = (w - ul_w) // 2
ul_y = self.TITLE_Y + 25
ul_g = QLinearGradient(ul_x, 0, ul_x + ul_w, 0)
ul_g.setColorAt(0.0, QColor(79, 124, 255, 0))
ul_g.setColorAt(0.5, QColor(79, 124, 255, 160))
ul_g.setColorAt(1.0, QColor(79, 124, 255, 0))
p.setPen(QPen(QBrush(ul_g), 1))
p.drawLine(ul_x, ul_y, ul_x + ul_w, ul_y)
# Status lines — typewritten, left-aligned
sf = QFont("Segoe UI", 11)
p.setFont(sf)
for i, (full_text, shown) in enumerate(self._lines):
yp = self.STATUS_TOP + i * self.LINE_H
is_active = (i == len(self._lines) - 1)
age = len(self._lines) - 1 - i
if is_active:
text_col = QColor(C["accent"])
else:
a = max(55, 175 - age * 38)
text_col = QColor(110, 135, 175, a)
# bullet
p.setPen(QColor(C["border_hi"]))
p.drawText(QRect(self.MARGIN, yp, 16, self.LINE_H),
Qt.AlignLeft | Qt.AlignVCenter, "›")
# revealed text
visible = full_text[:shown]
p.setPen(text_col)
p.drawText(QRect(self.MARGIN + 18, yp, w - self.MARGIN - 28, self.LINE_H),
Qt.AlignLeft | Qt.AlignVCenter, visible)
# blinking cursor on active line while still typing
if is_active and shown < len(full_text) and self._cur_vis:
fm = p.fontMetrics()
tx_w = fm.horizontalAdvance(visible)
p.setPen(QColor(C["accent"]))
p.drawText(QRect(self.MARGIN + 18 + tx_w + 2, yp, 14, self.LINE_H),
Qt.AlignLeft | Qt.AlignVCenter, "▌")
# Developer credit — bottom-left, clearly visible
cf = QFont("Segoe UI", 10)
p.setFont(cf)
p.setPen(QColor(165, 175, 200, 210))
p.drawText(QRect(self.MARGIN, h - 30, w, 28),
Qt.AlignRight, f"Created by {DEV_NAME} ")
# ══════════════════════════════════════════════════════════════════════════════
# ANIMATED GRADIENT HEADER
# ══════════════════════════════════════════════════════════════════════════════
class GradientHeader(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedHeight(90)
self._t = 0.0
t = QTimer(self); t.timeout.connect(self._tick); t.start(40)
def _tick(self):
self._t = (self._t + 0.003) % 1.0; self.update()
def paintEvent(self, _):
p = QPainter(self); p.setRenderHint(QPainter.Antialiasing)
g = QLinearGradient(0, 0, self.width(), 0)
o = self._t
g.setColorAt((o + 0.00) % 1.0, QColor("#0d0f14"))
g.setColorAt((o + 0.25) % 1.0, QColor("#141840"))
g.setColorAt((o + 0.50) % 1.0, QColor("#1e3080"))
g.setColorAt((o + 0.75) % 1.0, QColor("#141840"))
g.setColorAt(1.0, QColor("#0d0f14"))
p.fillRect(self.rect(), QBrush(g))
pen = QPen(QColor("#4f7cff44")); pen.setWidth(1); p.setPen(pen)
p.drawLine(0, self.height() - 1, self.width(), self.height() - 1)
# ══════════════════════════════════════════════════════════════════════════════
# WAVE SHIMMER RUN BUTTON
# ══════════════════════════════════════════════════════════════════════════════
class WaveRunButton(QPushButton):
def __init__(self, text: str, parent=None):
super().__init__(text, parent)
self.setFlat(True)
self.setCursor(Qt.PointingHandCursor)
self.setFixedSize(220, 48)
self._wave = 0.0
self._hover = False
self._down = False
t = QTimer(self); t.timeout.connect(self._tick); t.start(20)
def _tick(self):
self._wave = (self._wave + 0.005) % 1.0; self.update()
def paintEvent(self, _):
p = QPainter(self); p.setRenderHint(QPainter.Antialiasing)
w, h = self.width(), self.height()
clip = QPainterPath()
clip.addRoundedRect(QRectF(0, 0, w, h), 10, 10)
p.setClipPath(clip)
if self._down:
c1, c2 = QColor("#253880"), QColor("#4a2a90")
elif self._hover:
c1, c2 = QColor("#6090ff"), QColor("#9a60ff")
else:
c1, c2 = QColor("#4f7cff"), QColor("#7c4fff")
bg = QLinearGradient(0, 0, w, 0)
bg.setColorAt(0.0, c1); bg.setColorAt(1.0, c2)
p.fillPath(clip, QBrush(bg))
cx = self._wave * (w + 140) - 70
alpha = 60 if not self._hover else 90
sh = QLinearGradient(cx - 70, 0, cx + 70, 0)
sh.setColorAt(0.00, QColor(255, 255, 255, 0))
sh.setColorAt(0.40, QColor(255, 255, 255, 0))
sh.setColorAt(0.50, QColor(255, 255, 255, alpha))
sh.setColorAt(0.60, QColor(255, 255, 255, 0))
sh.setColorAt(1.00, QColor(255, 255, 255, 0))
p.fillPath(clip, QBrush(sh))
p.setClipping(False)
p.setPen(QColor("#ffffff") if self.isEnabled() else QColor("#66666666"))
f = self.font(); f.setBold(True); f.setPointSize(11); p.setFont(f)
p.drawText(QRect(0, 0, w, h), Qt.AlignCenter, self.text())
def enterEvent(self, e): self._hover = True; self.update(); super().enterEvent(e)
def leaveEvent(self, e): self._hover = False; self.update(); super().leaveEvent(e)
def mousePressEvent(self, e): self._down = True; self.update(); super().mousePressEvent(e)
def mouseReleaseEvent(self, e): self._down = False; self.update(); super().mouseReleaseEvent(e)
# ══════════════════════════════════════════════════════════════════════════════
# DRAG-AND-DROP ZONE
# ══════════════════════════════════════════════════════════════════════════════
class DropZone(QLabel):
dropped = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("dropzone"); self.setAlignment(Qt.AlignCenter)
self.setAcceptDrops(True); self.setMinimumHeight(80); self._idle()
def _idle(self):
self.setText("⬇ Drag & drop a folder, video, or .ser file here\n"
" — or use the Browse buttons below —")
def dragEnterEvent(self, e):
if e.mimeData().hasUrls():
e.acceptProposedAction()
self.setStyleSheet(
f"background:{C['surface3']}; border:2px dashed {C['accent']};"
f"border-radius:10px; color:{C['text']}; font-size:13px; padding:18px;")
self.setText(" ✓ Release to load")
def dragLeaveEvent(self, _): self.setStyleSheet(""); self._idle()
def dropEvent(self, e):
urls = e.mimeData().urls()
if urls: self.dropped.emit(urls[0].toLocalFile())
self.setStyleSheet(""); self._idle()
# ══════════════════════════════════════════════════════════════════════════════
# WORKER THREAD
# ══════════════════════════════════════════════════════════════════════════════
class WorkerThread(QThread):
log_line = pyqtSignal(str)
finished = pyqtSignal(bool, str)
def __init__(self, cfg: dict):
super().__init__(); self.cfg = cfg
def run(self):
if not ULTRASTACK_AVAILABLE:
self.finished.emit(False, f"Cannot import ultrastack:\n{_IMPORT_ERROR}"); return
cfg = self.cfg
class Tee(io.StringIO):
def __init__(self, sig): super().__init__(); self._s = sig
def write(self, s):
if s.strip(): self._s.emit(s.rstrip())
return len(s)
def flush(self): pass
tee = Tee(self.log_line)
self.log_line.emit("═" * 58)
self.log_line.emit(f" UltraStack — {datetime.now().strftime('%H:%M:%S')}")
if cfg.get("lite"): self.log_line.emit(" ⚡ QUICK STACK mode active")
self.log_line.emit("═" * 58)
try:
master_dark = None
if cfg.get("dark"):
with contextlib.redirect_stdout(tee):
master_dark = us.make_master_dark(cfg["dark"])
device = cfg["_device"]; torch_mod = cfg["_torch"]
input_path = Path(cfg["input"]); ext = input_path.suffix.lower()
self.log_line.emit(f" Input : {input_path}")
self.log_line.emit(f" Output : {cfg['output']}")
if cfg.get("lite"):
with contextlib.redirect_stdout(tee):
self._run_lite(cfg, input_path, ext, master_dark)
else:
common = dict(
output_path = cfg["output"],
stack_mode = cfg["mode"],
align_method = cfg["align"],
enhance = cfg["enhance"],
stretch = cfg["stretch"],
master_dark = master_dark,
hot_pixel_thresh = cfg["hot_pixels"],
device = device,
torch_module = torch_mod,
)
with contextlib.redirect_stdout(tee):
if input_path.is_dir():
us.run_folder_pipeline(
folder_path=str(input_path), stitch=cfg["stitch"],
stack_threshold=cfg["threshold"],
sigma_low=cfg["sigma_low"], sigma_high=cfg["sigma_high"],
sigma_iters=cfg["sigma_iters"], **common)
elif ext == ".ser":
us.run_ser_pipeline(
ser_path=str(input_path), frame_skip=cfg["skip"],
max_frames=cfg["max_frames"] or None,
sigma_low=cfg["sigma_low"], sigma_high=cfg["sigma_high"],
sigma_iters=cfg["sigma_iters"], **common)
elif ext in us.VIDEO_EXTENSIONS:
us.run_video_pipeline(
video_path=str(input_path), frame_skip=cfg["skip"],
max_frames=cfg["max_frames"] or None, **common)
else:
raise ValueError(f"Unsupported input: {input_path}")
self.finished.emit(True, cfg["output"])
except Exception as exc:
import traceback
self.log_line.emit(f"\n ✗ ERROR: {exc}")
self.log_line.emit(traceback.format_exc())
self.finished.emit(False, str(exc))
def _run_lite(self, cfg, input_path, ext, master_dark):
import numpy as np, cv2
skip_align = cfg.get("lite_skip_align", False)
out_path = cfg["output"]
self.log_line.emit(
f" Align: {'none' if skip_align else 'ORB'} | Mode: average | Enhance: off")
if input_path.is_dir():
_, paths = us.detect_folder_format(str(input_path))
self.log_line.emit(f" Found {len(paths)} images")
images = us.load_images_parallel(paths)
elif ext == ".ser":
ser = us.SERFile(str(input_path)); images = []
for i, (_, frm) in enumerate(ser.frames(cfg.get("skip", 1),
cfg.get("max_frames") or None)):
images.append(frm)
if (i+1) % 100 == 0: self.log_line.emit(f" Read {i+1} SER frames…")
ser.close()
elif ext in us.VIDEO_EXTENSIONS:
cap = cv2.VideoCapture(str(input_path)); images = []
skip = cfg.get("skip", 1); maxf = cfg.get("max_frames") or None; fi = 0
while True:
ret, frm = cap.read()
if not ret: break
if fi % skip == 0:
images.append(frm)
if len(images) % 100 == 0: self.log_line.emit(f" Read {len(images)} frames…")
fi += 1
if maxf and len(images) >= maxf: break
cap.release()
else:
raise ValueError(f"Unsupported: {input_path}")
if not images: raise ValueError("No frames loaded")
if master_dark is not None:
self.log_line.emit(" Subtracting dark…")
images = [us.subtract_dark(im, master_dark) for im in images]
if not skip_align and len(images) > 1:
self.log_line.emit(f" Aligning {len(images)} frames…")
base_gray = cv2.cvtColor(images[0], cv2.COLOR_BGR2GRAY)
aligned = [images[0]]
for i, img in enumerate(images[1:], 1):
aligned.append(us.align_frame(base_gray, img, "orb"))
if i % 50 == 0: self.log_line.emit(f" Aligned {i}/{len(images)-1}…")
images = aligned
self.log_line.emit(f" Stacking {len(images)} frames…")
acc = images[0].astype("float64")
for k, img in enumerate(images[1:], 1):
acc += (img.astype("float64") - acc) / (k + 1)
if k % 100 == 0: self.log_line.emit(f" Stacked {k+1}/{len(images)}…")
result = np.clip(acc, 0, 255).astype("uint8")
lite_fmt = cfg.get("lite_fmt", "jpg")
p = Path(out_path)
if p.suffix.lower().lstrip(".") != lite_fmt:
out_path = str(p.parent / f"{p.stem}_quick.{lite_fmt}")
cfg["output"] = out_path
us.save_output(result, out_path)
us.print_image_stats(result, out_path)
# ══════════════════════════════════════════════════════════════════════════════
# GPU PROBE
# ══════════════════════════════════════════════════════════════════════════════
class GPUProbeThread(QThread):
result = pyqtSignal(str, str, object, object)
status = pyqtSignal(str) # incremental status for splash
def run(self):
self.status.emit("Probing GPU… Please wait")
try:
self.status.emit("Loading PyTorch…")
device, torch_mod = (
us.setup_device(force_cpu=False)
if ULTRASTACK_AVAILABLE else ("cpu", None)
)
if device == "cuda":
import torch
self.status.emit("Reading GPU properties…")
name = torch.cuda.get_device_name(0)
vram = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)
self.result.emit(f"✓ {name} ({vram:.1f} GB)", "ok", device, torch_mod)
else:
self.result.emit("⚠ No CUDA GPU — CPU mode", "warn", device, torch_mod)
except Exception as e:
self.result.emit(f"✗ {e}", "err", "cpu", None)
# ══════════════════════════════════════════════════════════════════════════════
# MAIN WINDOW
# ══════════════════════════════════════════════════════════════════════════════
class UltraStackGUI(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("UltraStack v2 — Astronomical Image Stacking")
self.setMinimumSize(1100, 720)
self.resize(1320, 860)
self._device = "cpu"
self._torch = None
self._worker = None
self._build_ui()
# ── Splash screen + GPU probe ─────────────────────────────────────────
self._splash = SplashScreen()
self._splash.show()
self.hide() # keep main window hidden until splash finishes
self._probe = GPUProbeThread()
self._probe.status.connect(self._splash.set_status)
self._probe.result.connect(self._on_gpu_result)
self._probe.start()
# ── GPU result arrives ────────────────────────────────────────────────────
def _on_gpu_result(self, text, kind, device, torch_mod):
self._device = device
self._torch = torch_mod
cols = {"ok": C["success"], "warn": C["warning"], "err": C["danger"]}
col = cols.get(kind, C["text_dim"])
# Update badge — GPU status only (no error text dumped into header)
self._gpu_badge.setStyleSheet(
f"color:{col}; font-size:12px; font-weight:600; background:transparent;")
badge_icons = {"ok": "● GPU", "warn": "● CPU", "err": "● CPU"}
self._gpu_badge.setText(badge_icons.get(kind, "●"))
if kind == "ok":
import torch
name = torch.cuda.get_device_name(0)
vram = torch.cuda.get_device_properties(0).total_memory / (1024**3)
self._gpu_detail.setText(f"{name} · {vram:.1f} GB VRAM")
self._gpu_detail.setStyleSheet(f"color:{C['success']}; font-size:11px; background:transparent;")
elif kind == "warn":
self._gpu_detail.setText("No CUDA GPU — running on CPU")
self._gpu_detail.setStyleSheet(f"color:{C['warning']}; font-size:11px; background:transparent;")
else:
# Error: show brief note in detail line only — NOT in the banner
self._gpu_detail.setText("GPU unavailable — CPU mode active")
self._gpu_detail.setStyleSheet(f"color:{C['text_dim']}; font-size:11px; background:transparent;")
# Route full error message to system log only
icon = {"ok": "✓", "warn": "⚠", "err": "✗"}.get(kind, "•")
self._sys_append(f"{icon} {text}", col)
if kind == "err":
self._sys_append(
" Likely cause: PyTorch CUDA build does not match your\n"
" installed CUDA version (e.g. torch+cu121 on CUDA 12.4).\n"
" Fix: pytorch.org → Get Started → correct CUDA build.\n"
" UltraStack runs fully on CPU — no action required.",
C["text_dim"])
self._syslog_panel.setVisible(True)
elif kind == "warn":
self._syslog_panel.setVisible(True)
self.statusBar().showMessage(f" {text}")
# Fade splash, show main window
self._splash.set_status("Ready!" if kind == "ok" else
"CPU mode — ready!" if kind == "warn" else
"GPU unavailable — CPU mode ready")
QTimer.singleShot(600, self._finish_splash)
def _finish_splash(self):
self._splash.done.connect(self._show_main)
self._splash.fade_out()
def _show_main(self):
self.show()
self.raise_()
# ── Build UI ──────────────────────────────────────────────────────────────
def _build_ui(self):
cw = QWidget(); self.setCentralWidget(cw)
root = QVBoxLayout(cw); root.setContentsMargins(0, 0, 0, 0); root.setSpacing(0)
self._build_menu()
root.addWidget(self._build_header())
sp = QSplitter(Qt.Horizontal)
sp.setHandleWidth(3); sp.setChildrenCollapsible(False)
sp.addWidget(self._build_left()); sp.addWidget(self._build_right())
sp.setSizes([700, 440])
root.addWidget(sp, 1)
root.addWidget(self._build_bottom_bar())
# ── Menu ──────────────────────────────────────────────────────────────────
def _build_menu(self):
mb = self.menuBar()
fm = mb.addMenu("File")
a = QAction("Open Input…", self); a.triggered.connect(self._browse_input); fm.addAction(a)
a2 = QAction("Quit", self); a2.triggered.connect(self.close); fm.addAction(a2)
hm = mb.addMenu("Help")
a3 = QAction("About UltraStack", self); a3.triggered.connect(self._show_about); hm.addAction(a3)
# ── Header ────────────────────────────────────────────────────────────────
def _build_header(self) -> QWidget:
hdr = GradientHeader()
lay = QHBoxLayout(hdr); lay.setContentsMargins(28, 0, 20, 0)
# Left: title + subtitle
title = QLabel("ULTRASTACK"); title.setObjectName("title"); title.setStyleSheet("font-size:38px")
sub = QLabel("Both GPU & CPU Compatible Image Stacking for Astronomical or Casual use"); sub.setObjectName("subtitle"); sub.setStyleSheet("font-size:14px")
lv = QVBoxLayout(); lv.setSpacing(3)
lv.addWidget(title); lv.addWidget(sub)
# Centre: GPU status badge (just a coloured dot + label — no error text)
self._gpu_badge = QLabel("● Probing…")
self._gpu_badge.setStyleSheet(
f"color:{C['warning']}; font-size:12px; font-weight:600; background:transparent;")
self._gpu_badge.setAlignment(Qt.AlignCenter)
self._gpu_detail = QLabel("")
self._gpu_detail.setStyleSheet(
f"color:{C['text_dim']}; font-size:11px; background:transparent;")
self._gpu_detail.setAlignment(Qt.AlignCenter)
gpu_col = QVBoxLayout(); gpu_col.setSpacing(1)
gpu_col.addWidget(self._gpu_badge); gpu_col.addWidget(self._gpu_detail)
# Right: developer info
dev = QLabel("Developed by,")
dev.setStyleSheet(
f"color:{C['text_dim']}; font-size:12px; background:transparent;")
dev.setAlignment(Qt.AlignRight)
dev_name_lbl = QLabel(DEV_NAME)
dev_name_lbl.setStyleSheet(
f"color:{C['text_dim']}; font-size:16px; font-weight:600; background:transparent;")
dev_name_lbl.setAlignment(Qt.AlignRight)
dev_email_lbl = QLabel(DEV_EMAIL)
dev_email_lbl.setStyleSheet(
f"color:{C['text_dim']}; font-size:14px; background:transparent;")
dev_email_lbl.setAlignment(Qt.AlignRight)
dev_github_lbl = QLabel(DEV_GITHUB)
dev_github_lbl.setStyleSheet(
f"color:{C['accent']}; font-size:14px; background:transparent;")
dev_github_lbl.setAlignment(Qt.AlignRight)
dev_col = QVBoxLayout(); dev_col.setSpacing(1)
dev_col.addWidget(dev)
dev_col.addWidget(dev_name_lbl)
dev_col.addWidget(dev_email_lbl)
dev_col.addWidget(dev_github_lbl)
lay.addLayout(lv)
lay.addStretch()
lay.addLayout(gpu_col)
lay.addSpacing(30)
lay.addLayout(dev_col)
return hdr
# ── Left ──────────────────────────────────────────────────────────────────
def _build_left(self) -> QWidget:
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
w = QWidget(); lay = QVBoxLayout(w)
lay.setContentsMargins(16, 14, 10, 14); lay.setSpacing(12)
lay.addWidget(self._build_io_group())
lay.addWidget(self._build_tabs())
lay.addStretch()
scroll.setWidget(w); return scroll
# ── I/O group ─────────────────────────────────────────────────────────────
def _build_io_group(self) -> QGroupBox:
box = QGroupBox("Input / Output"); lay = QVBoxLayout(box); lay.setSpacing(9)
self._drop = DropZone(); self._drop.dropped.connect(self._on_drop); lay.addWidget(self._drop)
self._inp = QLineEdit()
self._inp.setPlaceholderText("Paste path to folder, video (.mp4, .avi…), or .ser file…")
tip(self._inp,
"Enter the full path to:\n"
"• A folder of images (JPG / PNG / TIFF / FITS / BMP / WEBP)\n"
"• A video file (MP4, AVI, MOV, MKV, TS, …)\n"
"• A SER file (astronomical capture — FireCapture, SharpCap)\n\n"
"Tip: drag & drop the folder or file into the zone above.")
self._inp.textChanged.connect(self._on_input_changed)
bi = QPushButton("📁 Browse"); tip(bi, "Open a file/folder picker"); bi.clicked.connect(self._browse_input)
ri = QHBoxLayout(); ri.addWidget(QLabel("Input:")); ri.addWidget(self._inp, 1); ri.addWidget(bi); lay.addLayout(ri)
self._out = QLineEdit()
self._out.setPlaceholderText("Output filename (e.g. stacked.tif or result.jpg)")
tip(self._out,
"Output file path. Extension controls format:\n"
" .jpg / .jpeg → JPEG quality 97\n"
" .png → Lossless PNG\n"
" .tif / .tiff → 16-bit TIFF (best for astro post-processing)")
bo = QPushButton("💾 Save as"); tip(bo, "Choose output path"); bo.clicked.connect(self._browse_output)
ro = QHBoxLayout(); ro.addWidget(QLabel("Output:")); ro.addWidget(self._out, 1); ro.addWidget(bo); lay.addLayout(ro)
self._dark = QLineEdit()
self._dark.setPlaceholderText("Optional: folder of dark calibration frames…")
tip(self._dark,
"Dark frames (same ISO/gain, exposure, temperature).\n"
"Median-stacked into a master dark and subtracted from every light.")
bd = QPushButton("🌑 Dark folder"); tip(bd, "Select dark calibration folder"); bd.clicked.connect(self._browse_dark)
rd = QHBoxLayout(); rd.addWidget(QLabel("Darks:")); rd.addWidget(self._dark, 1); rd.addWidget(bd); lay.addLayout(rd)
return box
# ── Tabs ──────────────────────────────────────────────────────────────────
def _build_tabs(self) -> QTabWidget:
tabs = QTabWidget()
tabs.addTab(self._tab_stacking(), "⚗ Stacking")
tabs.addTab(self._tab_alignment(), "🎯 Alignment")
tabs.addTab(self._tab_video_ser(), "🎬 Video / SER")
tabs.addTab(self._tab_postprocess(), "✨ Post-Process")
tabs.addTab(self._tab_quickstack(), "⚡ Quick Stack")
tabs.addTab(self._tab_advanced(), "⚙ Advanced")
tabs.tabBar().setTabTextColor(4, QColor(C["warning"]))
return tabs
# ── Stacking tab ──────────────────────────────────────────────────────────
def _tab_stacking(self) -> QWidget:
w = QWidget(); lay = QVBoxLayout(w)
lay.setContentsMargins(14, 14, 14, 14); lay.setSpacing(14)
self._mode = QComboBox()
self._mode.addItems(["average", "median", "sigma", "maximum", "minimum"])
tip(self._mode,
"Stacking algorithm:\n\n"
"average — Mean per pixel. Fast, GPU-accelerated.\n\n"
"median — Median per pixel. Removes hot pixels, satellites,\n"
" cosmic rays. Memory-intensive.\n\n"
"sigma — Sigma-clipping mean. Professional standard (DSS, Siril,\n"
" PixInsight). Best SNR for deep-sky.\n\n"
"maximum — Brightest pixel. Star trails, lightning, aurora.\n\n"
"minimum — Darkest pixel. Background/gradient removal.")
self._mode.currentTextChanged.connect(self._on_mode_changed)
lay.addLayout(labeled_row("Stack mode:", self._mode, label_width=130))
self._sigma_box = QGroupBox("Sigma-Clipping Settings")
sg = QGridLayout(self._sigma_box); sg.setSpacing(10)
self._sig_lo = QDoubleSpinBox(); self._sig_lo.setRange(0.5,10); self._sig_lo.setSingleStep(0.5); self._sig_lo.setValue(2.0)
tip(self._sig_lo, "Reject pixels below mean − σ_low × std_dev (typical: 1.5–3.0)")
self._sig_hi = QDoubleSpinBox(); self._sig_hi.setRange(0.5,10); self._sig_hi.setSingleStep(0.5); self._sig_hi.setValue(2.0)
tip(self._sig_hi, "Reject pixels above mean + σ_high × std_dev (typical: 1.5–3.0)")
self._sig_it = QSpinBox(); self._sig_it.setRange(1,10); self._sig_it.setValue(3)
tip(self._sig_it, "Sigma-clipping iterations. 2–5 typical. Diminishing returns above 5.")
sg.addWidget(QLabel("σ low:"), 0, 0); sg.addWidget(self._sig_lo, 0, 1)
sg.addWidget(QLabel("σ high:"), 0, 2); sg.addWidget(self._sig_hi, 0, 3)
sg.addWidget(QLabel("Iterations:"), 1, 0); sg.addWidget(self._sig_it, 1, 1)
lay.addWidget(self._sigma_box); self._sigma_box.setVisible(False)
self._stitch = QCheckBox("Stitch stacked groups into panorama")
tip(self._stitch, "Stitch all groups into a panorama after stacking.\nRequires ≥20–30% overlap. Ignored for video/SER.")
lay.addWidget(self._stitch)
self._thresh = QSpinBox(); self._thresh.setRange(5,500); self._thresh.setValue(20)
tip(self._thresh, "Min SIFT matches to group two images together.\nHigher = stricter grouping.")
lay.addLayout(labeled_row("SIFT group threshold:", self._thresh, label_width=175))
lay.addStretch(); return w
# ── Alignment tab ─────────────────────────────────────────────────────────
def _tab_alignment(self) -> QWidget:
w = QWidget(); lay = QVBoxLayout(w)
lay.setContentsMargins(14,14,14,14); lay.setSpacing(14)
self._align = QComboBox()
self._align.addItems(["none", "orb", "ecc"])
tip(self._align,
"Alignment method:\n\n"
"none — No alignment (pre-aligned or tracked mount).\n\n"
"orb — ORB + RANSAC. Fast, robust. Good for most targets.\n\n"
"ecc — Sub-pixel accuracy. Best for star fields / deep-sky.\n"
" Falls back to ORB if convergence fails.")
lay.addLayout(labeled_row("Alignment:", self._align, label_width=130))
lay.addWidget(h_line()); lay.addWidget(section_label("ORB Settings"))
self._orb_feat = QSpinBox(); self._orb_feat.setRange(500,20000); self._orb_feat.setSingleStep(500); self._orb_feat.setValue(5000)