-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_main.py
More file actions
1079 lines (990 loc) · 44.6 KB
/
Copy pathui_main.py
File metadata and controls
1079 lines (990 loc) · 44.6 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
from __future__ import annotations
from datetime import datetime
from pathlib import Path
from PySide6.QtCore import QProcess, QThread, QTimer, Qt, Signal, QSize
from PySide6.QtGui import QAction, QCloseEvent, QIcon, QResizeEvent, QShowEvent
from PySide6.QtWidgets import (
QApplication,
QButtonGroup,
QFrame,
QHBoxLayout,
QHeaderView,
QLabel,
QMainWindow,
QMenu,
QMessageBox,
QPushButton,
QScrollArea,
QSizePolicy,
QStackedWidget,
QSystemTrayIcon,
QTableWidget,
QTableWidgetItem,
QTextEdit,
QVBoxLayout,
QWidget,
)
import apache_welcome
import package_manager
import port_scanner
import privileged
import service_assets
import service_manager
from port_scanner import Conflict, PortEntry
from service_manager import ServiceInfo
REFRESH_INTERVAL_MS = 1500
LOG_LIMIT = 200
ACTION_BTN_MARGIN_H = 5
ACTION_BTN_HEIGHT = 26
ACTION_ROW_HEIGHT = 52
STYLESHEET_PATH = Path(__file__).resolve().parent / "styles" / "dark.qss"
ICON_PATH = Path(__file__).resolve().parent / "assets" / "icons" / "amper.png"
ICONS_DIR = Path(__file__).resolve().parent / "assets" / "icons"
DEVELOPER_LINKS = [
("socialLinkedIn", "social-linkedin.svg", "LinkedIn", "https://www.linkedin.com/in/hesham-yasser-78673831b/"),
("socialX", "social-x.svg", "X", "https://x.com/HaSh_Perfecto"),
("socialGitHub", "social-github.svg", "GitHub", "https://github.com/HaSh3003"),
]
def load_stylesheet() -> str:
if STYLESHEET_PATH.is_file():
return STYLESHEET_PATH.read_text(encoding="utf-8")
return ""
def load_app_icon() -> QIcon:
if ICON_PATH.is_file():
return QIcon(str(ICON_PATH))
return QIcon()
def _social_button(object_name: str, icon_file: str, tooltip: str, url: str) -> QPushButton:
button = QPushButton()
button.setObjectName(object_name)
icon_path = ICONS_DIR / icon_file
if icon_path.is_file():
button.setIcon(QIcon(str(icon_path)))
button.setIconSize(QSize(22, 22))
button.setFixedSize(42, 42)
button.setToolTip(tooltip)
button.setCursor(Qt.CursorShape.PointingHandCursor)
button.clicked.connect(lambda: service_assets.open_url(url))
return button
def _action_button(object_name: str, label: str, tooltip: str) -> QPushButton:
button = QPushButton(label)
button.setObjectName(object_name)
button.setToolTip(tooltip)
button.setCursor(Qt.CursorShape.PointingHandCursor)
button.setFixedHeight(ACTION_BTN_HEIGHT)
button.setMinimumWidth(56)
button.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
return button
def _make_transparent(widget: QWidget) -> QWidget:
widget.setAutoFillBackground(False)
widget.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
return widget
def _action_button_slot(button: QPushButton) -> QWidget:
slot = _make_transparent(QWidget())
slot.setObjectName("actionBtnSlot")
slot.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
slot_layout = QHBoxLayout(slot)
slot_layout.setContentsMargins(ACTION_BTN_MARGIN_H, 0, ACTION_BTN_MARGIN_H, 0)
slot_layout.setSpacing(0)
slot_layout.addWidget(button)
return slot
class ModuleRowActions(QWidget):
action_requested = Signal(str, str)
file_open_requested = Signal(str, str)
url_open_requested = Signal(str, str)
package_requested = Signal(str, str)
def __init__(self, service: ServiceInfo, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.service = service
self.unit = service.unit
self.service_key = service.key
self.setObjectName("moduleRowActions")
_make_transparent(self)
layout = QHBoxLayout(self)
layout.setContentsMargins(6, 8, 6, 8)
layout.setSpacing(0)
self.btn_install = _action_button("btnInstall", "Install", "Install this module")
self.btn_uninstall = _action_button("btnUninstall", "Remove", "Uninstall this module")
self.btn_start = _action_button("btnStart", "Start", "Start this service")
self.btn_stop = _action_button("btnStop", "Stop", "Stop this service")
self.btn_admin = _action_button("btnAdmin", "Admin", "Open web admin in browser")
self.btn_config = _action_button("btnConfig", "Config", "Open configuration files")
self.btn_logs = _action_button("btnLogs", "Logs", "Open log files")
self._action_buttons = (
self.btn_install,
self.btn_uninstall,
self.btn_start,
self.btn_stop,
self.btn_admin,
self.btn_config,
self.btn_logs,
)
self.btn_install.clicked.connect(
lambda: self.package_requested.emit(self.service_key, "install")
)
self.btn_uninstall.clicked.connect(self._request_uninstall)
self.btn_start.clicked.connect(lambda: self.action_requested.emit(self.unit, "start"))
self.btn_stop.clicked.connect(lambda: self.action_requested.emit(self.unit, "stop"))
self.btn_admin.clicked.connect(self._open_admin)
self.btn_config.clicked.connect(self._show_config_menu)
self.btn_logs.clicked.connect(self._show_logs_menu)
for button in self._action_buttons:
layout.addWidget(_action_button_slot(button))
layout.addStretch()
self.setMinimumHeight(ACTION_ROW_HEIGHT)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.config_menu = QMenu(self)
self.logs_menu = QMenu(self)
self._assets = service_assets.get_assets(self.service_key)
self._rebuild_asset_menus()
def _rebuild_asset_menus(self) -> None:
self.config_menu.clear()
self.logs_menu.clear()
assets = service_assets.get_assets(self.service_key)
for link in assets.configs:
action = self.config_menu.addAction(link.label)
action.setData(link.path)
for link in assets.logs:
action = self.logs_menu.addAction(link.label)
action.setData(link.path)
self._assets = assets
def _request_uninstall(self) -> None:
label = self.service.label
command = package_manager.build_uninstall_command(self.service_key)
packages = ", ".join(command.packages) if command else self.service_key
reply = QMessageBox.warning(
self.window(),
"Confirm Uninstall",
f"Are you sure you want to uninstall {label}?\n\n"
f"Packages to remove:\n{packages}\n\n"
"This will delete the module from your system.",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No,
)
if reply == QMessageBox.StandardButton.Yes:
self.package_requested.emit(self.service_key, "uninstall")
def _open_admin(self) -> None:
if self._assets.admin_url:
self.url_open_requested.emit(self.service_key, self._assets.admin_url)
def _show_config_menu(self) -> None:
if self.config_menu.isEmpty():
return
self.config_menu.exec(self.btn_config.mapToGlobal(self.btn_config.rect().bottomLeft()))
def _show_logs_menu(self) -> None:
if self.logs_menu.isEmpty():
return
self.logs_menu.exec(self.btn_logs.mapToGlobal(self.btn_logs.rect().bottomLeft()))
def connect_menus(self) -> None:
self.config_menu.triggered.connect(self._on_config_selected)
self.logs_menu.triggered.connect(self._on_log_selected)
def _on_config_selected(self, action: QAction) -> None:
path = action.data()
if isinstance(path, str):
self.file_open_requested.emit(self.service_key, path)
def _on_log_selected(self, action: QAction) -> None:
path = action.data()
if isinstance(path, str):
self.file_open_requested.emit(self.service_key, path)
def update_state(
self,
service: ServiceInfo,
pending: bool,
package_pending: bool,
) -> None:
self.service = service
assets = service_assets.get_assets(self.service_key)
self._assets = assets
manageable = package_manager.can_manage_packages(self.service_key)
busy = pending or package_pending
self.btn_install.setEnabled(manageable and not service.available and not package_pending)
self.btn_uninstall.setEnabled(manageable and service.available and not package_pending)
if not service.available:
self.btn_start.setEnabled(False)
self.btn_stop.setEnabled(False)
self.btn_admin.setEnabled(False)
self.btn_config.setEnabled(False)
self.btn_logs.setEnabled(False)
return
self.btn_config.setEnabled(bool(assets.configs) and not package_pending)
self.btn_logs.setEnabled(bool(assets.logs) and not package_pending)
self.btn_admin.setEnabled(bool(assets.admin_url) and not package_pending)
if not service.controllable:
self.btn_start.setEnabled(False)
self.btn_stop.setEnabled(False)
return
is_active = service.state == "active"
self.btn_start.setEnabled(not busy and not is_active)
self.btn_stop.setEnabled(not busy and is_active)
class ModulesDashboard(QFrame):
action_requested = Signal(str, str)
file_open_requested = Signal(str, str)
url_open_requested = Signal(str, str)
package_requested = Signal(str, str)
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("contentPanel")
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 20, 20, 20)
layout.setSpacing(12)
header = QHBoxLayout()
title = QLabel("Linux Services")
title.setObjectName("pageTitle")
subtitle = QLabel("Manage Apache, databases, and other systemd modules")
subtitle.setObjectName("pageSubtitle")
header_col = QVBoxLayout()
header_col.setSpacing(2)
header_col.addWidget(title)
header_col.addWidget(subtitle)
header.addLayout(header_col)
header.addStretch()
layout.addLayout(header)
self.table = QTableWidget(0, 5)
self.table.setObjectName("modulesTable")
self.table.setHorizontalHeaderLabels(
["Module", "Status", "PID", "Port", "Actions"]
)
self.table.setAlternatingRowColors(True)
self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
self.table.verticalHeader().setVisible(False)
self.table.verticalHeader().setDefaultSectionSize(ACTION_ROW_HEIGHT)
self.table.setShowGrid(True)
header_view = self.table.horizontalHeader()
header_view.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
header_view.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
header_view.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
header_view.setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
header_view.setSectionResizeMode(4, QHeaderView.ResizeMode.Fixed)
self.table.setColumnWidth(4, 640)
self.table.viewport().setAutoFillBackground(False)
layout.addWidget(self.table)
self.action_widgets: dict[str, ModuleRowActions] = {}
def rebuild(self, services: list[ServiceInfo]) -> None:
self.table.setRowCount(len(services))
self.action_widgets.clear()
for row, service in enumerate(services):
module_item = QTableWidgetItem(service.label)
module_item.setFlags(module_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
self.table.setItem(row, 0, module_item)
status_item = QTableWidgetItem(self._status_text(service))
status_item.setFlags(status_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
status_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
self._apply_status_style(status_item, service, False)
self.table.setItem(row, 1, status_item)
pid_item = QTableWidgetItem(self._pid_text(service))
pid_item.setFlags(pid_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
pid_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
self.table.setItem(row, 2, pid_item)
port_item = QTableWidgetItem(self._default_port_text(service))
port_item.setFlags(port_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
self.table.setItem(row, 3, port_item)
actions = ModuleRowActions(service)
actions.action_requested.connect(self.action_requested.emit)
actions.file_open_requested.connect(self.file_open_requested.emit)
actions.url_open_requested.connect(self.url_open_requested.emit)
actions.package_requested.connect(self.package_requested.emit)
actions.connect_menus()
actions.update_state(service, False, False)
self.table.setCellWidget(row, 4, actions)
key = service.key if service.key else service.unit
self.action_widgets[key] = actions
self.table.setRowHeight(row, ACTION_ROW_HEIGHT)
def update_services(
self,
services: list[ServiceInfo],
ports: list[PortEntry],
pending_units: set[str],
pending_packages: set[str],
) -> None:
for row, service in enumerate(services):
if row >= self.table.rowCount():
break
status_item = self.table.item(row, 1)
pid_item = self.table.item(row, 2)
port_item = self.table.item(row, 3)
if status_item is not None:
status_item.setText(self._status_text(service))
pending = service.unit in pending_units if service.unit else False
self._apply_status_style(status_item, service, pending)
if pid_item is not None:
pid_item.setText(self._pid_text(service))
if port_item is not None:
active_ports = port_scanner.get_ports_for_service(service, ports)
port_item.setText(self._port_text(service, active_ports))
key = service.key if service.key else service.unit
actions = self.action_widgets.get(key)
if actions is not None:
pending = service.unit in pending_units if service.unit else False
package_pending = service.key in pending_packages
actions.update_state(service, pending, package_pending)
def _status_text(self, service: ServiceInfo) -> str:
if not service.available:
return "Not Installed"
if service.key == "php" and service.state == "active":
return "Ready"
if service.state == "active":
return "Running"
if service.state in {"inactive", "dead"}:
return "Stopped"
if service.state == "failed":
return "Failed"
return service.state.capitalize()
def _pid_text(self, service: ServiceInfo) -> str:
if not service.available or service.main_pid <= 0:
return "—"
return str(service.main_pid)
def _default_port_text(self, service: ServiceInfo) -> str:
if service.ports:
return ", ".join(str(port) for port in service.ports)
return "—"
def _port_text(self, service: ServiceInfo, active_ports: list[int]) -> str:
if active_ports:
return ", ".join(str(port) for port in active_ports)
if service.state == "active" and service.ports:
return ", ".join(str(port) for port in service.ports)
if service.ports:
return ", ".join(str(port) for port in service.ports)
return "—"
def _apply_status_style(
self,
item: QTableWidgetItem,
service: ServiceInfo,
pending: bool,
) -> None:
if not service.available:
item.setForeground(Qt.GlobalColor.gray)
return
if pending:
item.setForeground(Qt.GlobalColor.magenta)
return
if service.state == "active":
item.setForeground(Qt.GlobalColor.green)
return
if service.state == "failed":
item.setForeground(Qt.GlobalColor.red)
return
item.setForeground(Qt.GlobalColor.red)
class PortMonitorPanel(QFrame):
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("contentPanel")
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 20, 20, 20)
layout.setSpacing(12)
header = QHBoxLayout()
title = QLabel("Network Ports")
title.setObjectName("pageTitle")
subtitle = QLabel("Live view of listening ports and conflicts")
subtitle.setObjectName("pageSubtitle")
header_col = QVBoxLayout()
header_col.setSpacing(2)
header_col.addWidget(title)
header_col.addWidget(subtitle)
header.addLayout(header_col)
header.addStretch()
layout.addLayout(header)
self.table = QTableWidget(0, 5)
self.table.setObjectName("netTable")
self.table.setHorizontalHeaderLabels(
["PORT", "PID", "PROCESS", "ADDR", "CONFLICT"]
)
self.table.setAlternatingRowColors(True)
self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
self.table.verticalHeader().setVisible(False)
header_view = self.table.horizontalHeader()
header_view.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
header_view.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
header_view.setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
header_view.setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
header_view.setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch)
self.table.viewport().setAutoFillBackground(False)
layout.addWidget(self.table)
def update_ports(self, ports: list[PortEntry], conflicts: list[Conflict]) -> None:
conflict_ports = port_scanner.conflict_port_set(conflicts)
self.table.setRowCount(len(ports))
for row, entry in enumerate(ports):
conflict_text = ""
if entry.port in conflict_ports:
conflict_text = port_scanner.conflict_labels_for_port(entry.port, conflicts)
values = [
str(entry.port),
str(entry.pid) if entry.pid else "—",
entry.process_name or "—",
entry.address or "—",
conflict_text or "—",
]
for column, value in enumerate(values):
item = QTableWidgetItem(value)
if conflict_text:
item.setForeground(Qt.GlobalColor.red)
self.table.setItem(row, column, item)
class AboutPanel(QFrame):
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("contentPanel")
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
scroll = QScrollArea()
scroll.setObjectName("aboutScroll")
scroll.setWidgetResizable(True)
scroll.setFrameShape(QFrame.Shape.NoFrame)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
scroll_host = QWidget()
scroll_host.setObjectName("aboutScrollHost")
scroll_layout = QVBoxLayout(scroll_host)
scroll_layout.setContentsMargins(20, 20, 20, 20)
scroll_layout.addStretch()
card = QFrame()
card.setObjectName("aboutCard")
card_layout = QVBoxLayout(card)
card_layout.setContentsMargins(40, 40, 40, 40)
card_layout.setSpacing(14)
card_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
icon_label = QLabel()
icon_label.setObjectName("aboutIcon")
icon_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
app_icon = load_app_icon()
if not app_icon.isNull():
icon_label.setPixmap(app_icon.pixmap(96, 96))
title = QLabel("Amper")
title.setObjectName("aboutTitle")
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
subtitle = QLabel("Linux Control Panel")
subtitle.setObjectName("aboutSubtitle")
subtitle.setAlignment(Qt.AlignmentFlag.AlignCenter)
body = QTextEdit()
body.setObjectName("aboutBody")
body.setReadOnly(True)
body.setFrameShape(QFrame.Shape.NoFrame)
body.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
body.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
body.setPlainText(
"Amper is an open-source desktop control panel for Linux.\n\n"
"Manage Apache, PHP, MySQL, phpMyAdmin, and other systemd services "
"from one place. Monitor ports, edit configs, view logs, and install "
"or remove modules with your system package manager."
)
body.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth)
body.document().setDocumentMargin(4)
body.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
self.about_body = body
version = QLabel("Version 1.0")
version.setObjectName("aboutVersion")
version.setAlignment(Qt.AlignmentFlag.AlignCenter)
copyright_label = QLabel("Copyright © 2026 Amper Linux Control Panel")
copyright_label.setObjectName("aboutCopyright")
copyright_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
dev_divider = QFrame()
dev_divider.setObjectName("aboutDivider")
dev_divider.setFixedHeight(1)
dev_heading = QLabel("About Developer")
dev_heading.setObjectName("aboutDevHeading")
dev_heading.setAlignment(Qt.AlignmentFlag.AlignCenter)
dev_name = QLabel("Hesham Yasser")
dev_name.setObjectName("aboutDevName")
dev_name.setAlignment(Qt.AlignmentFlag.AlignCenter)
dev_role = QLabel("Software Engineer")
dev_role.setObjectName("aboutDevRole")
dev_role.setAlignment(Qt.AlignmentFlag.AlignCenter)
social_row = QHBoxLayout()
social_row.setSpacing(0)
social_row.setContentsMargins(0, 8, 0, 8)
social_row.setAlignment(Qt.AlignmentFlag.AlignCenter)
for object_name, icon_file, tooltip, url in DEVELOPER_LINKS:
social_row.addWidget(_social_button(object_name, icon_file, tooltip, url))
social_host = QWidget()
social_host.setLayout(social_row)
self.perm_status = QLabel()
self.perm_status.setObjectName("aboutPermStatus")
self.perm_status.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.perm_status.setWordWrap(True)
self.btn_grant_perms = QPushButton("Grant Permissions (once)")
self.btn_grant_perms.setObjectName("btnGrantPerms")
self.btn_grant_perms.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_grant_perms.clicked.connect(self._grant_permissions)
self._refresh_permission_status()
card_layout.addWidget(icon_label)
card_layout.addWidget(title)
card_layout.addWidget(subtitle)
card_layout.addWidget(body)
card_layout.addWidget(version)
card_layout.addWidget(copyright_label)
card_layout.addWidget(dev_divider)
card_layout.addWidget(dev_heading)
card_layout.addWidget(dev_name)
card_layout.addWidget(dev_role)
card_layout.addWidget(social_host)
card_layout.addWidget(self.perm_status)
card_layout.addWidget(self.btn_grant_perms)
scroll_layout.addWidget(card, alignment=Qt.AlignmentFlag.AlignHCenter)
scroll_layout.addStretch()
scroll.setWidget(scroll_host)
outer.addWidget(scroll)
QTimer.singleShot(0, self._sync_about_body_height)
def showEvent(self, event: QShowEvent) -> None:
super().showEvent(event)
self._sync_about_body_height()
def resizeEvent(self, event: QResizeEvent) -> None:
super().resizeEvent(event)
self._sync_about_body_height()
def _sync_about_body_height(self) -> None:
body = self.about_body
width = max(body.viewport().width(), 400)
body.document().setTextWidth(width)
height = int(body.document().size().height()) + 16
body.setFixedHeight(max(100, height))
def _refresh_permission_status(self) -> None:
if privileged.is_ready():
self.perm_status.setText("Permissions active — actions run without password prompts.")
self.btn_grant_perms.setEnabled(False)
self.btn_grant_perms.hide()
else:
self.perm_status.setText(
"One-time setup required. Click below and enter your password once. "
"After that, Start, Stop, Install, and Remove work without prompts."
)
self.btn_grant_perms.setEnabled(True)
self.btn_grant_perms.show()
def _grant_permissions(self) -> None:
script = privileged.setup_script_path()
if not script.is_file():
return
process = QProcess(self)
process.setProgram("pkexec")
process.setArguments(["bash", str(script)])
process.finished.connect(self._on_permissions_setup_finished)
process.start()
def _on_permissions_setup_finished(self, exit_code: int, _status: QProcess.ExitStatus) -> None:
self._refresh_permission_status()
window = self.window()
if isinstance(window, MainWindow):
if exit_code == 0:
window._log("Permissions installed. Log out and back in, or run: newgrp amper")
else:
window._log("Permission setup failed or was cancelled")
class SidebarNav(QFrame):
page_changed = Signal(int)
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("sidebar")
self.setFixedWidth(168)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 16, 0, 16)
layout.setSpacing(4)
brand = QLabel("Control Panel")
brand.setObjectName("sidebarBrand")
brand.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(brand)
layout.addSpacing(12)
self.button_group = QButtonGroup(self)
self.button_group.setExclusive(True)
self.btn_linux = QPushButton("Linux")
self.btn_linux.setObjectName("navButton")
self.btn_linux.setCheckable(True)
self.btn_linux.setChecked(True)
self.btn_net = QPushButton("Net")
self.btn_net.setObjectName("navButton")
self.btn_net.setCheckable(True)
self.btn_about = QPushButton("About")
self.btn_about.setObjectName("navButton")
self.btn_about.setCheckable(True)
self.button_group.addButton(self.btn_linux, 0)
self.button_group.addButton(self.btn_net, 1)
self.button_group.addButton(self.btn_about, 2)
layout.addWidget(self.btn_linux)
layout.addWidget(self.btn_net)
layout.addWidget(self.btn_about)
layout.addStretch()
version = QLabel("v1.0")
version.setObjectName("sidebarVersion")
version.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(version)
self.button_group.idClicked.connect(self.page_changed.emit)
class ActivityLogPanel(QFrame):
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setObjectName("activityLog")
self.setFixedHeight(130)
layout = QVBoxLayout(self)
layout.setContentsMargins(16, 10, 16, 10)
layout.setSpacing(6)
title = QLabel("Activity Log")
title.setObjectName("logTitle")
layout.addWidget(title)
self.text = QTextEdit()
self.text.setObjectName("logText")
self.text.setReadOnly(True)
self.text.setPlaceholderText("Service changes will appear here...")
layout.addWidget(self.text)
self._lines: list[str] = []
def append(self, message: str) -> None:
stamp = datetime.now().strftime("%H:%M:%S")
line = f"[{stamp}] {message}"
self._lines.append(line)
if len(self._lines) > LOG_LIMIT:
self._lines = self._lines[-LOG_LIMIT:]
self.text.setPlainText("\n".join(self._lines))
scrollbar = self.text.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
class WelcomeDeployWorker(QThread):
finished = Signal(bool, str, str)
def run(self) -> None:
ok, root, message = apache_welcome.sync_welcome_if_needed()
self.finished.emit(ok, root, message)
class SystemTrayManager:
def __init__(self, window: QMainWindow) -> None:
self.window = window
self.tray: QSystemTrayIcon | None = None
self.menu = QMenu()
self.show_action = QAction("Show Amper", self.menu)
self.hide_action = QAction("Hide Amper", self.menu)
self.quit_action = QAction("Quit", self.menu)
self.service_actions: dict[str, dict[str, QAction]] = {}
self.show_action.triggered.connect(self._show_window)
self.hide_action.triggered.connect(self._hide_window)
self.quit_action.triggered.connect(QApplication.quit)
self.menu.addAction(self.show_action)
self.menu.addAction(self.hide_action)
self.menu.addSeparator()
self.quit_action.setMenuRole(QAction.MenuRole.QuitRole)
self.menu.addAction(self.quit_action)
if QSystemTrayIcon.isSystemTrayAvailable():
self.tray = QSystemTrayIcon(self.window)
app_icon = load_app_icon()
if not app_icon.isNull():
self.tray.setIcon(app_icon)
self.tray.setToolTip("Amper Linux Control Panel")
self.tray.setContextMenu(self.menu)
self.tray.activated.connect(self._on_activated)
self.tray.show()
def is_available(self) -> bool:
return self.tray is not None
def rebuild_service_menu(self, services: list[ServiceInfo]) -> None:
for actions in self.service_actions.values():
menu_action = actions.get("menu")
if menu_action is not None:
self.menu.removeAction(menu_action)
menu_action.deleteLater()
self.service_actions.clear()
for action in list(self.menu.actions()):
if action not in {self.show_action, self.hide_action, self.quit_action}:
self.menu.removeAction(action)
if action.menu() is not None:
action.menu().deleteLater()
action.deleteLater()
controllable = [
service for service in services if service.available and service.controllable and service.unit
]
if controllable:
self.menu.insertSeparator(self.quit_action)
for service in controllable:
submenu = QMenu(service.label, self.menu)
start_action = submenu.addAction("Start")
stop_action = submenu.addAction("Stop")
restart_action = submenu.addAction("Restart")
start_action.setData(("action", service.unit, "start"))
stop_action.setData(("action", service.unit, "stop"))
restart_action.setData(("action", service.unit, "restart"))
menu_action = self.menu.insertMenu(self.quit_action, submenu)
self.service_actions[service.unit] = {
"start": start_action,
"stop": stop_action,
"restart": restart_action,
"menu": menu_action,
}
def update_service_states(self, services: list[ServiceInfo], pending_units: set[str]) -> None:
for service in services:
actions = self.service_actions.get(service.unit)
if actions is None:
continue
busy = service.unit in pending_units
is_active = service.state == "active"
actions["start"].setEnabled(not busy and not is_active)
actions["stop"].setEnabled(not busy and is_active)
actions["restart"].setEnabled(not busy and is_active)
def connect_action_handler(self, handler) -> None:
self.menu.triggered.connect(handler)
def _show_window(self) -> None:
self.window.showNormal()
self.window.raise_()
self.window.activateWindow()
def _hide_window(self) -> None:
self.window.hide()
def _on_activated(self, reason: QSystemTrayIcon.ActivationReason) -> None:
if reason == QSystemTrayIcon.ActivationReason.DoubleClick:
if self.window.isVisible():
self._hide_window()
else:
self._show_window()
class MainWindow(QMainWindow):
def __init__(self) -> None:
super().__init__()
self.setWindowTitle("Amper Linux Control Panel")
app_icon = load_app_icon()
if not app_icon.isNull():
self.setWindowIcon(app_icon)
self.resize(1100, 620)
self.setMinimumSize(980, 520)
self.services: list[ServiceInfo] = []
self.pending_units: set[str] = set()
self.pending_packages: set[str] = set()
self.pending_actions: dict[str, str] = {}
self.processes: dict[str, QProcess] = {}
self.package_processes: dict[str, QProcess] = {}
self.previous_states: dict[str, str] = {}
self.welcome_worker: WelcomeDeployWorker | None = None
central = QWidget()
central.setObjectName("appRoot")
self.setCentralWidget(central)
root = QVBoxLayout(central)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
banner = QFrame()
banner.setObjectName("xamppBanner")
banner_layout = QHBoxLayout(banner)
banner_layout.setContentsMargins(20, 12, 20, 12)
banner_title = QLabel("Amper")
banner_title.setObjectName("bannerTitle")
banner_subtitle = QLabel("Linux Control Panel")
banner_subtitle.setObjectName("bannerSubtitle")
banner_layout.addWidget(banner_title)
banner_layout.addWidget(banner_subtitle)
banner_layout.addStretch()
root.addWidget(banner)
workspace = QWidget()
workspace_layout = QHBoxLayout(workspace)
workspace_layout.setContentsMargins(0, 0, 0, 0)
workspace_layout.setSpacing(0)
self.sidebar = SidebarNav()
self.sidebar.page_changed.connect(self._switch_page)
workspace_layout.addWidget(self.sidebar)
content_host = QWidget()
content_host.setObjectName("workspace")
content_layout = QVBoxLayout(content_host)
content_layout.setContentsMargins(0, 0, 0, 0)
content_layout.setSpacing(0)
self.pages = QStackedWidget()
self.pages.setObjectName("pageStack")
self.modules_panel = ModulesDashboard()
self.modules_panel.action_requested.connect(self._handle_service_action)
self.modules_panel.file_open_requested.connect(self._handle_open_file)
self.modules_panel.url_open_requested.connect(self._handle_open_url)
self.modules_panel.package_requested.connect(self._handle_package_action)
self.port_panel = PortMonitorPanel()
self.about_panel = AboutPanel()
self.pages.addWidget(self.modules_panel)
self.pages.addWidget(self.port_panel)
self.pages.addWidget(self.about_panel)
content_layout.addWidget(self.pages)
workspace_layout.addWidget(content_host, stretch=1)
root.addWidget(workspace, stretch=1)
self.activity_log = ActivityLogPanel()
root.addWidget(self.activity_log)
self.tray_manager = SystemTrayManager(self)
self.tray_manager.connect_action_handler(self._handle_tray_action)
self.refresh_timer = QTimer(self)
self.refresh_timer.setInterval(REFRESH_INTERVAL_MS)
self.refresh_timer.timeout.connect(self.refresh_ui)
self._build_modules()
self.refresh_ui()
self.refresh_timer.start()
QTimer.singleShot(800, self._sync_apache_welcome)
if not privileged.is_ready():
self._log("Tip: open About tab and click Grant Permissions once to skip password prompts")
def showEvent(self, event) -> None:
super().showEvent(event)
if hasattr(self, "about_panel"):
self.about_panel._refresh_permission_status()
def _sync_apache_welcome(self) -> None:
if self.welcome_worker is not None and self.welcome_worker.isRunning():
return
document_root = apache_welcome.find_document_root()
if not document_root or not apache_welcome.should_deploy(document_root):
return
self._log("Apache: installing Amper welcome page...")
self.welcome_worker = WelcomeDeployWorker(self)
self.welcome_worker.finished.connect(self._on_welcome_deploy_finished)
self.welcome_worker.start()
def _on_welcome_deploy_finished(self, ok: bool, root: str, message: str) -> None:
if ok:
self._log(f"Apache: welcome page deployed to {message}")
elif root and "already up to date" not in message:
self._log(f"Apache: welcome page deploy failed — {message}")
if self.welcome_worker is not None:
self.welcome_worker.deleteLater()
self.welcome_worker = None
def _switch_page(self, index: int) -> None:
self.pages.setCurrentIndex(index)
def _build_modules(self) -> None:
self.services = service_manager.list_catalog_services()
self.modules_panel.rebuild(self.services)
for service in self.services:
if service.available and service.unit:
self.previous_states[service.unit] = service.state
controllable = [
service for service in self.services if service.available and service.controllable
]
self.tray_manager.rebuild_service_menu(controllable)
def _label_for_unit(self, unit: str) -> str:
for service in self.services:
if service.unit == unit:
return service.label
return unit
def _status_label(self, state: str) -> str:
if state == "active":
return "Running"
if state in {"inactive", "dead"}:
return "Stopped"
if state == "failed":
return "Failed"
return state.capitalize()
def _log(self, message: str) -> None:
self.activity_log.append(message)
def _label_for_key(self, key: str) -> str:
for service in self.services:
if service.key == key:
return service.label
return key
def _handle_open_file(self, service_key: str, path: str) -> None:
label = self._label_for_key(service_key)
if service_assets.open_path(path):
self._log(f"{label}: opened {path}")
else:
self._log(f"{label}: file not found — {path}")
def _handle_open_url(self, service_key: str, url: str) -> None:
label = self._label_for_key(service_key)
service_assets.open_url(url)
self._log(f"{label}: opened {url}")
def _handle_package_action(self, service_key: str, action: str) -> None:
if service_key in self.pending_packages:
return
label = self._label_for_key(service_key)
if action == "install":
command = package_manager.build_install_command(service_key)
else:
command = package_manager.build_uninstall_command(service_key)
if command is None:
self._log(f"{label}: package manager not available for this module")
return
packages = ", ".join(command.packages)
self._log(f"{label}: {action} requested ({packages})...")
process = QProcess(self)
process.setProgram(command.argv[0])
process.setArguments(command.argv[1:])
process.finished.connect(
lambda code, _status, key=service_key, act=action, p=process: self._on_package_finished(
key, act, code, p
)
)
self.package_processes[service_key] = process
self.pending_packages.add(service_key)
process.start()
self.refresh_ui()
def _on_package_finished(
self,
service_key: str,
action: str,
exit_code: int,
process: QProcess,
) -> None:
self.pending_packages.discard(service_key)
self.package_processes.pop(service_key, None)
process.deleteLater()
label = self._label_for_key(service_key)
service_manager.invalidate_unit_cache()
self._build_modules()
if exit_code != 0:
self._log(f"{label}: {action} failed (exit {exit_code})")
else:
self._log(f"{label}: {action} completed successfully")
self.refresh_ui()
def _handle_tray_action(self, action: QAction) -> None:
data = action.data()
if not isinstance(data, tuple) or len(data) != 3:
return
kind, unit, verb = data
if kind == "action":
self._handle_service_action(unit, verb)
def _handle_service_action(self, unit: str, action: str) -> None:
if not unit or unit in self.pending_units:
return
label = self._label_for_unit(unit)
verb = action.capitalize()
self._log(f"{label}: {verb} requested...")
argv = privileged.wrap(["systemctl", action, unit])
process = QProcess(self)
process.setProgram(argv[0])