-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFOVSimulator.py
More file actions
2189 lines (1901 loc) · 105 KB
/
Copy pathFOVSimulator.py
File metadata and controls
2189 lines (1901 loc) · 105 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 logging
import math
import sys
import ssl
import threading
import urllib.parse
import urllib.request
from PySide6.QtCore import Qt, QUrl, QTimer, QSettings
from PySide6.QtGui import QAction
from PySide6.QtWidgets import (
QMainWindow, QVBoxLayout, QWidget, QLabel, QHBoxLayout,
QComboBox, QCheckBox, QPushButton, QMessageBox,
QToolButton, QMenu
)
from astropy import units as u
from astropy.time import Time
from astropy.coordinates import SkyCoord, EarthLocation, AltAz
from DatabaseManager import DatabaseManager
from WindowPositionManager import WindowPositionMixin
from Theme import COLORS
from UrlOpener import open_url
from NINAIntegration import NINAIntegration
logger = logging.getLogger(__name__)
class AladinLiteWindow(WindowPositionMixin, QMainWindow):
WINDOW_POSITION_KEY = "AladinLite"
SMART_TELESCOPES = [
{'name': 'ZWO Seestar S30', 'aperture': 30, 'focal_length': 150, 'camera_text': 'ASI662MC (7.4x5.6mm) (Seestar S30)', 'smart_telescope': True},
{'name': 'ZWO Seestar S30 Pro', 'aperture': 30, 'focal_length': 160, 'camera_text': 'IMX585 (11.1x6.3mm) (Seestar S30 Pro)', 'smart_telescope': True},
{'name': 'ZWO Seestar S50', 'aperture': 50, 'focal_length': 250, 'camera_text': 'ASI462MC (2.9x2.9mm) (Seestar S50)', 'smart_telescope': True},
{'name': 'Vaonis Vespera II', 'aperture': 50, 'focal_length': 250, 'camera_text': 'IMX585 (11.1x6.3mm) (Vaonis Vespera II)', 'smart_telescope': True},
{'name': 'Celestron Origin', 'aperture': 152, 'focal_length': 335, 'camera_text': 'IMX178 (7.4x4.9mm) (Celestron Origin)', 'smart_telescope': True},
{'name': 'Celestron Origin Mark II', 'aperture': 152, 'focal_length': 335, 'camera_text': 'IMX678 (7.7x4.3mm) (Celestron Origin Mark II)', 'smart_telescope': True},
{'name': 'Dwarf 3', 'aperture': 35, 'focal_length': 150, 'camera_text': 'IMX678 (7.7x4.3mm) (Dwarf 3)', 'smart_telescope': True},
{'name': 'Dwarf Mini', 'aperture': 30, 'focal_length': 150, 'camera_text': 'IMX662 (5.6x3.2mm) (Dwarf Mini)', 'smart_telescope': True},
]
def __init__(self, data: dict, parent=None):
super().__init__(parent)
self.setWindowTitle(f"{data['name']} - FOV Simulator - Cosmos Collection")
self.resize(1200, 800)
self.setup_window_position()
self.data = data
self.telescopes = []
self.selected_telescope = None
self.current_fov = None
self.current_target = None # Track current target to preserve user changes
self.observer_lat = None
self.observer_lon = None
# Calculate default FOV based on object size (in degrees)
try:
size_min = data.get('size_min', 30) or 30 # Default to 30 arcminutes if None
size_max = data.get('size_max', 30) or 30 # Default to 30 arcminutes if None
size_max = max(size_min, size_max) # arcminutes
self.default_fov = max(size_max / 60.0 * 3.0, 0.5) # Convert to degrees, 3x object size, min 0.5°
self.current_fov = self.default_fov
logger.debug(f"Size values for {data['name']}: min={size_min:.1f}', max={size_max:.1f}'")
logger.debug(f"Calculated default FOV: {self.default_fov:.3f}°")
except Exception as e:
logger.warning(f"Error calculating FOV for {data.get('name', 'Unknown')}: {e}")
self.default_fov = 1.0 # Safe fallback
self.current_fov = 1.0
# Create main layout
layout = QVBoxLayout()
# Create telescope controls layout
telescope_layout = QHBoxLayout()
# Telescope selection
telescope_label = QLabel("Telescope:")
self.telescope_combo = QComboBox()
self.telescope_combo.setMinimumWidth(280)
self.telescope_combo.addItem("Default View", None)
self.telescope_combo.currentTextChanged.connect(self._on_telescope_changed)
self.show_smart_telescopes = QCheckBox("Show Smart Telescopes")
self.show_smart_telescopes.setChecked(False)
self.show_smart_telescopes.toggled.connect(self._on_show_smart_telescopes_toggled)
# Load telescopes
self._load_telescopes()
# FOV display controls
self.show_telescope_fov = QCheckBox("Show Telescope FOV")
self.show_telescope_fov.setChecked(False)
self.show_telescope_fov.toggled.connect(self._on_show_fov_toggled)
self.show_horizon = QCheckBox("Virtual Horizon")
self.show_horizon.setChecked(False)
self.show_horizon.toggled.connect(self._on_show_horizon_toggled)
# Camera/Eyepiece selection (for different FOVs)
camera_label = QLabel("Camera/Eyepiece:")
self.camera_combo = QComboBox()
# Load user equipment first
self._load_user_cameras_and_eyepieces()
# Visual eyepieces with typical apparent FOV values
self.camera_combo.addItem("--- EYEPIECES ---", None)
self.camera_combo.addItem("32mm Eyepiece (52° AFOV)", {"type": "eyepiece", "focal_length": 32, "apparent_fov": 52})
self.camera_combo.addItem("25mm Eyepiece (52° AFOV)", {"type": "eyepiece", "focal_length": 25, "apparent_fov": 52})
self.camera_combo.addItem("20mm Eyepiece (50° AFOV)", {"type": "eyepiece", "focal_length": 20, "apparent_fov": 50})
self.camera_combo.addItem("15mm Eyepiece (50° AFOV)", {"type": "eyepiece", "focal_length": 15, "apparent_fov": 50})
self.camera_combo.addItem("10mm Eyepiece (50° AFOV)", {"type": "eyepiece", "focal_length": 10, "apparent_fov": 50})
self.camera_combo.addItem("6mm Eyepiece (50° AFOV)", {"type": "eyepiece", "focal_length": 6, "apparent_fov": 50})
# DSLR cameras
self.camera_combo.addItem("--- DSLR CAMERAS ---", None)
self.camera_combo.addItem("Canon Full Frame (36x24mm)", {"type": "camera", "sensor_width": 36, "sensor_height": 24})
self.camera_combo.addItem("Canon APS-C (22.3x14.9mm)", {"type": "camera", "sensor_width": 22.3, "sensor_height": 14.9})
self.camera_combo.addItem("Canon APS-H (28.7x19mm)", {"type": "camera", "sensor_width": 28.7, "sensor_height": 19.0})
self.camera_combo.addItem("Nikon Full Frame (35.9x24mm)", {"type": "camera", "sensor_width": 35.9, "sensor_height": 24.0})
self.camera_combo.addItem("Nikon APS-C (23.5x15.6mm)", {"type": "camera", "sensor_width": 23.5, "sensor_height": 15.6})
self.camera_combo.addItem("Sony Full Frame (35.8x23.8mm)", {"type": "camera", "sensor_width": 35.8, "sensor_height": 23.8})
self.camera_combo.addItem("Sony APS-C (23.5x15.6mm)", {"type": "camera", "sensor_width": 23.5, "sensor_height": 15.6})
# ZWO cameras
self.camera_combo.addItem("--- ZWO ASI CAMERAS ---", None)
self.camera_combo.addItem("ASI6200MM Pro (36x24mm)", {"type": "camera", "sensor_width": 36.0, "sensor_height": 24.0})
self.camera_combo.addItem("ASI2600MM Pro (23.5x15.7mm)", {"type": "camera", "sensor_width": 23.5, "sensor_height": 15.7})
self.camera_combo.addItem("ASI533MM Pro (11.3x7.1mm)", {"type": "camera", "sensor_width": 11.3, "sensor_height": 7.1})
self.camera_combo.addItem("ASI294MM Pro (19.1x13.0mm)", {"type": "camera", "sensor_width": 19.1, "sensor_height": 13.0})
self.camera_combo.addItem("ASI183MM Pro (13.2x8.8mm)", {"type": "camera", "sensor_width": 13.2, "sensor_height": 8.8})
self.camera_combo.addItem("ASI585MC (8.3x6.2mm)", {"type": "camera", "sensor_width": 8.3, "sensor_height": 6.2})
self.camera_combo.addItem("ASI662MC (7.4x5.6mm) (Seestar S30)", {"type": "camera", "sensor_width": 7.4, "sensor_height": 5.6})
self.camera_combo.addItem("IMX585 (11.1x6.3mm) (Seestar S30 Pro)", {"type": "camera", "sensor_width": 11.1, "sensor_height": 6.3})
self.camera_combo.addItem("ASI385MC (7.7x4.9mm)", {"type": "camera", "sensor_width": 7.7, "sensor_height": 4.9})
self.camera_combo.addItem("ASI462MC (2.9x2.9mm) (Seestar S50)", {"type": "camera", "sensor_width": 2.9, "sensor_height": 2.9})
self.camera_combo.addItem("ASI224MC (3.9x2.8mm)", {"type": "camera", "sensor_width": 3.9, "sensor_height": 2.8})
self.camera_combo.addItem("ASI120MM (3.8x2.8mm)", {"type": "camera", "sensor_width": 3.8, "sensor_height": 2.8})
# QHY cameras
self.camera_combo.addItem("--- QHY CAMERAS ---", None)
self.camera_combo.addItem("QHY600M (36x24mm)", {"type": "camera", "sensor_width": 36.0, "sensor_height": 24.0})
self.camera_combo.addItem("QHY268M (23.5x15.7mm)", {"type": "camera", "sensor_width": 23.5, "sensor_height": 15.7})
self.camera_combo.addItem("QHY294M (19.1x13.0mm)", {"type": "camera", "sensor_width": 19.1, "sensor_height": 13.0})
self.camera_combo.addItem("QHY183M (13.2x8.8mm)", {"type": "camera", "sensor_width": 13.2, "sensor_height": 8.8})
self.camera_combo.addItem("QHY174M (11.3x7.1mm)", {"type": "camera", "sensor_width": 11.3, "sensor_height": 7.1})
# SBIG cameras
self.camera_combo.addItem("--- SBIG CAMERAS ---", None)
self.camera_combo.addItem("SBIG STF-8300M (17.96x13.52mm)", {"type": "camera", "sensor_width": 17.96, "sensor_height": 13.52})
self.camera_combo.addItem("SBIG ST-2000XM (15.2x15.2mm)", {"type": "camera", "sensor_width": 15.2, "sensor_height": 15.2})
# Atik cameras
self.camera_combo.addItem("--- ATIK CAMERAS ---", None)
self.camera_combo.addItem("Atik 460EX (36x24mm)", {"type": "camera", "sensor_width": 36.0, "sensor_height": 24.0})
self.camera_combo.addItem("Atik 383L+ (23.6x15.8mm)", {"type": "camera", "sensor_width": 23.6, "sensor_height": 15.8})
# Vaonis cameras
self.camera_combo.addItem("--- VAONIS CAMERAS ---", None)
self.camera_combo.addItem("IMX585 (11.1x6.3mm) (Vaonis Vespera II)", {"type": "camera", "sensor_width": 11.1, "sensor_height": 6.3})
# Celestron cameras
self.camera_combo.addItem("--- CELESTRON CAMERAS ---", None)
self.camera_combo.addItem("IMX178 (7.4x4.9mm) (Celestron Origin)", {"type": "camera", "sensor_width": 7.4, "sensor_height": 4.9})
self.camera_combo.addItem("IMX678 (7.7x4.3mm) (Celestron Origin Mark II)", {"type": "camera", "sensor_width": 7.7, "sensor_height": 4.3})
self.camera_combo.currentTextChanged.connect(self._on_camera_changed)
# Barlow/Reducer selection
barlow_label = QLabel("Barlow/Reducer:")
self.barlow_combo = QComboBox()
# Optical accessories
self.barlow_combo.addItem("None (1.0x)", {"factor": 1.0, "type": "none"})
# Load user barlows/reducers
self._load_user_barlows()
self.barlow_combo.addItem("--- BARLOWS ---", None)
self.barlow_combo.addItem("1.25x Barlow", {"factor": 1.25, "type": "barlow"})
self.barlow_combo.addItem("1.5x Barlow", {"factor": 1.5, "type": "barlow"})
self.barlow_combo.addItem("2x Barlow", {"factor": 2.0, "type": "barlow"})
self.barlow_combo.addItem("2.5x Barlow", {"factor": 2.5, "type": "barlow"})
self.barlow_combo.addItem("3x Barlow", {"factor": 3.0, "type": "barlow"})
self.barlow_combo.addItem("4x Barlow", {"factor": 4.0, "type": "barlow"})
self.barlow_combo.addItem("5x Barlow", {"factor": 5.0, "type": "barlow"})
self.barlow_combo.addItem("--- REDUCERS ---", None)
self.barlow_combo.addItem("0.5x Reducer", {"factor": 0.5, "type": "reducer"})
self.barlow_combo.addItem("0.6x Reducer", {"factor": 0.6, "type": "reducer"})
self.barlow_combo.addItem("0.63x Reducer", {"factor": 0.63, "type": "reducer"})
self.barlow_combo.addItem("0.67x Reducer", {"factor": 0.67, "type": "reducer"})
self.barlow_combo.addItem("0.7x Reducer", {"factor": 0.7, "type": "reducer"})
self.barlow_combo.addItem("0.75x Reducer", {"factor": 0.75, "type": "reducer"})
self.barlow_combo.addItem("0.8x Reducer", {"factor": 0.8, "type": "reducer"})
self.barlow_combo.currentTextChanged.connect(self._on_barlow_changed)
# Arrange telescope controls
telescope_layout.addWidget(telescope_label)
telescope_layout.addWidget(self.telescope_combo)
telescope_layout.addWidget(self.show_smart_telescopes)
telescope_layout.addWidget(self.show_telescope_fov)
telescope_layout.addWidget(self.show_horizon)
telescope_layout.addWidget(camera_label)
telescope_layout.addWidget(self.camera_combo)
telescope_layout.addWidget(barlow_label)
telescope_layout.addWidget(self.barlow_combo)
telescope_layout.addStretch()
# Target List button
target_menu = QMenu(self)
self.add_target_action = QAction("Add to Target List", self)
self.add_target_action.triggered.connect(self._add_to_target_list)
target_menu.addAction(self.add_target_action)
self.remove_target_action = QAction("Remove from Target List", self)
self.remove_target_action.triggered.connect(self._remove_from_target_list)
self.remove_target_action.setVisible(False)
target_menu.addAction(self.remove_target_action)
self.open_target_action = QAction("Open in Target List", self)
self.open_target_action.triggered.connect(self._open_from_target_list)
self.open_target_action.setVisible(False)
target_menu.addAction(self.open_target_action)
target_button = QToolButton()
target_button.setText("Target List")
target_button.setMenu(target_menu)
target_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
telescope_layout.addWidget(target_button)
# Add NINA button if integration is enabled
if NINAIntegration.is_enabled():
nina_menu = QMenu(self)
framing_action = QAction("Send to Framing Assistant", self)
framing_action.triggered.connect(self._send_to_nina)
nina_menu.addAction(framing_action)
slew_action = QAction("Slew to Target", self)
slew_action.triggered.connect(self._slew_to_nina_target)
nina_menu.addAction(slew_action)
nina_button = QToolButton()
nina_button.setText("NINA")
nina_button.setToolTip("Send to NINA")
nina_button.setMenu(nina_menu)
nina_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
telescope_layout.addWidget(nina_button)
layout.addLayout(telescope_layout)
# Initialize web view as None initially - we'll create it safely later
self.web_view = None
self.web_view_error = None
# Create a placeholder widget for the web view
self.web_placeholder = QLabel("Loading Aladin Lite...")
self.web_placeholder.setAlignment(Qt.AlignCenter)
self.web_placeholder.setStyleSheet(f"QLabel {{ background-color: {COLORS['background']}; color: white; font-size: 14px; }}")
self.web_placeholder.setMinimumSize(400, 300)
layout.addWidget(self.web_placeholder)
# Create a horizontal layout for the bottom controls
bottom_layout = QHBoxLayout()
# Add FOV information display
self.fov_info_label = QLabel()
self.fov_info_label.setStyleSheet("font-size: 10pt;")
bottom_layout.addWidget(self.fov_info_label)
bottom_layout.addStretch()
# Add close button
close_button = QPushButton("Close")
close_button.clicked.connect(self.close)
bottom_layout.addWidget(close_button)
# Add the bottom layout to the main layout
layout.addLayout(bottom_layout)
# Create central widget and set layout for QMainWindow
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
# Initialize overlay data storage
self.pending_fov_overlay = None
self.target_coordinates = None
self.fallback_button = None # Track fallback button to avoid duplicates
self._renderer_crashed = False # Set by _on_render_process_terminated; suppresses the generic load-failed message
# Add loading timeout
self.loading_timeout = QTimer()
self.loading_timeout.timeout.connect(self._handle_loading_timeout)
self.loading_timeout.setSingleShot(True)
# Load persistent settings before creating web view
self._load_aladin_settings()
# Update target list button state
self._update_target_list_button()
# Defer web view creation to avoid initialization crashes
QTimer.singleShot(100, self._create_web_view_safely)
logger.debug(f"Opened Aladin Lite window with default FOV: {self.default_fov:.2f}'")
def _create_web_view_safely(self):
"""Safely create the web view with error handling"""
try:
logger.debug("Creating web view safely...")
# Try to create the web view
try:
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtCore import QUrl
except ImportError as ie:
raise Exception(f"QWebEngineView not available: {ie}")
self.web_view = QWebEngineView()
self.web_view.setMinimumSize(400, 300)
# Enable WebGL and hardware acceleration for Aladin Lite
try:
from PySide6.QtWebEngineCore import QWebEngineSettings
settings = self.web_view.settings()
# Enable WebGL - critical for Aladin Lite rendering
settings.setAttribute(QWebEngineSettings.WebAttribute.WebGLEnabled, True)
settings.setAttribute(QWebEngineSettings.WebAttribute.Accelerated2dCanvasEnabled, True)
settings.setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessRemoteUrls, True)
# Enable JavaScript (required for Aladin Lite)
settings.setAttribute(QWebEngineSettings.WebAttribute.JavascriptEnabled, True)
settings.setAttribute(QWebEngineSettings.WebAttribute.JavascriptCanAccessClipboard, True)
settings.setAttribute(QWebEngineSettings.WebAttribute.JavascriptCanOpenWindows, True)
# Enable local storage and other web features
settings.setAttribute(QWebEngineSettings.WebAttribute.LocalStorageEnabled, True)
logger.debug("WebGL, JavaScript, and hardware acceleration enabled for Aladin window")
except Exception as e:
logger.warning(f"Could not enable WebGL settings: {e}")
# Add load progress and error handling
self.web_view.loadStarted.connect(self._on_load_started)
self.web_view.loadProgress.connect(self._on_load_progress)
self.web_view.loadFinished.connect(self._on_load_finished)
self.web_view.page().renderProcessTerminated.connect(self._on_render_process_terminated)
# Enable developer tools for debugging (optional)
try:
from PySide6.QtWebEngineCore import QWebEngineSettings
# Try different attribute names depending on PySide6 version
try:
self.web_view.settings().setAttribute(QWebEngineSettings.WebAttribute.DeveloperExtrasEnabled, True)
except AttributeError:
try:
self.web_view.settings().setAttribute(QWebEngineSettings.DeveloperExtrasEnabled, True)
except AttributeError:
# Alternative approach for older versions
settings = self.web_view.settings()
settings.setAttribute(settings.DeveloperExtrasEnabled, True)
# Enable context menu for developer tools
self.web_view.setContextMenuPolicy(Qt.DefaultContextMenu)
logger.debug("Developer tools enabled for Aladin window")
except Exception as e:
logger.debug(f"Could not enable developer tools: {e}")
# Continue without developer tools
# Load Aladin — placeholder stays visible until _on_load_finished swaps it out
self._update_aladin_view(preserve_target=False)
logger.debug("Web view created successfully")
except Exception as e:
logger.error(f"Failed to create web view safely: {e}")
self.web_view_error = str(e)
# Update placeholder to show error and offer browser fallback
if self.web_placeholder:
self.web_placeholder.setText(f"Failed to load Aladin Lite\nError: {str(e)}\n\nClick below to open in browser instead.")
self.web_placeholder.setStyleSheet(f"QLabel {{ background-color: {COLORS['background']}; color: {COLORS['error']}; font-size: 12px; }}")
# Add a button to open in browser as fallback
self._add_browser_fallback_button()
def _add_browser_fallback_button(self):
"""Add a button to open Aladin Lite in the default browser"""
try:
# Don't add button if it already exists
if self.fallback_button is not None:
return
# Find the central widget and its layout
central_widget = self.centralWidget()
if central_widget and central_widget.layout():
main_layout = central_widget.layout()
# Create a fallback button
self.fallback_button = QPushButton("Open Aladin Lite in Browser")
self.fallback_button.setStyleSheet(f"QPushButton {{ background-color: {COLORS['success']}; color: white; font-weight: bold; margin: 10px; padding: 8px; }}")
self.fallback_button.clicked.connect(self._open_in_browser)
# Insert before the bottom controls (last item should be the bottom layout)
main_layout.insertWidget(main_layout.count() - 1, self.fallback_button)
logger.debug("Added browser fallback button")
except Exception as e:
logger.error(f"Failed to add browser fallback button: {e}")
def _open_in_browser(self):
"""Open Aladin Lite in the default browser"""
try:
# Build the same URL we would use in the web view
ra = self.data.get('ra_deg', 0)
dec = self.data.get('dec_deg', 0)
target_id = f"{ra} {dec}" if ra and dec else self.data.get('name', 'M1')
url_params = [
f"target={target_id}",
f"fov={self.default_fov}",
"survey=P%2FDSS2%2Fcolor",
"showReticle=true"
]
base_url = "https://aladin.u-strasbg.fr/AladinLite/?"
browser_url = f"{base_url}{'&'.join(url_params)}"
logger.debug(f"Opening Aladin Lite in browser: {browser_url}")
open_url(browser_url)
# Show a message to the user
QMessageBox.information(self, "Opened in Browser",
f"Aladin Lite has been opened in your default browser for {self.data.get('name', 'the selected object')}.")
except Exception as e:
logger.error(f"Failed to open Aladin Lite in browser: {e}")
QMessageBox.warning(self, "Error", f"Failed to open Aladin Lite in browser: {str(e)}")
def closeEvent(self, event):
"""Handle window close event with proper cleanup"""
try:
logger.debug("Cleaning up Aladin Lite window")
# Stop any pending JavaScript operations
if hasattr(self, 'web_view') and self.web_view:
self.web_view.stop()
# Clear the web view content
self.web_view.setHtml("")
event.accept()
except Exception as e:
logger.warning(f"Error during Aladin window cleanup: {e}")
event.accept() # Always accept to prevent hanging
def _load_telescopes(self):
"""Load active user telescopes from database"""
try:
with DatabaseManager().get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT id, name, aperture, focal_length, is_active
FROM usertelescopes
WHERE focal_length IS NOT NULL AND focal_length > 0 AND is_active = 1
ORDER BY name ASC
""")
telescopes = cursor.fetchall()
self.telescopes = []
for telescope_id, name, aperture, focal_length, is_active in telescopes:
telescope_data = {
'id': telescope_id,
'name': name,
'aperture': aperture,
'focal_length': focal_length,
'is_active': is_active
}
self.telescopes.append(telescope_data)
# Add to combo box
display_name = f"{name} ({focal_length}mm f/{focal_length/aperture:.1f})" if aperture else f"{name} ({focal_length}mm)"
self.telescope_combo.addItem(display_name, telescope_data)
logger.debug(f"Loaded {len(telescopes)} active telescopes with focal length data")
except Exception as e:
logger.error(f"Error loading telescopes: {str(e)}")
def _load_user_cameras_and_eyepieces(self):
"""Load user cameras and eyepieces from database to populate camera combo"""
try:
with DatabaseManager().get_connection() as conn:
cursor = conn.cursor()
# Load user cameras
cursor.execute("""
SELECT id, name, sensor_width, sensor_height
FROM userequipment
WHERE equipment_type = 'camera'
ORDER BY name ASC
""")
user_cameras = cursor.fetchall()
# Load user eyepieces
cursor.execute("""
SELECT id, name, focal_length, apparent_fov
FROM userequipment
WHERE equipment_type = 'eyepiece'
ORDER BY name ASC
""")
user_eyepieces = cursor.fetchall()
# Add user cameras section if there are any
if user_cameras:
self.camera_combo.addItem("--- YOUR CAMERAS ---", None)
for eq_id, name, sensor_width, sensor_height in user_cameras:
if sensor_width and sensor_height:
display_text = f"{name} ({sensor_width}x{sensor_height}mm)"
self.camera_combo.addItem(display_text, {
"type": "camera",
"sensor_width": sensor_width,
"sensor_height": sensor_height,
"source": "user",
"id": eq_id
})
# Add user eyepieces section if there are any
if user_eyepieces:
self.camera_combo.addItem("--- YOUR EYEPIECES ---", None)
for eq_id, name, focal_length, apparent_fov in user_eyepieces:
if focal_length and apparent_fov:
display_text = f"{name} ({focal_length}mm, {apparent_fov}\u00b0 AFOV)"
self.camera_combo.addItem(display_text, {
"type": "eyepiece",
"focal_length": focal_length,
"apparent_fov": apparent_fov,
"source": "user",
"id": eq_id
})
logger.debug(f"Loaded {len(user_cameras)} user cameras and {len(user_eyepieces)} user eyepieces")
except Exception as e:
logger.error(f"Error loading user cameras/eyepieces: {str(e)}")
def _load_user_barlows(self):
"""Load user barlows and reducers from database to populate barlow combo"""
try:
with DatabaseManager().get_connection() as conn:
cursor = conn.cursor()
# Load user barlows and reducers
cursor.execute("""
SELECT id, name, factor, equipment_type
FROM userequipment
WHERE equipment_type IN ('barlow', 'reducer')
ORDER BY equipment_type, factor DESC
""")
user_barlows = cursor.fetchall()
# Add user barlows/reducers section if there are any
if user_barlows:
self.barlow_combo.addItem("--- YOUR EQUIPMENT ---", None)
for eq_id, name, factor, eq_type in user_barlows:
if factor:
display_text = f"{name} ({factor}x)"
self.barlow_combo.addItem(display_text, {
"type": eq_type,
"factor": factor,
"source": "user",
"id": eq_id
})
logger.debug(f"Loaded {len(user_barlows)} user barlows/reducers")
except Exception as e:
logger.error(f"Error loading user barlows/reducers: {str(e)}")
def _load_aladin_settings(self):
"""Load persistent Aladin Lite settings from QSettings"""
try:
settings = QSettings("CosmosCollection", "AladinLite")
# Block signals during loading to prevent save being triggered
self.telescope_combo.blockSignals(True)
self.show_telescope_fov.blockSignals(True)
self.show_smart_telescopes.blockSignals(True)
self.camera_combo.blockSignals(True)
self.barlow_combo.blockSignals(True)
self.show_horizon.blockSignals(True)
# Load show smart telescopes checkbox and populate combo if needed
# (must happen before telescope name restore so smart entries are in the combo)
show_smart = settings.value("show_smart_telescopes", False, type=bool)
self.show_smart_telescopes.setChecked(show_smart)
if show_smart:
self._add_smart_telescopes()
logger.debug(f"Restored show smart telescopes: {show_smart}")
# Load telescope selection
saved_telescope_name = settings.value("telescope_name", None)
if saved_telescope_name:
# Find the telescope in the combo box
for i in range(self.telescope_combo.count()):
data = self.telescope_combo.itemData(i)
if data and data.get('name') == saved_telescope_name:
self.telescope_combo.setCurrentIndex(i)
self.selected_telescope = data
logger.debug(f"Restored telescope selection: {saved_telescope_name}")
break
# Load show telescope FOV checkbox
show_fov = settings.value("show_telescope_fov", False, type=bool)
self.show_telescope_fov.setChecked(show_fov)
logger.debug(f"Restored show telescope FOV: {show_fov}")
# Load camera/eyepiece selection
saved_camera_text = settings.value("camera_eyepiece", None)
if saved_camera_text:
index = self.camera_combo.findText(saved_camera_text)
if index >= 0:
self.camera_combo.setCurrentIndex(index)
logger.debug(f"Restored camera/eyepiece selection: {saved_camera_text}")
# Load barlow/reducer selection
saved_barlow_text = settings.value("barlow_reducer", None)
if saved_barlow_text:
index = self.barlow_combo.findText(saved_barlow_text)
if index >= 0:
self.barlow_combo.setCurrentIndex(index)
logger.debug(f"Restored barlow/reducer selection: {saved_barlow_text}")
# Load virtual horizon checkbox
show_horizon = settings.value("show_horizon", False, type=bool)
self.show_horizon.setChecked(show_horizon)
logger.debug(f"Restored show virtual horizon: {show_horizon}")
# Unblock signals
self.telescope_combo.blockSignals(False)
self.show_telescope_fov.blockSignals(False)
self.show_smart_telescopes.blockSignals(False)
self.camera_combo.blockSignals(False)
self.barlow_combo.blockSignals(False)
self.show_horizon.blockSignals(False)
logger.debug("Aladin Lite settings loaded successfully")
except Exception as e:
logger.error(f"Error loading Aladin settings: {str(e)}")
# Make sure to unblock signals even if there's an error
self.telescope_combo.blockSignals(False)
self.show_telescope_fov.blockSignals(False)
self.show_smart_telescopes.blockSignals(False)
self.camera_combo.blockSignals(False)
self.barlow_combo.blockSignals(False)
self.show_horizon.blockSignals(False)
def _save_aladin_settings(self):
"""Save persistent Aladin Lite settings to QSettings"""
try:
settings = QSettings("CosmosCollection", "AladinLite")
# Save telescope selection
telescope_data = self.telescope_combo.currentData()
if telescope_data:
settings.setValue("telescope_name", telescope_data.get('name'))
else:
settings.setValue("telescope_name", None)
# Save show telescope FOV checkbox
settings.setValue("show_telescope_fov", self.show_telescope_fov.isChecked())
# Save show smart telescopes checkbox
settings.setValue("show_smart_telescopes", self.show_smart_telescopes.isChecked())
# Save camera/eyepiece selection
settings.setValue("camera_eyepiece", self.camera_combo.currentText())
# Save barlow/reducer selection
settings.setValue("barlow_reducer", self.barlow_combo.currentText())
# Save virtual horizon checkbox
settings.setValue("show_horizon", self.show_horizon.isChecked())
logger.debug("Aladin Lite settings saved successfully")
except Exception as e:
logger.error(f"Error saving Aladin settings: {str(e)}")
def _add_smart_telescopes(self):
"""Append smart telescope entries to the telescope combo box."""
self.telescope_combo.addItem("--- SMART TELESCOPES ---", None)
for st in self.SMART_TELESCOPES:
display = f"{st['name']} ({st['focal_length']}mm f/{st['focal_length']/st['aperture']:.1f})"
self.telescope_combo.addItem(display, dict(st))
def _remove_smart_telescopes(self):
"""Remove all smart telescope entries (and separator) from the telescope combo box."""
i = 0
while i < self.telescope_combo.count():
text = self.telescope_combo.itemText(i)
data = self.telescope_combo.itemData(i)
if text == "--- SMART TELESCOPES ---" or (data and data.get('smart_telescope')):
self.telescope_combo.removeItem(i)
else:
i += 1
def _on_show_smart_telescopes_toggled(self, checked):
"""Handle Show Smart Telescopes checkbox toggle."""
if checked:
self._add_smart_telescopes()
else:
# If a smart telescope is currently selected, reset to Default View first
current_data = self.telescope_combo.currentData()
if current_data and current_data.get('smart_telescope'):
self.telescope_combo.setCurrentIndex(0)
self._remove_smart_telescopes()
self._save_aladin_settings()
def _on_telescope_changed(self):
"""Handle telescope selection change"""
current_data = self.telescope_combo.currentData()
if current_data:
self.selected_telescope = current_data
logger.debug(f"Selected telescope: {current_data['name']} ({current_data['focal_length']}mm)")
if current_data.get('smart_telescope'):
camera_text = current_data.get('camera_text')
if camera_text:
idx = self.camera_combo.findText(camera_text)
if idx >= 0:
self.camera_combo.blockSignals(True)
self.camera_combo.setCurrentIndex(idx)
self.camera_combo.blockSignals(False)
self.barlow_combo.blockSignals(True)
self.barlow_combo.setCurrentIndex(0) # "None (1.0x)"
self.barlow_combo.blockSignals(False)
else:
# Auto-select equipment associated with this telescope
self._select_telescope_equipment(current_data.get('id'))
else:
self.selected_telescope = None
logger.debug("Selected default view")
self._save_aladin_settings()
self._update_aladin_view()
def _select_telescope_equipment(self, telescope_id):
"""Auto-select equipment associated with the given telescope"""
if not telescope_id:
return
try:
with DatabaseManager().get_connection() as conn:
cursor = conn.cursor()
# Get all equipment IDs associated with this telescope
cursor.execute("""
SELECT e.id, e.equipment_type
FROM userequipment e
JOIN telescope_equipment te ON e.id = te.equipment_id
WHERE te.telescope_id = ?
ORDER BY e.name ASC
""", (telescope_id,))
equipment = cursor.fetchall()
# Find first camera or eyepiece and select it
camera_selected = False
barlow_selected = False
for eq_id, eq_type in equipment:
# Select first camera/eyepiece in the camera combo
if not camera_selected and eq_type in ('camera', 'eyepiece'):
for i in range(self.camera_combo.count()):
data = self.camera_combo.itemData(i)
if data and data.get('source') == 'user' and data.get('id') == eq_id:
self.camera_combo.blockSignals(True)
self.camera_combo.setCurrentIndex(i)
self.camera_combo.blockSignals(False)
camera_selected = True
logger.debug(f"Auto-selected camera/eyepiece ID {eq_id} for telescope")
break
# Select first barlow/reducer in the barlow combo
if not barlow_selected and eq_type in ('barlow', 'reducer'):
for i in range(self.barlow_combo.count()):
data = self.barlow_combo.itemData(i)
if data and data.get('source') == 'user' and data.get('id') == eq_id:
self.barlow_combo.blockSignals(True)
self.barlow_combo.setCurrentIndex(i)
self.barlow_combo.blockSignals(False)
barlow_selected = True
logger.debug(f"Auto-selected barlow/reducer ID {eq_id} for telescope")
break
except Exception as e:
logger.error(f"Error selecting telescope equipment: {str(e)}")
def _on_camera_changed(self):
"""Handle camera/sensor selection change"""
self._save_aladin_settings()
self._update_aladin_view()
def _on_barlow_changed(self):
"""Handle barlow/reducer selection change"""
self._save_aladin_settings()
self._update_aladin_view()
def _on_show_fov_toggled(self):
"""Handle show telescope FOV checkbox toggle"""
self._save_aladin_settings()
self._update_aladin_view()
def _calculate_telescope_fov(self):
"""Calculate telescope FOV based on selected telescope and camera/eyepiece"""
if not self.selected_telescope:
return None
telescope_fl = self.selected_telescope['focal_length'] # mm
telescope_aperture = self.selected_telescope.get('aperture', 100) # mm
# Get barlow/reducer factor
barlow_data = self.barlow_combo.currentData()
barlow_factor = 1.0 # Default no change
if barlow_data and 'factor' in barlow_data:
barlow_factor = barlow_data['factor']
# Apply barlow/reducer to effective focal length
effective_fl = telescope_fl * barlow_factor
camera_data = self.camera_combo.currentData()
if not camera_data or camera_data is None:
return None
if camera_data.get('type') == 'eyepiece':
# Visual observation with eyepiece
eyepiece_fl = camera_data['focal_length'] # mm
apparent_fov = camera_data['apparent_fov'] # degrees
# Calculate magnification using effective focal length
magnification = effective_fl / eyepiece_fl
# True FOV = Apparent FOV / Magnification
true_fov_deg = apparent_fov / magnification
true_fov_arcmin = true_fov_deg * 60
barlow_text = f" with {barlow_factor}x" if barlow_factor != 1.0 else ""
logger.debug(f"Eyepiece FOV calculation: {eyepiece_fl}mm eyepiece{barlow_text}, {apparent_fov}° AFOV, {magnification:.1f}x mag, {true_fov_arcmin:.1f}' true FOV")
barlow_details = f" + {barlow_factor}x" if barlow_factor != 1.0 else ""
return {
'width_arcmin': true_fov_arcmin,
'height_arcmin': true_fov_arcmin,
'type': 'visual',
'details': f"{eyepiece_fl}mm eyepiece{barlow_details}, {magnification:.0f}x mag"
}
elif camera_data.get('type') == 'camera':
# Camera sensor
sensor_width = camera_data['sensor_width'] # mm
sensor_height = camera_data['sensor_height'] # mm
# FOV = 2 * arctan(sensor_size / (2 * effective_focal_length)) * (180/π) * 60 (arcmin)
fov_width_rad = 2 * math.atan(sensor_width / (2 * effective_fl))
fov_height_rad = 2 * math.atan(sensor_height / (2 * effective_fl))
fov_width_arcmin = fov_width_rad * (180 / math.pi) * 60
fov_height_arcmin = fov_height_rad * (180 / math.pi) * 60
# Calculate pixel scale for additional info using effective focal length
pixel_scale_arcsec = 206265 * (sensor_width / 1000) / effective_fl # arcsec/mm (assuming square pixels)
barlow_text = f" with {barlow_factor}x" if barlow_factor != 1.0 else ""
logger.debug(f"Camera FOV calculation: {sensor_width}x{sensor_height}mm sensor, {effective_fl}mm effective FL{barlow_text}, FOV={fov_width_arcmin:.1f}'x{fov_height_arcmin:.1f}'")
barlow_details = f" + {barlow_factor}x" if barlow_factor != 1.0 else ""
return {
'width_arcmin': fov_width_arcmin,
'height_arcmin': fov_height_arcmin,
'type': 'camera',
'details': f"{sensor_width}×{sensor_height}mm sensor{barlow_details}",
'pixel_scale_arcsec': pixel_scale_arcsec
}
return None
def _update_aladin_view(self, preserve_target=True):
"""Update the Aladin Lite view with current settings
Args:
preserve_target: If True, preserve current target when updating FOV overlays
"""
# Check if web view is available
if not self.web_view:
logger.debug("Web view not yet created, skipping Aladin update")
return
# Determine FOV to use
telescope_fov_data = None
display_fov = self.default_fov
if self.selected_telescope and self.show_telescope_fov.isChecked():
telescope_fov_data = self._calculate_telescope_fov()
if telescope_fov_data:
# Use the larger dimension for display FOV, but convert to degrees and add reasonable margin
telescope_fov_arcmin = max(telescope_fov_data['width_arcmin'], telescope_fov_data['height_arcmin'])
display_fov = telescope_fov_arcmin / 60.0 * 1.5 # Convert to degrees and add 50% margin
logger.debug(f"Telescope FOV: {telescope_fov_arcmin:.1f}' -> Display FOV: {display_fov:.3f}°")
self.current_fov = display_fov
# If preserving target and we already have a page loaded, just update the FOV overlay
if preserve_target and self.current_target and hasattr(self, 'web_view') and self.web_view.url().toString():
logger.debug("Preserving target - updating FOV overlay only")
if telescope_fov_data and self.show_telescope_fov.isChecked():
self.pending_fov_overlay = telescope_fov_data
self.target_coordinates = self.current_target
self._inject_fov_overlay(True)
else:
# Remove FOV overlay
self._remove_fov_overlay()
self._update_fov_info()
return
# Build Aladin URL for full page load
base_url = "https://aladin.u-strasbg.fr/AladinLite/?"
# Determine target to use
target_id = None
if preserve_target and self.current_target:
# Use current target for URL
target_id = self.current_target
logger.debug(f"Using current target for URL: {target_id}")
else:
# Use original data to set initial target
if 'ra_deg' in self.data and 'dec_deg' in self.data and self.data['ra_deg'] is not None and self.data['dec_deg'] is not None:
ra = self.data['ra_deg']
dec = self.data['dec_deg']
# Format coordinates properly for Aladin (space-separated)
target_id = f"{ra} {dec}"
logger.debug(f"Using coordinates for Aladin target: RA={ra}, Dec={dec}")
else:
# Fallback to object names
target_id = self.data.get('name', '')
logger.debug(f"Using object name for Aladin target: {target_id}")
# If still no target, try dsodetailid
if not target_id:
target_id = self.data.get('dsodetailid', '')
logger.debug(f"Using dsodetailid for Aladin target: {target_id}")
if not target_id:
logger.error(f"No valid target found for Aladin. Data keys: {list(self.data.keys())}")
target_id = "M1" # Default fallback
# Store the target
self.current_target = target_id
# URL encode the target if it contains coordinates
encoded_target = urllib.parse.quote(str(target_id))
# Build URL with parameters
url_params = [
f"target={encoded_target}",
f"fov={display_fov}",
"survey=P%2FDSS2%2Fcolor",
"showReticle=true"
]
# Always use standard Aladin URL first
image_url = f"{base_url}{'&'.join(url_params)}"
logger.debug(f"Final Aladin URL: {image_url}")
# Safely load the URL with error handling
try:
if hasattr(self, 'web_view') and self.web_view:
logger.debug(f"Loading Aladin URL: {image_url}")
self.web_view.setUrl(QUrl(image_url))
# Test connectivity by trying a simple request first
self._test_connectivity_async()
else:
logger.error("Web view not available for URL loading")
raise Exception("Web view not available")
except Exception as e:
logger.error(f"Error loading Aladin URL: {e}")
# Show error in placeholder
if self.web_placeholder:
self.web_placeholder.setText(f"Error loading Aladin Lite\n{str(e)}\n\nClick below to open in browser instead.")
self.web_placeholder.setStyleSheet(f"QLabel {{ background-color: {COLORS['background']}; color: {COLORS['error']}; font-size: 12px; }}")
self._add_browser_fallback_button()
# Add telescope FOV overlay using JavaScript injection if enabled
if telescope_fov_data and self.show_telescope_fov.isChecked():
logger.debug(f"Will inject FOV overlay. Telescope: {self.selected_telescope['name']}, FOV: {telescope_fov_data['width_arcmin']:.1f}'x{telescope_fov_data['height_arcmin']:.1f}', Type: {telescope_fov_data['type']}")
# Store the FOV data for injection after page loads
self.pending_fov_overlay = telescope_fov_data
self.target_coordinates = target_id
# The FOV overlay injection will be handled by the main loadFinished handler
else:
self.pending_fov_overlay = None