-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
7362 lines (6195 loc) · 312 KB
/
Copy pathmain.py
File metadata and controls
7362 lines (6195 loc) · 312 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 argparse
import faulthandler
import logging
import os
import sys
import urllib.request
import urllib.error
import json
from typing import Optional, Dict
# Configure SSL certificates BEFORE any network imports (CRITICAL for PyInstaller)
if getattr(sys, 'frozen', False):
# Running in a PyInstaller bundle - configure SSL first
try:
import certifi
cert_path = os.path.join(sys._MEIPASS, 'certifi', 'cacert.pem')
if os.path.exists(cert_path):
os.environ['SSL_CERT_FILE'] = cert_path
os.environ['REQUESTS_CA_BUNDLE'] = cert_path
os.environ['CURL_CA_BUNDLE'] = cert_path
else:
# Fallback to certifi's default path
os.environ['SSL_CERT_FILE'] = certifi.where()
os.environ['REQUESTS_CA_BUNDLE'] = certifi.where()
os.environ['CURL_CA_BUNDLE'] = certifi.where()
except Exception as e:
print(f"Warning: Could not configure SSL certificates: {e}")
# The embedded Chromium (QtWebEngine) renderer was terminating (exit code 18) before it could
# render Aladin Lite. This is a sandbox initialization failure, not the GPU blocklist issue it
# was previously assumed to be: --disable-gpu-sandbox alone did not stop the crash, but
# --no-sandbox does, and it also restores full hardware-accelerated WebGL (verified against real
# rendering, not just "page loaded"). The disabled sandbox only applies to Aladin Lite's fixed,
# non-user-supplied aladin.u-strasbg.fr URL.
# NOTE: this must stay the only place QTWEBENGINE_CHROMIUM_FLAGS is set — a later
# assignment near QApplication startup used to clobber this and re-enable the crash-prone path.
#
# --enable-logging/--log-file: app.exec() has crashed (SIGABRT) with no Python-level cause and no
# Windows "Application Error" event, which points to a Chromium-internal CHECK()/fatal-assertion
# failure (likely GPU/WebGL, given it happened while Aladin Lite was actively rendering) rather
# than memory corruption. Chromium prints the fatal message to its own log right before abort()-ing;
# without this flag that message is lost, leaving faulthandler's single app.exec() frame as the
# only clue. This captures it to chromium_debug.log next to crash.log for the next occurrence.
from ResourceManager import ResourceManager as _ResourceManager
_chromium_log_path = os.path.join(str(_ResourceManager.get_data_dir()), 'chromium_debug.log')
os.environ['QTWEBENGINE_CHROMIUM_FLAGS'] = f'--no-sandbox --enable-logging --log-file={_chromium_log_path}'
# Core PySide6 imports (always needed)
from PySide6.QtCore import Qt, QAbstractTableModel, QModelIndex, QUrl, Signal, QObject, QTimer, QEvent, QThread, QSettings, Slot
from PySide6.QtGui import QPixmap, QPainter, QIcon, QColor, QBrush, QAction
from PySide6.QtWidgets import (
QApplication, QMainWindow, QTableView,
QVBoxLayout, QWidget, QLabel, QDialog,
QHeaderView, QPushButton, QHBoxLayout, QLineEdit, QComboBox, QTextEdit, QCheckBox, QGroupBox,
QToolBar, QMessageBox, QMenu, QScrollArea, QGridLayout, QSpinBox, QFileDialog, QSizePolicy,
QListWidget, QListWidgetItem, QCompleter, QSplitter, QSystemTrayIcon,
QTableWidget, QTableWidgetItem
)
# Local imports (always needed)
from DatabaseManager import DatabaseManager
from WindowPositionManager import WindowPositionManager, WindowPositionMixin
from ResourceManager import ResourceManager
from CollageBuilder import CollageBuilder, CollageBuilderWindow
from Theme import apply_theme, COLORS
from ImageViewer import ImageViewerWindow
from DSODetail import DSODetailWindow
from FOVSimulator import AladinLiteWindow
from NINAIntegration import NINAIntegration
from SystemTrayManager import SystemTrayManager
# Import astroquery at module level so PyInstaller detects it
try:
from astroquery.simbad import Simbad
from astropy.coordinates import SkyCoord
import astropy.units as u
ASTROQUERY_AVAILABLE = True
except ImportError as e:
ASTROQUERY_AVAILABLE = False
print(f"Warning: astroquery not available: {e}")
# Heavy imports - lazy loaded when needed:
# - QWebEngineView (only loaded when Aladin window is created)
# - astroplan/astropy (only loaded when visibility calculations are needed)
# - DSOVisibilityApp (only loaded when visibility calculator is used)
# Set up logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Get the application directory
APP_DIR = os.path.dirname(os.path.abspath(__file__))
# Log SSL configuration status and configure astroquery
if getattr(sys, 'frozen', False):
logger.info(f"Running in PyInstaller bundle. SSL_CERT_FILE={os.environ.get('SSL_CERT_FILE')}")
# Configure astroquery cache directory for PyInstaller
try:
from astropy.config.paths import set_temp_cache
import tempfile
cache_dir = os.path.join(tempfile.gettempdir(), 'astroquery_cache')
os.makedirs(cache_dir, exist_ok=True)
# Set astroquery to use this cache directory
os.environ['XDG_CACHE_HOME'] = cache_dir
logger.info(f"Astroquery cache directory set to: {cache_dir}")
except Exception as e:
logger.warning(f"Could not configure astroquery cache: {e}")
else:
logger.debug("Running in normal Python environment")
# Check for optional DSO Visibility Calculator availability
try:
import DSOVisibilityCalculator
VISIBILITY_AVAILABLE = True
except ImportError:
VISIBILITY_AVAILABLE = False
logging.warning("DSOVisibilityCalculator.py not found. Visibility calculator will be disabled.")
# --- Initial Startup Data Loader Thread ---
class InitialDataLoadWorker(QThread):
"""Worker thread for loading initial DSO data on startup without blocking UI"""
data_loaded = Signal(list, list, int) # dso_data, catalogs, total_count
load_failed = Signal(str) # error message
def __init__(self, parent=None):
super().__init__(parent)
def run(self):
"""Load initial data batch in background thread"""
try:
import sqlite3
from ResourceManager import ResourceManager
db_path = ResourceManager.get_database_path()
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
from ResourceManager import attach_update_catalogs
attach_update_catalogs(conn)
cursor = conn.cursor()
# Get list of available catalogs
cursor.execute("""
SELECT DISTINCT catalogue
FROM cataloguenr
ORDER BY catalogue
""")
catalogs = [row[0] for row in cursor.fetchall()]
# Get total count for progress indication
cursor.execute("SELECT COUNT(DISTINCT d.id) FROM dsodetail d JOIN cataloguenr c ON d.id = c.dsodetailid")
total_count = cursor.fetchone()[0]
logger.debug(f"Total DSO count: {total_count}")
# Load initial batch of objects (first 2000 for faster startup)
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, ', ') 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
GROUP BY d.id
ORDER BY c.catalogue, CAST(c.designation AS INTEGER)
LIMIT 2000
""")
dso_data = []
for row in cursor.fetchall():
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 = row
# Get the primary designation
primary_designation = designations.split(',')[0]
catalogue, designation = primary_designation.split(' ', 1)
# 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
dso_data.append({
"id": designation,
"ra_deg": ra,
"dec_deg": dec,
"catalogue": catalogue,
"name": f"{catalogue} {designation}",
"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,
"image_path": image_path,
"integration_time": integration_time,
"equipment": equipment,
"date_taken": date_taken,
"notes": notes,
"image_count": image_count
})
logger.debug(f"Loaded initial batch: {len(dso_data)} of {total_count} DSOs in background thread")
conn.close()
# Emit the loaded data
self.data_loaded.emit(dso_data, catalogs, total_count)
except Exception as e:
logger.error(f"Error loading initial data in background: {e}", exc_info=True)
self.load_failed.emit(str(e))
# --- Lazy Loading Worker Thread ---
class DataLoadWorker(QThread):
"""Worker thread for loading additional DSO data in background"""
data_loaded = Signal(list) # Signal with new data batch
progress_updated = Signal(int, int) # loaded count, total count
def __init__(self, offset, limit, catalog_filter=None, type_filter=None, parent=None):
super().__init__(parent)
self.offset = offset
self.limit = limit
self.catalog_filter = catalog_filter
self.type_filter = type_filter
def run(self):
"""Load data batch in background thread"""
try:
# Create a direct SQLite connection for this thread (avoiding singleton DatabaseManager)
import sqlite3
from ResourceManager import ResourceManager
# Use the same database path logic as DatabaseManager
# ResourceManager is a global instance, not a class
db_path = ResourceManager.get_database_path()
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
from ResourceManager import attach_update_catalogs
attach_update_catalogs(conn)
cursor = conn.cursor()
# Build query with optional catalog and type filters
if self.catalog_filter:
# When catalog filter is active, filter DSOs that have that catalog
# Special handling for Messier catalog - only numeric designations (M 1 - M 110)
if self.catalog_filter == 'M':
query = """
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(c2.catalogue || ' ' || c2.designation, ', ' ORDER BY
CASE c2.catalogue
WHEN 'M' THEN 1
WHEN 'NGC' THEN 2
WHEN 'IC' THEN 3
ELSE 4
END, c2.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
AND c.catalogue = ?
AND c.designation NOT LIKE '%-%'
AND c.designation NOT LIKE '% %'
AND LENGTH(TRIM(c.designation)) <= 3
AND CAST(c.designation AS INTEGER) > 0
AND CAST(c.designation AS INTEGER) <= 110
JOIN cataloguenr c2 ON d.id = c2.dsodetailid
LEFT JOIN userimages ui ON d.id = ui.dsodetailid
"""
else:
query = """
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(c2.catalogue || ' ' || c2.designation, ', ' ORDER BY
CASE c2.catalogue
WHEN 'M' THEN 1
WHEN 'NGC' THEN 2
WHEN 'IC' THEN 3
ELSE 4
END, c2.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 AND c.catalogue = ?
JOIN cataloguenr c2 ON d.id = c2.dsodetailid
LEFT JOIN userimages ui ON d.id = ui.dsodetailid
"""
params = [self.catalog_filter]
if self.type_filter:
query += " WHERE d.dsotype = ?"
params.append(self.type_filter)
else:
# No catalog filter - get all objects
query = """
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
"""
params = []
if self.type_filter:
query += " WHERE d.dsotype = ?"
params.append(self.type_filter)
query += """
GROUP BY d.id
ORDER BY c.catalogue, CAST(c.designation AS INTEGER)
LIMIT ? OFFSET ?
"""
params.extend([self.limit, self.offset])
# Debug: log query and params when catalog filter is active
if self.catalog_filter:
logger.debug(f"SQL Query with catalog_filter='{self.catalog_filter}'")
logger.debug(f"Params: {params}")
cursor.execute(query, params)
dso_data = []
for row in cursor.fetchall():
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 = row
# Get the primary designation
primary_designation = designations.split(',')[0].strip()
# Handle cases where designation might not have a space
if ' ' in primary_designation:
catalogue, designation = primary_designation.split(' ', 1)
else:
# No space in designation, use entire string as catalogue
catalogue = primary_designation
designation = ""
# Debug: log first few entries when catalog filter is active
if self.catalog_filter and len(dso_data) < 5:
logger.debug(f"Loaded DSO: {primary_designation} (all: {designations})")
# 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
dso_data.append({
"id": designation,
"ra_deg": ra,
"dec_deg": dec,
"catalogue": catalogue,
"name": f"{catalogue} {designation}",
"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,
"image_path": image_path,
"integration_time": integration_time,
"equipment": equipment,
"date_taken": date_taken,
"notes": notes,
"image_count": image_count
})
self.data_loaded.emit(dso_data)
logger.debug(f"Loaded {len(dso_data)} DSOs from offset {self.offset}")
# Clean up the direct connection
conn.close()
except Exception as e:
logger.error(f"Error loading data batch: {e}")
# Clean up on error too
try:
conn.close()
except:
pass
# --- Parallel Loading Manager ---
class ParallelDataLoadManager(QObject):
"""Manages multiple DataLoadWorker threads for parallel data loading"""
all_data_loaded = Signal(list) # Signal with all combined data
progress_updated = Signal(int, int) # loaded count, total count
def __init__(self, parent=None):
super().__init__(parent)
self.workers = []
self.results = {} # Dictionary to store results by offset
self.expected_batches = 0
self.completed_batches = 0
self.total_records = 0
def load_batches_parallel(self, start_offset, total_to_load, batch_size, max_threads, catalog_filter=None, type_filter=None):
"""Load multiple batches in parallel using worker threads"""
# Calculate how many batches we need
num_batches = (total_to_load + batch_size - 1) // batch_size # Ceiling division
num_batches = min(num_batches, max_threads) # Don't create more threads than needed
self.expected_batches = num_batches
self.completed_batches = 0
self.results = {}
self.workers = []
self.total_records = 0
logger.debug(f"Starting parallel load: {num_batches} batches, {max_threads} max threads, offset={start_offset}, total_to_load={total_to_load}")
# Create and start worker threads for each batch
for i in range(num_batches):
offset = start_offset + (i * batch_size)
# Last batch might be smaller
limit = min(batch_size, total_to_load - (i * batch_size))
if limit <= 0:
break
worker = DataLoadWorker(offset, limit, catalog_filter, type_filter)
worker.data_loaded.connect(lambda data, offset=offset: self._on_batch_loaded(data, offset))
self.workers.append(worker)
worker.start()
def _on_batch_loaded(self, data, offset):
"""Handle a batch being loaded"""
self.results[offset] = data
self.completed_batches += 1
self.total_records += len(data)
logger.debug(f"Batch loaded: offset={offset}, records={len(data)}, completed={self.completed_batches}/{self.expected_batches}")
# Emit progress
self.progress_updated.emit(self.total_records, self.expected_batches)
# Check if all batches are complete
if self.completed_batches >= self.expected_batches:
self._combine_and_emit_results()
def _combine_and_emit_results(self):
"""Combine all batch results in order and emit"""
# Sort by offset to maintain correct order
sorted_offsets = sorted(self.results.keys())
combined_data = []
for offset in sorted_offsets:
combined_data.extend(self.results[offset])
logger.debug(f"All batches loaded: {len(combined_data)} total records from {self.expected_batches} batches")
self.all_data_loaded.emit(combined_data)
# Clean up workers
for worker in self.workers:
if worker.isRunning():
worker.quit()
worker.wait()
self.workers = []
self.results = {}
# --- Model for displaying DSO data in table ---
class DSOTableModel(QAbstractTableModel):
def __init__(self, dso_data, parent=None, db_manager=None, total_count=None):
super().__init__(parent)
self.dso_data = dso_data
self.filtered_data = dso_data.copy() # For filtering
self.headers = ["Catalog", "Designation", "RA (hms)", "Dec (dms)", "Images"]
self.selected_catalog = None
self.highlight_no_images = False
self._cached_formatted_data = {} # Cache for formatted data
# Lazy loading support
self.db_manager = db_manager
self.total_count = total_count or len(dso_data)
self.load_offset = len(dso_data)
self.loading = False
self.load_worker = None
self.load_batch_size = 2000
self.startup_mode = True # Prevent sort-triggered loading during startup
# Parallel loading support
self.parallel_loader = ParallelDataLoadManager(self)
self.parallel_loader.all_data_loaded.connect(self._on_parallel_data_loaded)
self.max_threads = self._get_max_threads()
logger.debug(f"DSOTableModel initialized with max_threads={self.max_threads}")
def rowCount(self, index=QModelIndex()):
return len(self.filtered_data)
def columnCount(self, index=QModelIndex()):
return 5
def data(self, index, role):
if not index.isValid():
return None
row = index.row()
col = index.column()
entry = self.filtered_data[row]
if role == Qt.ItemDataRole.BackgroundRole:
if self.highlight_no_images and entry["image_count"] == 0:
return QBrush(QColor(233, 94, 70, 128))
elif row % 2 == 1:
return QBrush(QColor(61, 61, 61))
return QBrush(QColor(45, 45, 45))
elif role == Qt.ItemDataRole.DisplayRole:
cache_key = f"{row}_{col}"
if cache_key in self._cached_formatted_data:
return self._cached_formatted_data[cache_key]
result = self._format_cell_data(entry, col)
self._cached_formatted_data[cache_key] = result
return result
return None
def _format_cell_data(self, entry, col):
"""Format cell data with caching"""
# Check if we have a matched designation from search
matched_designation = entry.get("matched_designation")
if col == 0:
# Show catalog from matched designation if available
if matched_designation:
parts = matched_designation.split(" ", 1)
return parts[0] if parts else entry["catalogue"]
elif self.selected_catalog and self.selected_catalog != "All Catalogs":
return self.selected_catalog
return entry["catalogue"]
elif col == 1:
# Show designation from matched designation if available
if matched_designation:
parts = matched_designation.split(" ", 1)
return parts[1] if len(parts) > 1 else matched_designation
designations = entry["designations"].split(", ")
if self.selected_catalog and self.selected_catalog != "All Catalogs":
for designation in designations:
if designation.startswith(self.selected_catalog + " "):
return designation.split(" ", 1)[1]
return entry["id"]
elif col == 2:
return self._format_ra(entry["ra_deg"])
elif col == 3:
return self._format_dec(entry["dec_deg"])
elif col == 4:
return str(entry["image_count"])
return None
def headerData(self, index, orientation, role):
if role != Qt.DisplayRole or orientation != Qt.Horizontal:
return None
return self.headers[index]
def sort(self, column, order):
"""Sort the data by the specified column"""
logger.debug(f"Sort requested: column={column}, order={order}, loaded={len(self.dso_data)}, offset={self.load_offset}, total={self.total_count}, startup_mode={getattr(self, 'startup_mode', False)}")
# During startup, only sort loaded data to maintain lazy loading performance
if getattr(self, 'startup_mode', False):
logger.debug("Startup mode: sorting only currently loaded data")
# Continue with normal sort of loaded data
# Check if we need to load all data for proper sorting (only after startup)
elif self.load_offset < self.total_count:
logger.debug(f"Sorting requested with partial data ({len(self.dso_data)}/{self.total_count}). Loading all data first...")
self._load_all_data_for_sort(column, order)
return
logger.debug(f"All data loaded, proceeding with sort on {len(self.filtered_data)} items")
self.layoutAboutToBeChanged.emit()
# Get the sort key function based on the column
if column == 0: # Catalog
key_func = lambda x: x["catalogue"]
elif column == 1: # Designation
key_func = lambda x: x["id"]
elif column == 2: # RA
key_func = lambda x: x["ra_deg"]
elif column == 3: # Dec
key_func = lambda x: x["dec_deg"]
elif column == 4: # Images
key_func = lambda x: x["image_count"]
else:
return
# Sort the data
self.filtered_data.sort(key=key_func, reverse=(order == Qt.DescendingOrder))
# Clear the cache when data changes
self._cached_formatted_data.clear()
self.layoutChanged.emit()
logger.debug(f"Sorted {len(self.filtered_data)} items by column {column}")
def _load_all_data_for_sort(self, column, order):
"""Load all remaining data before sorting"""
if self.loading:
logger.debug("Already loading data, sort will be applied when complete")
# Store the sort request to apply after loading
self._pending_sort = (column, order)
return
# Prevent recursive calls by checking if we already have a pending sort
if hasattr(self, '_pending_sort') and self._pending_sort:
logger.debug(f"Sort already pending: {self._pending_sort}, ignoring new request")
return
logger.debug(f"Loading all remaining data for sort by column {column}")
self._pending_sort = (column, order)
# Load remaining data in larger batches for faster completion
remaining = self.total_count - self.load_offset
if remaining > 0:
# Temporarily increase batch size for faster loading
old_batch_size = self.load_batch_size
self.load_batch_size = min(remaining, 5000) # Load up to 5000 at a time
logger.debug(f"Starting to load {remaining} remaining items for sort")
self.load_more_data()
self.load_batch_size = old_batch_size
else:
logger.debug("No remaining data to load, applying sort immediately")
self._apply_pending_sort()
def _apply_pending_sort(self):
"""Apply any pending sort after data loading completes"""
if hasattr(self, '_pending_sort') and self._pending_sort:
column, order = self._pending_sort
self._pending_sort = None
logger.debug(f"Applying pending sort by column {column}")
self.sort(column, order)
def filter_data(self, search_text, selected_catalog=None, show_images_only=False, selected_type=None, show_no_images_only=False):
"""Filter the data based on search text, catalog, image presence, and DSO type"""
self.layoutAboutToBeChanged.emit()
# Check if catalog or type filter changed - if so, reset lazy loading
catalog_changed = self.selected_catalog != selected_catalog
type_changed = getattr(self, '_current_selected_type', None) != selected_type
# Store the selected catalog for use in data() method
self.selected_catalog = selected_catalog
# Track current search for lazy loading
self._current_search = search_text or ''
self._current_show_images_only = show_images_only
self._current_show_no_images_only = show_no_images_only
self._current_selected_type = selected_type
if catalog_changed or type_changed:
# Reset lazy loading state for new filter
self._reset_lazy_loading_for_filter(selected_catalog, selected_type)
# Trigger immediate load of data for the new filter
self.load_more_data()
# Data will be empty until load completes, so set filtered_data to empty
self.filtered_data = []
self.layoutChanged.emit()
return
if not search_text and not selected_catalog and not show_images_only and not selected_type and not show_no_images_only:
self.filtered_data = self.dso_data.copy()
else:
search_text = search_text.lower() if search_text else ""
# Improved search logic with priority for exact catalog matches
matches = []
for item in self.dso_data:
# Apply catalog and type filters
if selected_catalog and selected_catalog != "All Catalogs":
if not any(designation.startswith(selected_catalog + " ")
for designation in item["designations"].split(", ")):
continue
if selected_type and selected_type != "All Types":
if item.get("dso_type", "") != selected_type:
continue
if show_images_only and item["image_count"] == 0:
continue
if show_no_images_only and item["image_count"] > 0:
continue
# Apply search text filter
if search_text:
matched_designation = None
# If we have a catalog filter, prioritize exact catalog+designation matches
if selected_catalog and selected_catalog != "All Catalogs":
# Check for exact match: catalog filter + search text = designation
designations = item["designations"].split(", ")
for designation in designations:
if designation.lower() == f"{selected_catalog.lower()} {search_text}":
matched_designation = designation
break
# Also check if the item's ID matches the search
id_match = search_text in item["id"].lower()
if matched_designation or id_match:
item_copy = item.copy()
if matched_designation:
item_copy["matched_designation"] = matched_designation
matches.append((item_copy, 0)) # Priority 0 = exact match
continue
# Otherwise do regular substring matching and find which designation matched
designations = item["designations"].split(", ")
# Check each designation for a match
for designation in designations:
if search_text in designation.lower():
matched_designation = designation
break
# Check other fields
if (search_text in item["catalogue"].lower() or
search_text in item["id"].lower() or
self._format_ra(item["ra_deg"]).lower() in search_text or
self._format_dec(item["dec_deg"]).lower() in search_text or
matched_designation):
item_copy = item.copy()
if matched_designation:
item_copy["matched_designation"] = matched_designation
matches.append((item_copy, 1)) # Priority 1 = substring match
else:
matches.append((item, 1))
# Sort by priority (exact matches first) and extract items
matches.sort(key=lambda x: x[1])
self.filtered_data = [item for item, priority in matches]
# Clear the cache when data changes
self._cached_formatted_data.clear()
self.layoutChanged.emit()
def _format_ra(self, ra_deg):
"""Convert RA in degrees to hms format"""
ra_hours = ra_deg / 15.0
ra_h = int(ra_hours)
ra_remaining = (ra_hours - ra_h) * 60
ra_m = int(ra_remaining)
ra_s = (ra_remaining - ra_m) * 60
return f"{ra_h:02d}h{ra_m:02d}m{ra_s:05.2f}s"
def _format_dec(self, dec_deg):
"""Convert Dec in degrees to dms format"""
dec_sign = '-' if dec_deg < 0 else '+'
dec_abs = abs(dec_deg)
dec_d = int(dec_abs)
dec_remaining = (dec_abs - dec_d) * 60
dec_m = int(dec_remaining)
dec_s = (dec_remaining - dec_m) * 60
return f"{dec_sign}{dec_d:02d}°{dec_m:02d}'{dec_s:04.1f}\""
def _reset_lazy_loading_for_filter(self, catalog_filter, type_filter):
"""Reset lazy loading state when filter changes and query filtered count"""
if not self.db_manager:
return
try:
import sqlite3
from ResourceManager import ResourceManager, attach_update_catalogs
# Query the total count for this specific filter
db_path = ResourceManager.get_database_path()
conn = sqlite3.connect(str(db_path))
attach_update_catalogs(conn)
cursor = conn.cursor()
# Build count query with filters - must match the data loading query logic
if catalog_filter == 'M':
# Special handling for Messier catalog - only numeric designations
query = """
SELECT COUNT(DISTINCT d.id)
FROM dsodetail d
JOIN cataloguenr c ON d.id = c.dsodetailid
AND c.catalogue = ?
AND c.designation NOT LIKE '%-%'
AND c.designation NOT LIKE '% %'
AND LENGTH(TRIM(c.designation)) <= 3
AND CAST(c.designation AS INTEGER) > 0
AND CAST(c.designation AS INTEGER) <= 110
"""
params = [catalog_filter]
if type_filter:
query += " WHERE d.dsotype = ?"
params.append(type_filter)
elif catalog_filter:
# Other catalog filters
query = """
SELECT COUNT(DISTINCT d.id)
FROM dsodetail d
JOIN cataloguenr c ON d.id = c.dsodetailid
WHERE c.catalogue = ?
"""
params = [catalog_filter]
if type_filter:
query += " AND d.dsotype = ?"
params.append(type_filter)
else:
# No catalog filter
query = """
SELECT COUNT(DISTINCT d.id)
FROM dsodetail d
JOIN cataloguenr c ON d.id = c.dsodetailid
"""
params = []
if type_filter:
query += " WHERE d.dsotype = ?"
params.append(type_filter)
cursor.execute(query, params)
filtered_total = cursor.fetchone()[0]
conn.close()
# Cancel any pending load worker
if hasattr(self, 'load_worker') and self.load_worker:
try:
self.load_worker.disconnect()
self.load_worker.terminate()
self.load_worker.wait(1000) # Wait up to 1 second
self.load_worker.deleteLater()
except:
pass
self.load_worker = None
# Clear existing data and reset offset
self.loading = False
# Notify view that we're about to clear all data
self.beginResetModel()
self.dso_data = []
self.filtered_data = []
self.load_offset = 0
self.total_count = filtered_total
self._cached_formatted_data.clear()
self.endResetModel()
logger.debug(f"Reset lazy loading for filter: catalog={catalog_filter}, type={type_filter}, total={filtered_total}")
except Exception as e:
logger.error(f"Error resetting lazy loading for filter: {e}")
def setHighlightNoImages(self, highlight):
"""Set whether to highlight objects without images"""
self.highlight_no_images = highlight
self.dataChanged.emit(self.index(0, 0), self.index(self.rowCount() - 1, self.columnCount() - 1))
def check_and_load_more_data(self, view_bottom_row):
"""Check if we need to load more data and trigger loading if needed"""
filtered_len = len(self.filtered_data)
loaded_len = len(self.dso_data)
# FILTER-AWARE LOADING: If we have active filters and very few results, keep loading
has_active_filters = (hasattr(self, '_current_search') and
(self._current_search or self.selected_catalog or
getattr(self, '_current_show_images_only', False) or
getattr(self, '_current_show_no_images_only', False) or
getattr(self, '_current_selected_type', None)))
# If filters are active and we have very few results, keep loading more aggressively
# For sparse results (like "show images only"), we need to load much more data
if has_active_filters and loaded_len < self.total_count:
if filtered_len < 100: # Very few results - load aggressively
filter_needs_more_data = True
elif filtered_len < 500: # Moderate results - load when nearing end
# Load more if we're showing most of what we found
filter_needs_more_data = view_bottom_row > filtered_len * 0.7
else:
# Normal threshold for larger result sets
filter_needs_more_data = False
else:
filter_needs_more_data = False
# MAJOR FIX: If view_bottom_row seems capped (~2000), use the actual visible rows as reference
max_visible_rows = max(view_bottom_row + 1, 2000)
# Use much more aggressive triggering when we hit apparent view limits
if view_bottom_row >= 1900: # Near the apparent view limit
trigger_point = max_visible_rows - 100 # Very aggressive
else:
# Normal triggering logic
trigger_point_rows = filtered_len - 200
trigger_point_percent = int(filtered_len * 0.8)
trigger_point = min(trigger_point_rows, trigger_point_percent)
# Multiple trigger conditions
near_end_of_visible = view_bottom_row > trigger_point
displayed_most_data = view_bottom_row > len(self.dso_data) * 0.75
near_view_limit = view_bottom_row >= 1950 # Emergency trigger when hitting view limits
if (self.db_manager and
not self.loading and
self.load_offset < self.total_count and
(near_end_of_visible or displayed_most_data or near_view_limit or filter_needs_more_data)):
# Log only when loading is actually triggered
trigger_reason = []
if near_end_of_visible: trigger_reason.append("near end of visible")
if displayed_most_data: trigger_reason.append("75% of loaded data")
if near_view_limit: trigger_reason.append("emergency trigger")
if filter_needs_more_data:
if filtered_len < 100:
trigger_reason.append("sparse filter results - loading more")
else:
trigger_reason.append("filter needs more data")
logger.debug(f"Triggering lazy load: {', '.join(trigger_reason)} (filtered: {filtered_len}, loaded: {loaded_len}, total: {self.total_count})")
self.load_more_data()
else:
# Reduced debug logging for non-trigger cases
pass
def _get_max_threads(self):
"""Get max_threads setting from QSettings"""
try:
settings = QSettings("AstroAssist", "CosmosCollection")
default_threads = max(1, (os.cpu_count() or 4) - 2)
max_threads = settings.value("max_threads", default_threads, type=int)
return max(1, min(max_threads, 128)) # Ensure reasonable bounds
except Exception as e:
logger.error(f"Error reading max_threads setting: {e}")
return max(1, (os.cpu_count() or 4) - 2)
def load_more_data(self):
"""Load the next batches of data in parallel background threads"""
if self.loading or self.load_offset >= self.total_count:
logger.debug(f"Load blocked: loading={self.loading}, offset={self.load_offset}, total={self.total_count}")
return
# Get current filters
catalog_filter = self.selected_catalog if self.selected_catalog else None
type_filter = getattr(self, '_current_selected_type', None)
# Calculate how much data remains to load
remaining = self.total_count - self.load_offset
# Load up to max_threads * batch_size in this batch (parallel loading)
total_to_load = min(remaining, self.max_threads * self.load_batch_size)
logger.debug(f"Starting parallel load from offset {self.load_offset}, loading {total_to_load} records using {self.max_threads} threads, catalog={catalog_filter}, type={type_filter}")
self.loading = True
# Emit signal to update UI loading state
if hasattr(self.parent(), '_on_loading_started'):
self.parent()._on_loading_started()
# Use parallel loader
self.parallel_loader.load_batches_parallel(
self.load_offset,
total_to_load,
self.load_batch_size,
self.max_threads,
catalog_filter,
type_filter
)
def _on_data_loaded(self, new_data):
"""Handle new data batch loaded from background thread"""
if new_data:
# Add new data to existing data
self.beginInsertRows(QModelIndex(), len(self.dso_data), len(self.dso_data) + len(new_data) - 1)
self.dso_data.extend(new_data)
self.endInsertRows()
# Re-apply current filters to include new data
# Catalog and type filters are already applied at SQL level, so we only need to filter by:
# - search text