-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSOTargetList.py
More file actions
1813 lines (1506 loc) · 76.7 KB
/
Copy pathDSOTargetList.py
File metadata and controls
1813 lines (1506 loc) · 76.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
#!/usr/bin/env python3
"""
DSO Target List Manager
Allows users to manage their observing target list for deep sky objects
"""
import sys
import os
import calendar
from datetime import datetime
from PySide6.QtCore import Qt, QTimer, Signal, QStringListModel
from PySide6.QtWidgets import (QMainWindow, QVBoxLayout, QHBoxLayout,
QWidget, QPushButton, QLabel, QTableWidget,
QTableWidgetItem, QGroupBox, QMessageBox,
QHeaderView, QTextEdit, QDialog, QComboBox,
QLineEdit, QCheckBox, QDateEdit, QSpinBox, QMenu,
QCompleter)
from PySide6.QtGui import QFont
from DatabaseManager import DatabaseManager
from BestDSOTonight import BestDSOTonightWindow
from WindowPositionManager import WindowPositionMixin
from Theme import COLORS
from NINAIntegration import NINAIntegration
import logging
# Set up logging
logger = logging.getLogger(__name__)
class PriorityTableWidgetItem(QTableWidgetItem):
"""Custom QTableWidgetItem that sorts priorities correctly"""
PRIORITY_ORDER = {"Urgent": 4, "High": 3, "Medium": 2, "Low": 1}
def __init__(self, priority_text):
super().__init__(priority_text)
self.priority_value = self.PRIORITY_ORDER.get(priority_text, 0)
self.setTextAlignment(Qt.AlignCenter)
def __lt__(self, other):
"""Override less-than operator for proper sorting"""
if isinstance(other, PriorityTableWidgetItem):
return self.priority_value < other.priority_value
return super().__lt__(other)
class AddTargetDialog(QDialog):
"""Dialog for adding a new target to the list"""
def __init__(self, dso_data=None, parent=None):
super().__init__(parent)
self.setWindowTitle("Add Target to List")
self.setWindowFlags(Qt.Dialog | Qt.WindowCloseButtonHint)
self.setModal(True)
self.resize(500, 400)
self.dso_data = dso_data
self.db_manager = DatabaseManager()
self.is_edit_mode = False # Track if we're editing an existing target
self.target_id = None # Store the ID of the target being edited
self._dso_cache = {} # Cache for autocomplete results
# Debounce timer for DSO catalog search
self._search_timer = QTimer()
self._search_timer.setSingleShot(True)
self._search_timer.setInterval(300)
self._search_timer.timeout.connect(self._do_dso_search)
self._pending_search_text = ""
self._setup_ui()
# Pre-fill with DSO data if provided
if self.dso_data:
self._populate_from_dso_data()
def _setup_ui(self):
"""Set up the dialog UI"""
layout = QVBoxLayout()
# DSO Information Group
dso_group = QGroupBox("DSO Information")
dso_layout = QVBoxLayout()
# Name
name_layout = QHBoxLayout()
name_layout.addWidget(QLabel("Name:"))
self.name_edit = QLineEdit()
self.name_edit.setPlaceholderText("e.g., M 31, NGC 7000, IC 1396")
# Set up autocomplete for DSO catalog
self._completer_model = QStringListModel()
self._completer = QCompleter()
self._completer.setModel(self._completer_model)
self._completer.setCaseSensitivity(Qt.CaseInsensitive)
self._completer.setFilterMode(Qt.MatchContains)
self.name_edit.setCompleter(self._completer)
self._completer.activated.connect(self._on_dso_selected)
self.name_edit.textChanged.connect(self._on_name_text_changed)
name_layout.addWidget(self.name_edit)
dso_layout.addLayout(name_layout)
# Type and Constellation
type_constellation_layout = QHBoxLayout()
type_constellation_layout.addWidget(QLabel("Type:"))
self.type_edit = QLineEdit()
type_constellation_layout.addWidget(self.type_edit)
type_constellation_layout.addWidget(QLabel("Constellation:"))
self.constellation_edit = QLineEdit()
type_constellation_layout.addWidget(self.constellation_edit)
dso_layout.addLayout(type_constellation_layout)
# Coordinates
coord_layout = QHBoxLayout()
coord_layout.addWidget(QLabel("RA (deg):"))
self.ra_edit = QLineEdit()
coord_layout.addWidget(self.ra_edit)
coord_layout.addWidget(QLabel("Dec (deg):"))
self.dec_edit = QLineEdit()
coord_layout.addWidget(self.dec_edit)
dso_layout.addLayout(coord_layout)
# Magnitude and Size
mag_size_layout = QHBoxLayout()
mag_size_layout.addWidget(QLabel("Magnitude:"))
self.magnitude_edit = QLineEdit()
coord_layout.addWidget(self.magnitude_edit)
mag_size_layout.addWidget(QLabel("Size ('):"))
self.size_edit = QLineEdit()
mag_size_layout.addWidget(self.size_edit)
dso_layout.addLayout(mag_size_layout)
dso_group.setLayout(dso_layout)
layout.addWidget(dso_group)
# Target Information Group
target_group = QGroupBox("Target Information")
target_layout = QVBoxLayout()
# Priority
priority_layout = QHBoxLayout()
priority_layout.addWidget(QLabel("Priority:"))
self.priority_combo = QComboBox()
self.priority_combo.addItems(["Low", "Medium", "High", "Urgent"])
self.priority_combo.setCurrentText("Medium")
priority_layout.addWidget(self.priority_combo)
# Status
priority_layout.addWidget(QLabel("Status:"))
self.status_combo = QComboBox()
self.status_combo.addItems(["Not Observed", "Observed", "Imaged", "Completed"])
self.status_combo.setCurrentText("Not Observed")
priority_layout.addWidget(self.status_combo)
target_layout.addLayout(priority_layout)
# Telescope
telescope_layout = QHBoxLayout()
telescope_layout.addWidget(QLabel("Telescope:"))
self.telescope_combo = QComboBox()
self._populate_telescope_combo()
telescope_layout.addWidget(self.telescope_combo)
telescope_layout.addStretch()
target_layout.addLayout(telescope_layout)
# Best months for observing
months_layout = QHBoxLayout()
months_layout.addWidget(QLabel("Best Months:"))
self.months_edit = QLineEdit()
self.months_edit.setPlaceholderText("e.g., Nov-Feb, Mar-Jun")
months_layout.addWidget(self.months_edit)
target_layout.addLayout(months_layout)
# Notes
notes_layout = QVBoxLayout()
notes_layout.addWidget(QLabel("Notes:"))
self.notes_edit = QTextEdit()
self.notes_edit.setMaximumHeight(100)
self.notes_edit.setPlaceholderText("Observing notes, equipment recommendations, etc.")
notes_layout.addWidget(self.notes_edit)
target_layout.addLayout(notes_layout)
target_group.setLayout(target_layout)
layout.addWidget(target_group)
# Buttons
buttons_layout = QHBoxLayout()
buttons_layout.addStretch()
cancel_btn = QPushButton("Cancel")
cancel_btn.clicked.connect(self.reject)
buttons_layout.addWidget(cancel_btn)
self.save_btn = QPushButton("Add to Target List")
self.save_btn.clicked.connect(self._save_target)
self.save_btn.setDefault(True)
buttons_layout.addWidget(self.save_btn)
layout.addLayout(buttons_layout)
self.setLayout(layout)
def set_edit_mode(self, target_id):
"""Set the dialog to edit mode, changing the button text"""
self.is_edit_mode = True
self.target_id = target_id
self.save_btn.setText("Save Changes")
def _populate_telescope_combo(self):
"""Populate telescope dropdown with active telescopes"""
self.telescope_combo.clear()
self.telescope_combo.addItem("Any", None) # First item for unassigned
try:
with self.db_manager.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT id, name, aperture, focal_length
FROM usertelescopes
WHERE is_active = 1
ORDER BY name
""")
telescopes = cursor.fetchall()
for telescope in telescopes:
tel_id, name, aperture, focal_length = telescope
# Calculate f/ratio if we have both values
if aperture and focal_length and aperture > 0:
f_ratio = focal_length / aperture
display_text = f"{name} ({int(aperture)}mm f/{f_ratio:.1f})"
elif aperture:
display_text = f"{name} ({int(aperture)}mm)"
else:
display_text = name
self.telescope_combo.addItem(display_text, tel_id)
except Exception as e:
logger.error(f"Error loading telescopes: {str(e)}")
def _populate_from_dso_data(self):
"""Populate dialog fields with DSO data"""
if not self.dso_data:
return
self.name_edit.setText(self.dso_data.get("name", ""))
self.type_edit.setText(self.dso_data.get("dso_type", ""))
self.constellation_edit.setText(self.dso_data.get("constellation", ""))
# Handle numeric fields - only set if value is not None
ra_deg = self.dso_data.get("ra_deg")
if ra_deg is not None:
self.ra_edit.setText(str(ra_deg))
dec_deg = self.dso_data.get("dec_deg")
if dec_deg is not None:
self.dec_edit.setText(str(dec_deg))
magnitude = self.dso_data.get("magnitude")
if magnitude is not None:
self.magnitude_edit.setText(str(magnitude))
# Format size
size_min = self.dso_data.get("size_min", 0)
size_max = self.dso_data.get("size_max", 0)
if size_min > 0 or size_max > 0:
self.size_edit.setText(f"{size_min:.1f} x {size_max:.1f}")
# Populate best months if available
self.months_edit.setText(self.dso_data.get("best_months", ""))
def _on_name_text_changed(self, text):
"""Handle text changes in the name field — debounce before searching"""
text = text.strip()
if len(text) < 2:
self._completer_model.setStringList([])
self._dso_cache.clear()
return
self._pending_search_text = text
self._search_timer.start()
def _do_dso_search(self):
"""Execute the DSO catalog search after debounce"""
text = self._pending_search_text
if len(text) < 2:
return
self._search_dso_catalog(text)
def _search_dso_catalog(self, text):
"""Search the DSO catalog and update completer suggestions"""
try:
with self.db_manager.get_connection() as conn:
cursor = conn.cursor()
# Try to parse a catalogue prefix (e.g., "M 3", "NGC 70", "IC 13")
catalogue = None
designation_part = None
text_upper = text.upper().strip()
for prefix in ("NGC", "IC", "M"):
if text_upper.startswith(prefix):
remainder = text_upper[len(prefix):]
# Ensure remainder is empty, starts with space, or a digit
if remainder == "" or remainder[0] in (" ", "-") or remainder[0].isdigit():
catalogue = prefix
designation_part = remainder.strip()
break
if catalogue and designation_part is not None:
# Search within a specific catalogue
cursor.execute("""
SELECT c.catalogue || ' ' || c.designation as name,
d.ra, d.dec, d.magnitude,
d.sizemin / 60.0 as sizemin,
d.sizemax / 60.0 as sizemax,
d.constellation, d.dsotype
FROM cataloguenr c
JOIN dsodetail d ON d.id = c.dsodetailid
WHERE c.catalogue = ? AND c.designation LIKE ?
ORDER BY CAST(c.designation AS INTEGER), c.designation
LIMIT 20
""", (catalogue, designation_part + "%"))
else:
# Search across all catalogues
cursor.execute("""
SELECT c.catalogue || ' ' || c.designation as name,
d.ra, d.dec, d.magnitude,
d.sizemin / 60.0 as sizemin,
d.sizemax / 60.0 as sizemax,
d.constellation, d.dsotype
FROM cataloguenr c
JOIN dsodetail d ON d.id = c.dsodetailid
WHERE c.catalogue || ' ' || c.designation LIKE ?
ORDER BY c.catalogue, CAST(c.designation AS INTEGER), c.designation
LIMIT 20
""", ("%" + text + "%",))
results = cursor.fetchall()
self._dso_cache.clear()
names = []
for row in results:
name = row[0]
names.append(name)
self._dso_cache[name] = {
"ra": row[1],
"dec": row[2],
"magnitude": row[3],
"sizemin": row[4],
"sizemax": row[5],
"constellation": row[6],
"dsotype": row[7],
}
self._completer_model.setStringList(names)
except Exception as e:
logger.error(f"Error searching DSO catalog: {str(e)}")
def _on_dso_selected(self, text):
"""Auto-fill fields when a DSO suggestion is selected"""
data = self._dso_cache.get(text)
if not data:
return
# Type mapping (same as DSOTargetListWindow._get_friendly_type_name)
type_mapping = {
"GALXY": "Galaxy", "DRKNB": "Dark Nebula", "OPNCL": "Open Cluster",
"PLNNB": "Planetary Nebula", "BRTNB": "Bright Nebula",
"SNREM": "Supernova Remnant", "GALCL": "Galaxy Cluster",
"GLOCL": "Globular Cluster", "CL+NB": "Cluster + Nebula",
"GX+DN": "Galaxy + Dark Nebula", "ASTER": "Asterism",
"2STAR": "Double Star", "3STAR": "Triple Star",
"4STAR": "Quadruple Star", "1STAR": "Single Star",
"QUASR": "Quasar", "NONEX": "Non-existent",
}
dsotype = data.get("dsotype", "")
self.type_edit.setText(type_mapping.get(dsotype, dsotype or ""))
self.constellation_edit.setText(data.get("constellation") or "")
ra = data.get("ra")
if ra is not None:
self.ra_edit.setText(str(round(ra, 6)))
dec = data.get("dec")
if dec is not None:
self.dec_edit.setText(str(round(dec, 6)))
mag = data.get("magnitude")
if mag is not None:
self.magnitude_edit.setText(str(round(mag, 2)))
else:
self.magnitude_edit.setText("")
sizemin = data.get("sizemin") or 0
sizemax = data.get("sizemax") or 0
if sizemin > 0 or sizemax > 0:
self.size_edit.setText(f"{sizemin:.1f} x {sizemax:.1f}")
else:
self.size_edit.setText("")
def _save_target(self):
"""Save the target to the database"""
try:
# Validate required fields
if not self.name_edit.text().strip():
QMessageBox.warning(self, "Validation Error", "Name is required.")
return
# Helper function to safely convert to float
def safe_float(text):
"""Convert text to float, handling empty strings and 'None'"""
text = text.strip()
if not text or text.lower() == 'none':
return 0.0
return float(text)
# Create target data
target_data = {
"name": self.name_edit.text().strip(),
"dso_type": self.type_edit.text().strip(),
"constellation": self.constellation_edit.text().strip(),
"ra_deg": safe_float(self.ra_edit.text()),
"dec_deg": safe_float(self.dec_edit.text()),
"magnitude": safe_float(self.magnitude_edit.text()),
"size_info": self.size_edit.text().strip(),
"priority": self.priority_combo.currentText(),
"status": self.status_combo.currentText(),
"best_months": self.months_edit.text().strip(),
"notes": self.notes_edit.toPlainText().strip(),
"date_added": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"telescope_id": self.telescope_combo.currentData()
}
# Save to database - either INSERT new or UPDATE existing
with self.db_manager.get_connection() as conn:
cursor = conn.cursor()
if self.is_edit_mode and self.target_id:
# Update existing record
cursor.execute("""
UPDATE usertargetlist SET
name = ?, dso_type = ?, constellation = ?, ra_deg = ?, dec_deg = ?,
magnitude = ?, size_info = ?, priority = ?, status = ?,
best_months = ?, notes = ?, telescope_id = ?
WHERE id = ?
""", (
target_data["name"], target_data["dso_type"], target_data["constellation"],
target_data["ra_deg"], target_data["dec_deg"], target_data["magnitude"],
target_data["size_info"], target_data["priority"], target_data["status"],
target_data["best_months"], target_data["notes"], target_data["telescope_id"],
self.target_id
))
success_message = f"{target_data['name']} has been updated in your target list."
else:
# Insert new record
cursor.execute("""
INSERT INTO usertargetlist (
name, dso_type, constellation, ra_deg, dec_deg, magnitude,
size_info, priority, status, best_months, notes, date_added, telescope_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
target_data["name"], target_data["dso_type"], target_data["constellation"],
target_data["ra_deg"], target_data["dec_deg"], target_data["magnitude"],
target_data["size_info"], target_data["priority"], target_data["status"],
target_data["best_months"], target_data["notes"], target_data["date_added"],
target_data["telescope_id"]
))
success_message = f"{target_data['name']} has been added to your target list."
conn.commit()
QMessageBox.information(self, "Success", success_message)
self.accept()
except ValueError as e:
QMessageBox.warning(self, "Validation Error", "Please enter valid numeric values for coordinates and magnitude.")
except Exception as e:
logger.error(f"Error saving target: {str(e)}")
QMessageBox.critical(self, "Error", f"Failed to save target: {str(e)}")
class DSOTargetListWindow(WindowPositionMixin, QMainWindow):
WINDOW_POSITION_KEY = "DSOTargetList"
"""Main window for DSO target list management"""
def __init__(self):
super().__init__()
self.setAttribute(Qt.WA_QuitOnClose, False)
self.setWindowTitle("DSO Target List - Cosmos Collection")
self.resize(1210, 850)
self.setup_window_position()
self.db_manager = DatabaseManager()
self.targets_data = []
self._init_database()
self._init_ui()
self._load_targets()
def _init_database(self):
"""Initialize the target list database table"""
try:
with self.db_manager.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS usertargetlist (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
dso_type TEXT,
constellation TEXT,
ra_deg REAL,
dec_deg REAL,
magnitude REAL,
size_info TEXT,
priority TEXT DEFAULT 'Medium',
status TEXT DEFAULT 'Not Observed',
best_months TEXT,
notes TEXT,
date_added TEXT,
date_observed TEXT,
created_date TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
logger.debug("DSO target list table initialized successfully")
except Exception as e:
logger.error(f"Error initializing target list database: {str(e)}")
def _populate_telescope_filter(self):
"""Populate telescope filter dropdown with all telescopes (including inactive)"""
self.telescope_filter.clear()
self.telescope_filter.addItem("All", "all")
self.telescope_filter.addItem("Unassigned", "unassigned")
try:
with self.db_manager.get_connection() as conn:
cursor = conn.cursor()
# Include all telescopes (even inactive) since targets may reference them
cursor.execute("""
SELECT id, name, is_active
FROM usertelescopes
ORDER BY name
""")
telescopes = cursor.fetchall()
for telescope in telescopes:
tel_id, name, is_active = telescope
display_text = name if is_active else f"{name} (inactive)"
self.telescope_filter.addItem(display_text, tel_id)
except Exception as e:
logger.error(f"Error loading telescopes for filter: {str(e)}")
def _init_ui(self):
"""Initialize the user interface"""
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
# Header
header_label = QLabel("DSO Target List")
header_label.setAlignment(Qt.AlignCenter)
header_label.setStyleSheet("font-size: 18px; font-weight: bold; margin: 10px;")
main_layout.addWidget(header_label)
# Control panel
control_group = QGroupBox("Target List Management")
control_layout = QVBoxLayout()
# Search row
search_row = QHBoxLayout()
self.search_box = QLineEdit()
self.search_box.setPlaceholderText("Search name, type, constellation...")
self.search_box.setFixedWidth(280)
self.search_box.textChanged.connect(self._filter_targets)
self.search_box.setClearButtonEnabled(True)
search_row.addWidget(QLabel("Search:"))
search_row.addWidget(self.search_box)
search_row.addStretch()
control_layout.addLayout(search_row)
# Buttons and filter row
buttons_row = QHBoxLayout()
# Add target button
add_target_btn = QPushButton("Add New Target")
add_target_btn.clicked.connect(self._add_new_target)
buttons_row.addWidget(add_target_btn)
# Edit target button
self.edit_target_btn = QPushButton("Edit Selected")
self.edit_target_btn.clicked.connect(self._edit_selected_target)
self.edit_target_btn.setEnabled(False)
buttons_row.addWidget(self.edit_target_btn)
# View details button
self.view_details_btn = QPushButton("View Details")
self.view_details_btn.clicked.connect(self._view_target_details)
self.view_details_btn.setEnabled(False)
self.view_details_btn.setToolTip("Open detailed view of selected target")
buttons_row.addWidget(self.view_details_btn)
# Remove target button
self.remove_target_btn = QPushButton("Remove Selected")
self.remove_target_btn.clicked.connect(self._remove_selected_target)
self.remove_target_btn.setEnabled(False)
buttons_row.addWidget(self.remove_target_btn)
# Best DSO Tonight button
best_tonight_btn = QPushButton("Best DSO Tonight")
best_tonight_btn.clicked.connect(self._open_best_dso_tonight)
best_tonight_btn.setToolTip("Open Best DSO Tonight window to find the best objects to observe tonight")
buttons_row.addWidget(best_tonight_btn)
buttons_row.addStretch()
# Filter controls
buttons_row.addWidget(QLabel("Filter by Status:"))
self.status_filter = QComboBox()
self.status_filter.addItems(["All", "Not Observed", "Observed", "Imaged", "Completed"])
self.status_filter.currentTextChanged.connect(self._filter_targets)
buttons_row.addWidget(self.status_filter)
buttons_row.addWidget(QLabel("Filter by Priority:"))
self.priority_filter = QComboBox()
self.priority_filter.addItems(["All", "Low", "Medium", "High", "Urgent"])
self.priority_filter.currentTextChanged.connect(self._filter_targets)
buttons_row.addWidget(self.priority_filter)
buttons_row.addWidget(QLabel("Telescope:"))
self.telescope_filter = QComboBox()
self._populate_telescope_filter()
self.telescope_filter.currentIndexChanged.connect(self._filter_targets)
buttons_row.addWidget(self.telescope_filter)
# Refresh button
refresh_btn = QPushButton("Refresh")
refresh_btn.clicked.connect(self._load_targets)
buttons_row.addWidget(refresh_btn)
control_layout.addLayout(buttons_row)
control_group.setLayout(control_layout)
main_layout.addWidget(control_group)
# Targets table
targets_group = QGroupBox("Target List")
targets_layout = QVBoxLayout()
self.targets_table = QTableWidget()
self.targets_table.setColumnCount(11)
self.targets_table.setHorizontalHeaderLabels([
"Name", "Type", "Constellation", "Magnitude", "Size",
"Priority", "Status", "Telescope", "Direction", "Best Months", "Date Added"
])
# Enable sorting and disable editing
self.targets_table.setSortingEnabled(True)
# Set column widths - Allow manual resizing
header = self.targets_table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeToContents) # Name column autosizes to content
for col in range(1, 11):
header.setSectionResizeMode(col, QHeaderView.Interactive) # Other columns allow manual resizing
# Set initial default widths for manually resizable columns
self.targets_table.setColumnWidth(1, 120) # Type
self.targets_table.setColumnWidth(2, 100) # Constellation
self.targets_table.setColumnWidth(3, 90) # Magnitude
self.targets_table.setColumnWidth(4, 80) # Size
self.targets_table.setColumnWidth(5, 90) # Priority
self.targets_table.setColumnWidth(6, 100) # Status
self.targets_table.setColumnWidth(7, 120) # Telescope
self.targets_table.setColumnWidth(8, 70) # Direction
self.targets_table.setColumnWidth(9, 150) # Best Months
self.targets_table.setColumnWidth(10, 100) # Date Added
self.targets_table.setAlternatingRowColors(True)
self.targets_table.setSelectionBehavior(QTableWidget.SelectRows)
self.targets_table.setEditTriggers(QTableWidget.NoEditTriggers) # Disable cell editing
self.targets_table.selectionModel().selectionChanged.connect(self._on_selection_changed)
self.targets_table.itemDoubleClicked.connect(self._edit_selected_target)
# Enable context menu
self.targets_table.setContextMenuPolicy(Qt.CustomContextMenu)
self.targets_table.customContextMenuRequested.connect(self._show_context_menu)
targets_layout.addWidget(self.targets_table)
targets_group.setLayout(targets_layout)
main_layout.addWidget(targets_group)
# Status bar
self.status_label = QLabel("Ready")
main_layout.addWidget(self.status_label)
def _add_new_target(self):
"""Add a new target to the list"""
dialog = AddTargetDialog(parent=self)
if dialog.exec() == QDialog.Accepted:
self._load_targets()
def _edit_selected_target(self):
"""Edit the selected target"""
current_row = self.targets_table.currentRow()
if current_row < 0:
QMessageBox.warning(self, "No Selection", "Please select a target to edit.")
return
# Get target data from the name item (column 0) to handle sorting
name_item = self.targets_table.item(current_row, 0)
if not name_item:
return
target_data = name_item.data(Qt.UserRole)
dialog = AddTargetDialog(dso_data=target_data, parent=self)
dialog.setWindowTitle("Edit Target")
dialog.set_edit_mode(target_data["id"]) # Change button text to "Save Changes" and set target ID
# Pre-populate with target data
dialog.name_edit.setText(target_data.get("name", ""))
dialog.type_edit.setText(target_data.get("dso_type", ""))
dialog.constellation_edit.setText(target_data.get("constellation", ""))
# Handle numeric fields - only set if value is not None
ra_deg = target_data.get("ra_deg")
if ra_deg is not None:
dialog.ra_edit.setText(str(ra_deg))
dec_deg = target_data.get("dec_deg")
if dec_deg is not None:
dialog.dec_edit.setText(str(dec_deg))
magnitude = target_data.get("magnitude")
if magnitude is not None:
dialog.magnitude_edit.setText(str(magnitude))
dialog.size_edit.setText(target_data.get("size_info", ""))
dialog.priority_combo.setCurrentText(target_data.get("priority", "Medium"))
dialog.status_combo.setCurrentText(target_data.get("status", "Not Observed"))
dialog.months_edit.setText(target_data.get("best_months", ""))
dialog.notes_edit.setPlainText(target_data.get("notes", ""))
# Set telescope selection
telescope_id = target_data.get("telescope_id")
if telescope_id is not None:
index = dialog.telescope_combo.findData(telescope_id)
if index >= 0:
dialog.telescope_combo.setCurrentIndex(index)
else:
dialog.telescope_combo.setCurrentIndex(0) # "Any"
if dialog.exec() == QDialog.Accepted:
# Store the target ID to re-select after reload
edited_target_id = target_data["id"]
# Reload targets to reflect the changes (dialog already handles the database update)
self._load_targets()
# Re-select the edited target
self._select_target_by_id(edited_target_id)
def _select_target_by_id(self, target_id):
"""Find and select a target row by its ID"""
for row in range(self.targets_table.rowCount()):
name_item = self.targets_table.item(row, 0)
if name_item:
row_data = name_item.data(Qt.UserRole)
if row_data and row_data.get("id") == target_id:
self.targets_table.selectRow(row)
self.targets_table.scrollToItem(name_item)
return
def _remove_selected_target(self):
"""Remove the selected target from the list"""
current_row = self.targets_table.currentRow()
if current_row < 0:
QMessageBox.warning(self, "No Selection", "Please select a target to remove.")
return
# Get target data from the name item (column 0) to handle sorting
name_item = self.targets_table.item(current_row, 0)
if not name_item:
return
target_data = name_item.data(Qt.UserRole)
target_name = target_data.get("name", "Unknown")
reply = QMessageBox.question(
self, "Confirm Removal",
f"Are you sure you want to remove '{target_name}' from your target list?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No
)
if reply == QMessageBox.Yes:
try:
with self.db_manager.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM usertargetlist WHERE id = ?", (target_data["id"],))
conn.commit()
QMessageBox.information(self, "Success", f"'{target_name}' has been removed from your target list.")
self._load_targets()
except Exception as e:
logger.error(f"Error removing target: {str(e)}")
QMessageBox.critical(self, "Error", f"Failed to remove target: {str(e)}")
def _on_selection_changed(self):
"""Handle selection changes in the table"""
has_selection = self.targets_table.currentRow() >= 0
self.edit_target_btn.setEnabled(has_selection)
self.view_details_btn.setEnabled(has_selection)
self.remove_target_btn.setEnabled(has_selection)
def _open_best_dso_tonight(self):
"""Open the Best DSO Tonight window"""
try:
# Create and show the Best DSO Tonight window with target list auto-selected
self.best_dso_window = BestDSOTonightWindow(use_target_list=True)
self.best_dso_window.show()
self.best_dso_window.raise_()
self.best_dso_window.activateWindow()
logger.debug("Best DSO Tonight window opened successfully with target list selected")
except Exception as e:
logger.error(f"Error opening Best DSO Tonight window: {str(e)}", exc_info=True)
QMessageBox.critical(self, "Error", f"Failed to open Best DSO Tonight window: {str(e)}")
def _view_target_details(self):
"""Open DSODetailWindow for the selected target"""
current_row = self.targets_table.currentRow()
if current_row < 0:
QMessageBox.warning(self, "No Selection", "Please select a target to view details.")
return
# Get target data from the name item (column 0) to handle sorting
name_item = self.targets_table.item(current_row, 0)
if not name_item:
return
try:
target_data = name_item.data(Qt.UserRole)
target_name = target_data.get("name", "")
# Import DSODetailWindow from main.py
from main import DSODetailWindow
# Try to find the complete DSO data in the main database
detail_data = self._get_full_dso_data(target_name, target_data)
if detail_data:
# Create and show the DSODetailWindow with full data
detail_window = DSODetailWindow(detail_data, self)
detail_window.show()
else:
QMessageBox.warning(self, "Object Not Found",
f"Could not find complete information for {target_name} in the main DSO database.")
except ImportError as e:
QMessageBox.critical(self, "Error", "Could not import DSODetailWindow. Please ensure Main.py is available.")
logger.error(f"Failed to import DSODetailWindow: {str(e)}")
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to open target details: {str(e)}")
logger.error(f"Error opening target details: {str(e)}")
def _get_full_dso_data(self, target_name, target_data):
"""Get full DSO data from the main database"""
try:
with self.db_manager.get_connection() as conn:
cursor = conn.cursor()
# Parse the target name to get catalogue and designation
name_parts = target_name.split()
if len(name_parts) >= 2:
catalogue = name_parts[0]
designation = " ".join(name_parts[1:])
else:
# If name doesn't have clear catalogue/designation, try to find by coordinates
return self._get_dso_data_by_coordinates(target_data)
# Query the full DSO data using the same method as Main.py
cursor.execute("""
WITH object_dsodetailid AS (
SELECT d.id
FROM dsodetail d
JOIN cataloguenr c ON d.id = c.dsodetailid
WHERE c.catalogue = ? AND c.designation = ?
)
SELECT d.id, d.ra, d.dec, d.magnitude, d.surfacebrightness,
CAST(d.sizemin/60.0 AS REAL) as sizemin,
CAST(d.sizemax/60.0 AS REAL) as sizemax,
d.constellation, d.dsotype, d.dsoclass,
GROUP_CONCAT(c.catalogue || ' ' || c.designation, ', ' ORDER BY
CASE c.catalogue
WHEN 'M' THEN 1
WHEN 'NGC' THEN 2
WHEN 'IC' THEN 3
ELSE 4
END, c.designation) as designations,
ui.image_path, ui.integration_time, ui.equipment, ui.date_taken, ui.notes,
(SELECT COUNT(*) FROM userimages WHERE dsodetailid = d.id) as image_count
FROM dsodetail d
JOIN cataloguenr c ON d.id = c.dsodetailid
LEFT JOIN userimages ui ON d.id = ui.dsodetailid
WHERE d.id = (SELECT id FROM object_dsodetailid)
GROUP BY d.id
""", (catalogue, designation))
result = cursor.fetchone()
if result:
return self._process_dso_query_result(result, target_data)
else:
# If not found by name, try by coordinates
return self._get_dso_data_by_coordinates(target_data)
except Exception as e:
logger.error(f"Error querying DSO database: {str(e)}")
return None
def _get_dso_data_by_coordinates(self, target_data):
"""Try to find DSO by coordinates (within reasonable tolerance)"""
try:
ra_deg = target_data.get("ra_deg", 0)
dec_deg = target_data.get("dec_deg", 0)
tolerance = 0.1 # degrees
with self.db_manager.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT d.id, d.ra, d.dec, d.magnitude, d.surfacebrightness,
CAST(d.sizemin/60.0 AS REAL) as sizemin,
CAST(d.sizemax/60.0 AS REAL) as sizemax,
d.constellation, d.dsotype, d.dsoclass,
GROUP_CONCAT(c.catalogue || ' ' || c.designation, ', ' ORDER BY
CASE c.catalogue
WHEN 'M' THEN 1
WHEN 'NGC' THEN 2
WHEN 'IC' THEN 3
ELSE 4
END, c.designation) as designations,
ui.image_path, ui.integration_time, ui.equipment, ui.date_taken, ui.notes,
(SELECT COUNT(*) FROM userimages WHERE dsodetailid = d.id) as image_count
FROM dsodetail d
JOIN cataloguenr c ON d.id = c.dsodetailid
LEFT JOIN userimages ui ON d.id = ui.dsodetailid
WHERE ABS(d.ra - ?) < ? AND ABS(d.dec - ?) < ?
GROUP BY d.id
ORDER BY ABS(d.ra - ?) + ABS(d.dec - ?) ASC
LIMIT 1
""", (ra_deg, tolerance, dec_deg, tolerance, ra_deg, dec_deg))
result = cursor.fetchone()
if result:
return self._process_dso_query_result(result, target_data)
except Exception as e:
logger.error(f"Error querying DSO by coordinates: {str(e)}")
return None
def _process_dso_query_result(self, result, target_data):
"""Process database query result into DSODetailWindow format"""
try:
obj_id, ra, dec, magnitude, surface_brightness, size_min, size_max, \
constellation, dso_type, dso_class, designations, image_path, integration_time, \
equipment, date_taken, notes, image_count = result
# Get the primary designation
primary_designation = designations.split(',')[0].strip()
# Handle size values
size_min_arcmin = float(size_min) if size_min is not None else 0.0
size_max_arcmin = float(size_max) if size_max is not None else 0.0
# Format coordinates for display
ra_str = self._format_ra_for_display(ra)
dec_str = self._format_dec_for_display(dec)
return {
"name": primary_designation,
"ra": ra_str,
"dec": dec_str,
"ra_deg": ra,
"dec_deg": dec,
"magnitude": magnitude,
"surface_brightness": surface_brightness,
"size_min": size_min_arcmin,
"size_max": size_max_arcmin,
"constellation": constellation,
"dso_type": dso_type,
"dso_class": dso_class,
"designations": designations,
"catalogue": primary_designation.split()[0] if " " in primary_designation else "",
"id": " ".join(primary_designation.split()[1:]) if " " in primary_designation else primary_designation,
"dsodetailid": obj_id,
"image_path": image_path,
"integration_time": integration_time,
"equipment": equipment,
"date_taken": date_taken,