-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSOGallery.py
More file actions
2305 lines (1940 loc) · 96 KB
/
Copy pathDSOGallery.py
File metadata and controls
2305 lines (1940 loc) · 96 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 Image Gallery
Displays all DSO objects with images in a responsive grid gallery format
"""
import sys
import os
import re
from datetime import datetime
from PySide6.QtCore import Qt, Signal, QTimer, QThreadPool, QRunnable, QObject
from PySide6.QtWidgets import (QMainWindow, QVBoxLayout, QHBoxLayout,
QWidget, QPushButton, QLabel, QGroupBox,
QMessageBox, QScrollArea, QComboBox, QLineEdit,
QFrame, QGridLayout, QMenu, QApplication,
QDialog, QFileDialog, QFormLayout, QDialogButtonBox,
QCompleter, QSlider, QProgressDialog, QPlainTextEdit,
QSizePolicy)
from PySide6.QtCore import QSettings
from PySide6.QtGui import QPixmap, QImage
from DatabaseManager import DatabaseManager
from WindowPositionManager import WindowPositionMixin
from Theme import COLORS
import numpy as np
# Image extensions supported for DSO images throughout the gallery
SUPPORTED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.tif', '.tiff', '.fits', '.fit', '.fts'}
class ThumbnailCache:
"""Cache for storing generated thumbnails to avoid regeneration"""
def __init__(self, max_size=200):
self._cache = {} # image_path -> QPixmap
self._max_size = max_size
self._access_order = [] # Track access order for LRU eviction
def get(self, image_path):
"""Get cached thumbnail for image path"""
if image_path in self._cache:
# Move to end (most recently used)
if image_path in self._access_order:
self._access_order.remove(image_path)
self._access_order.append(image_path)
return self._cache[image_path]
return None
def put(self, image_path, pixmap):
"""Store thumbnail in cache"""
if image_path in self._cache:
# Update existing entry
if image_path in self._access_order:
self._access_order.remove(image_path)
elif len(self._cache) >= self._max_size:
# Remove least recently used item
if self._access_order:
lru_path = self._access_order.pop(0)
if lru_path in self._cache:
del self._cache[lru_path]
self._cache[image_path] = pixmap
self._access_order.append(image_path)
def clear(self):
"""Clear all cached thumbnails"""
self._cache.clear()
self._access_order.clear()
class ThumbnailSignals(QObject):
"""Signals for ThumbnailRunnable (QRunnable doesn't support signals directly)"""
thumbnail_ready = Signal(object, QPixmap) # card, pixmap
thumbnail_error = Signal(object, str) # card, error_message
class ThumbnailRunnable(QRunnable):
"""Runnable task for generating a single thumbnail in a thread pool"""
# Map thumbnail sizes to size names for disk cache filenames
SIZE_NAMES = {
100: 'Small',
150: 'Medium',
300: 'Large',
500: 'ExtraLarge'
}
def __init__(self, card, image_path, cache, signals, cancelled_flag, thumbnail_size=150):
"""
Initialize thumbnail runnable
Args:
card: GalleryCard instance to update
image_path: Path to image file
cache: ThumbnailCache instance
signals: ThumbnailSignals instance for emitting signals
cancelled_flag: List with single boolean for cancellation check
thumbnail_size: Size of thumbnail (width and height in pixels)
"""
super().__init__()
self.card = card
self.image_path = image_path
self.cache = cache
self.signals = signals
self.cancelled_flag = cancelled_flag
self.thumbnail_size = thumbnail_size
def _get_disk_cache_path(self):
"""Get the path for the disk-cached thumbnail file"""
directory = os.path.dirname(self.image_path)
basename = os.path.basename(self.image_path)
name_without_ext = os.path.splitext(basename)[0]
size_name = self.SIZE_NAMES.get(self.thumbnail_size, f'{self.thumbnail_size}px')
cache_filename = f"{name_without_ext}_{size_name}_Thumbnail.jpg"
return os.path.join(directory, cache_filename)
def _is_disk_cache_valid(self, cache_path):
"""Check if disk cache file exists and is newer than the original image"""
if not os.path.exists(cache_path):
return False
try:
cache_mtime = os.path.getmtime(cache_path)
original_mtime = os.path.getmtime(self.image_path)
return cache_mtime >= original_mtime
except OSError:
return False
def _load_from_disk_cache(self, cache_path):
"""Load thumbnail from disk cache"""
try:
pixmap = QPixmap(cache_path)
if not pixmap.isNull():
return pixmap
except Exception:
pass
return None
def _save_to_disk_cache(self, pixmap, cache_path):
"""Save thumbnail to disk cache as JPEG at 85% quality"""
try:
pixmap.save(cache_path, "JPEG", 85)
except Exception:
pass # Silently fail if we can't save cache
def _load_fits_thumbnail(self, fits_path):
"""Load a FITS file and convert to QPixmap thumbnail"""
try:
from astropy.io import fits
from astropy.visualization import simple_norm
# Open FITS file
with fits.open(fits_path) as hdul:
# Get the primary image data
image_data = None
for hdu in hdul:
if hdu.data is not None and len(hdu.data.shape) >= 2:
image_data = hdu.data
break
if image_data is None:
return None
# Handle different dimensionalities
is_rgb = False
if len(image_data.shape) > 2:
# Check if this is an RGB image (3 color planes)
if len(image_data.shape) == 3 and image_data.shape[2] == 3:
is_rgb = True
elif len(image_data.shape) == 3 and image_data.shape[0] == 3:
# RGB planes in first dimension, transpose
image_data = np.transpose(image_data, (1, 2, 0))
is_rgb = True
elif len(image_data.shape) == 3:
# Take first 2D slice
image_data = image_data[0]
elif len(image_data.shape) == 4:
image_data = image_data[0, 0]
else:
return None
# Normalize the data
image_data = np.nan_to_num(image_data, nan=0.0, posinf=0.0, neginf=0.0)
if is_rgb:
# Handle RGB FITS - normalize each channel separately
normalized_data = np.zeros_like(image_data)
for channel in range(3):
channel_data = image_data[:, :, channel]
try:
norm = simple_norm(channel_data, stretch='linear', percent=99.5)
normalized_data[:, :, channel] = norm(channel_data)
except Exception:
data_min, data_max = np.percentile(channel_data, [0.5, 99.5])
if data_max > data_min:
normalized_data[:, :, channel] = (channel_data - data_min) / (data_max - data_min)
else:
normalized_data[:, :, channel] = channel_data
# Clip and convert to 8-bit RGB
normalized_data = np.clip(normalized_data, 0, 1)
rgb_data = (normalized_data * 255).astype(np.uint8)
if not rgb_data.flags['C_CONTIGUOUS']:
rgb_data = np.ascontiguousarray(rgb_data)
height, width, channels = rgb_data.shape
bytes_per_line = width * channels
qimage = QImage(rgb_data.data, width, height, bytes_per_line, QImage.Format_RGB888)
else:
# Handle grayscale FITS
try:
norm = simple_norm(image_data, stretch='linear', percent=99.5)
normalized_data = norm(image_data)
except Exception:
data_min, data_max = np.percentile(image_data, [0.5, 99.5])
if data_max > data_min:
normalized_data = (image_data - data_min) / (data_max - data_min)
else:
normalized_data = image_data
normalized_data = np.clip(normalized_data, 0, 1)
# Convert to 8-bit grayscale
image_8bit = (normalized_data * 255).astype(np.uint8)
if not image_8bit.flags['C_CONTIGUOUS']:
image_8bit = np.ascontiguousarray(image_8bit)
height, width = image_8bit.shape
bytes_per_line = width
qimage = QImage(image_8bit.data, width, height, bytes_per_line, QImage.Format_Grayscale8)
# Convert to QPixmap
return QPixmap.fromImage(qimage)
except Exception as e:
return None
def run(self):
"""Generate thumbnail for single image"""
# Check if cancelled before starting
if self.cancelled_flag[0]:
return
from PySide6.QtGui import QImageReader
try:
# Check memory cache first
if self.cache:
cached_pixmap = self.cache.get(self.image_path)
if cached_pixmap:
self.signals.thumbnail_ready.emit(self.card, cached_pixmap)
return
# Check if cancelled
if self.cancelled_flag[0]:
return
# Check if disk caching is enabled
settings = QSettings("CosmosCollection", "CosmosCollection")
disk_cache_enabled = settings.value("cache_thumbnails_to_disk", True, type=bool)
disk_cache_path = self._get_disk_cache_path() if disk_cache_enabled else None
# Try loading from disk cache if enabled and valid
if disk_cache_enabled and self._is_disk_cache_valid(disk_cache_path):
disk_pixmap = self._load_from_disk_cache(disk_cache_path)
if disk_pixmap and not disk_pixmap.isNull():
# Store in memory cache too
if self.cache:
self.cache.put(self.image_path, disk_pixmap)
self.signals.thumbnail_ready.emit(self.card, disk_pixmap)
return
# Check if cancelled
if self.cancelled_flag[0]:
return
if os.path.exists(self.image_path):
# Check file size
file_size = os.path.getsize(self.image_path)
if file_size == 0:
self.signals.thumbnail_error.emit(self.card, "Empty File")
return
# Get file extension
_, ext = os.path.splitext(self.image_path.lower())
pixmap = None
# Handle FITS files
if ext in ['.fits', '.fit', '.fts']:
pixmap = self._load_fits_thumbnail(self.image_path)
if pixmap is None:
self.signals.thumbnail_error.emit(self.card, "FITS Load Error")
return
else:
# Load regular image formats
QImageReader.setAllocationLimit(512)
# Try standard QPixmap loading
pixmap = QPixmap(self.image_path)
# If failed, try QImageReader
if pixmap.isNull():
try:
reader = QImageReader(self.image_path)
if reader.canRead():
# Set explicit format
if ext in ['.jpg', '.jpeg']:
reader.setFormat(b"JPEG")
elif ext == '.png':
reader.setFormat(b"PNG")
elif ext in ['.tiff', '.tif']:
reader.setFormat(b"TIFF")
image = reader.read()
if not image.isNull():
pixmap = QPixmap.fromImage(image)
except Exception:
pass
# Check if cancelled before emitting
if self.cancelled_flag[0]:
return
if pixmap and not pixmap.isNull():
# Scale to thumbnail size (gallery card size)
scaled_pixmap = pixmap.scaled(self.thumbnail_size, self.thumbnail_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
# Cache the thumbnail in memory
if self.cache:
self.cache.put(self.image_path, scaled_pixmap)
# Save to disk cache if enabled
if disk_cache_enabled and disk_cache_path:
self._save_to_disk_cache(scaled_pixmap, disk_cache_path)
self.signals.thumbnail_ready.emit(self.card, scaled_pixmap)
else:
error_msg = f"Load Error"
self.signals.thumbnail_error.emit(self.card, error_msg)
else:
self.signals.thumbnail_error.emit(self.card, "File Not Found")
except Exception as e:
self.signals.thumbnail_error.emit(self.card, f"Error: {str(e)[:20]}")
class DataLoaderSignals(QObject):
"""Signals for DataLoaderRunnable"""
data_loaded = Signal(list) # Emits list of loaded items
load_error = Signal(str) # Emits error message
class DataLoaderRunnable(QRunnable):
"""Runnable task for loading gallery data in background"""
def __init__(self, signals):
"""
Initialize data loader runnable
Args:
signals: DataLoaderSignals instance for emitting signals
"""
super().__init__()
self.signals = signals
def _get_friendly_type_name(self, dso_type):
"""Convert DSO type code to user-friendly 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",
"LMCCN": "LMC Cluster/Nebula",
"LMCDN": "LMC Dark Nebula",
"LMCGC": "LMC Globular Cluster",
"LMCOC": "LMC Open Cluster",
"SMCCN": "SMC Cluster/Nebula",
"SMCDN": "SMC Dark Nebula",
"SMCGC": "SMC Globular Cluster",
"SMCOC": "SMC Open Cluster"
}
return type_mapping.get(dso_type, dso_type)
def run(self):
"""Load gallery data from database"""
import sqlite3
from ResourceManager import ResourceManager
try:
# Create new SQLite connection in this thread (DatabaseManager is a singleton)
db_path = ResourceManager.get_database_path()
conn = sqlite3.connect(str(db_path))
from ResourceManager import attach_update_catalogs
attach_update_catalogs(conn)
# Ensure created_date column exists (migration for older databases)
# Do this before setting row_factory
# Note: ALTER TABLE cannot use CURRENT_TIMESTAMP as default, so we use NULL
cursor = conn.cursor()
cursor.execute("PRAGMA table_info(userimages)")
columns = [row[1] for row in cursor.fetchall()]
if 'created_date' not in columns:
cursor.execute("ALTER TABLE userimages ADD COLUMN created_date TEXT")
conn.commit()
conn.row_factory = sqlite3.Row
try:
cursor = conn.cursor()
# One row per image (not per DSO) so every attached image gets its own card
query = """
SELECT
d.id as dsodetailid,
ui.id as imageid,
ui.image_path,
ui.equipment,
ui.is_favorite,
d.dsotype,
d.constellation,
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 name,
ui.created_date,
d.ra,
d.dec
FROM userimages ui
INNER JOIN dsodetail d ON d.id = ui.dsodetailid
INNER JOIN cataloguenr c ON d.id = c.dsodetailid
WHERE ui.image_path IS NOT NULL AND ui.image_path != ''
GROUP BY ui.id
ORDER BY name
"""
cursor.execute(query)
rows = cursor.fetchall()
# Convert rows to dictionaries
items = []
for row in rows:
item = {
'dsodetailid': row[0],
'imageid': row[1],
'image_path': row[2],
'equipment': row[3] or '',
'is_favorite': row[4],
'dsotype': row[5] or '',
'constellation': row[6] or '',
'name': row[7] or 'Unknown',
'friendly_type': self._get_friendly_type_name(row[5] or ''),
'created_date': row[8] or '',
'ra_deg': row[9],
'dec_deg': row[10]
}
items.append(item)
# Emit success signal with loaded data
self.signals.data_loaded.emit(items)
finally:
# Close the connection
conn.close()
except Exception as e:
# Emit error signal
self.signals.load_error.emit(str(e))
def _load_preview_pixmap(image_path, max_dim=200):
"""Load a small preview pixmap for an image path, including FITS files.
Returns None if the file can't be read/decoded (e.g. unsupported format).
"""
if not image_path or not os.path.exists(image_path):
return None
_, ext = os.path.splitext(image_path.lower())
pixmap = None
if ext in ('.fits', '.fit', '.fts'):
try:
from astropy.io import fits
from astropy.visualization import simple_norm
with fits.open(image_path) as hdul:
image_data = None
for hdu in hdul:
if hdu.data is not None and len(hdu.data.shape) >= 2:
image_data = hdu.data
break
if image_data is None:
return None
if len(image_data.shape) == 3 and image_data.shape[0] == 3:
image_data = np.transpose(image_data, (1, 2, 0))
elif len(image_data.shape) == 3 and image_data.shape[2] != 3:
image_data = image_data[0]
elif len(image_data.shape) == 4:
image_data = image_data[0, 0]
image_data = np.nan_to_num(image_data, nan=0.0, posinf=0.0, neginf=0.0)
is_rgb = len(image_data.shape) == 3 and image_data.shape[2] == 3
def _normalize(channel):
try:
norm = simple_norm(channel, stretch='linear', percent=99.5)
return norm(channel)
except Exception:
lo, hi = np.percentile(channel, [0.5, 99.5])
return (channel - lo) / (hi - lo) if hi > lo else channel
if is_rgb:
normalized = np.zeros_like(image_data, dtype=float)
for c in range(3):
normalized[:, :, c] = _normalize(image_data[:, :, c])
rgb = (np.clip(normalized, 0, 1) * 255).astype(np.uint8)
if not rgb.flags['C_CONTIGUOUS']:
rgb = np.ascontiguousarray(rgb)
h, w, c = rgb.shape
qimage = QImage(rgb.data, w, h, w * c, QImage.Format_RGB888)
else:
normalized = np.clip(_normalize(image_data), 0, 1)
img8 = (normalized * 255).astype(np.uint8)
if not img8.flags['C_CONTIGUOUS']:
img8 = np.ascontiguousarray(img8)
h, w = img8.shape
qimage = QImage(img8.data, w, h, w, QImage.Format_Grayscale8)
pixmap = QPixmap.fromImage(qimage.copy())
except Exception:
return None
else:
pixmap = QPixmap(image_path)
if pixmap is None or pixmap.isNull():
return None
return pixmap.scaled(max_dim, max_dim, Qt.KeepAspectRatio, Qt.SmoothTransformation)
class AddImageDialog(WindowPositionMixin, QDialog):
"""Dialog for adding a new image to a DSO"""
WINDOW_POSITION_KEY = "AddImageDialog"
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Add Image to DSO")
self.selected_file = None
self.dso_data = [] # List of (dsodetailid, name) tuples, index-aligned with dso_combo
self._dso_auto_selected = False
self.setAcceptDrops(True)
self._init_ui()
self._load_dso_list()
self._load_equipment_list()
self._update_preview()
self.setup_window_position()
def _init_ui(self):
"""Create the dialog UI"""
layout = QVBoxLayout(self)
layout.setSpacing(12)
# Instructions
instructions = QLabel("Select an image file and choose which DSO to attach it to.")
instructions.setWordWrap(True)
layout.addWidget(instructions)
# --- Image preview / drop zone + DSO selection -----------------
top_row = QHBoxLayout()
top_row.setSpacing(12)
# Grows with the dialog (both wider and taller) so enlarging the
# window makes the thumbnail bigger instead of the text fields;
# the loaded source pixmap is re-scaled to fit on every resize.
self._preview_source_pixmap = None
self.preview_label = QLabel()
self.preview_label.setMinimumSize(150, 150)
self.preview_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.preview_label.setAlignment(Qt.AlignCenter)
self.preview_label.setWordWrap(True)
self.preview_label.setCursor(Qt.PointingHandCursor)
self.preview_label.setToolTip("Click to browse, or drag & drop an image onto this dialog")
self.preview_label.setStyleSheet(f"""
QLabel {{
background-color: {COLORS['background_light']};
border: 2px dashed {COLORS['border_light']};
border-radius: 6px;
color: {COLORS['text_secondary']};
font-size: 9pt;
padding: 6px;
}}
""")
self.preview_label.mousePressEvent = lambda event: self._browse_file()
top_row.addWidget(self.preview_label, 1)
# Fields column stays at its natural width (stretch 0) so extra
# horizontal space is given to the preview above instead.
right_col = QVBoxLayout()
right_col.setSpacing(6)
file_layout = QHBoxLayout()
self.file_path_edit = QLineEdit()
self.file_path_edit.setPlaceholderText("No file selected...")
self.file_path_edit.setReadOnly(True)
self.file_path_edit.setMinimumWidth(200)
self.file_path_edit.setMaximumWidth(260)
file_layout.addWidget(self.file_path_edit)
browse_btn = QPushButton("Browse...")
browse_btn.clicked.connect(self._browse_file)
file_layout.addWidget(browse_btn)
right_col.addLayout(file_layout)
dso_label = QLabel("Attach to DSO:")
right_col.addWidget(dso_label)
# DSO selection with search
self.dso_combo = QComboBox()
self.dso_combo.setEditable(True)
self.dso_combo.setInsertPolicy(QComboBox.NoInsert)
self.dso_combo.lineEdit().setPlaceholderText("Search for DSO...")
# Keep the closed combo box narrow regardless of how long individual
# DSO entries are (some objects have many catalogue designations);
# the popup list itself is widened separately so full names stay readable.
self.dso_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
self.dso_combo.setMinimumContentsLength(20)
self.dso_combo.setMinimumWidth(200)
self.dso_combo.setMaximumWidth(260)
self.dso_combo.view().setMinimumWidth(380)
self.dso_combo.activated.connect(self._on_dso_manually_changed)
right_col.addWidget(self.dso_combo)
self.detected_label = QLabel("")
self.detected_label.setStyleSheet(f"color: {COLORS['info']}; font-size: 9pt;")
self.detected_label.setWordWrap(True)
self.detected_label.setMaximumWidth(260)
self.detected_label.hide()
right_col.addWidget(self.detected_label)
right_col.addStretch()
top_row.addLayout(right_col)
# Give the image/DSO row the extra vertical space on a taller resize
# too, so the preview grows in both directions.
layout.addLayout(top_row, 1)
# --- Optional capture details -----------------------------------
# Capped to a fixed max width so resizing the dialog doesn't stretch
# these fields - all the extra space goes to the preview instead.
FIELD_MAX_WIDTH = 260
form_layout = QFormLayout()
form_layout.setSpacing(10)
self.telescope_combo = QComboBox()
self.telescope_combo.setEditable(True)
self.telescope_combo.setInsertPolicy(QComboBox.NoInsert)
self.telescope_combo.lineEdit().setPlaceholderText("e.g., 8\" SCT")
self.telescope_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
self.telescope_combo.setMinimumContentsLength(18)
self.telescope_combo.setMaximumWidth(FIELD_MAX_WIDTH)
form_layout.addRow("Telescope:", self.telescope_combo)
self.camera_combo = QComboBox()
self.camera_combo.setEditable(True)
self.camera_combo.setInsertPolicy(QComboBox.NoInsert)
self.camera_combo.lineEdit().setPlaceholderText("e.g., ASI294MC Pro")
self.camera_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
self.camera_combo.setMinimumContentsLength(18)
self.camera_combo.setMaximumWidth(FIELD_MAX_WIDTH)
form_layout.addRow("Camera:", self.camera_combo)
self.integration_edit = QLineEdit()
self.integration_edit.setPlaceholderText("e.g., 2h 30m")
self.integration_edit.setMaximumWidth(FIELD_MAX_WIDTH)
form_layout.addRow("Integration Time:", self.integration_edit)
date_layout = QHBoxLayout()
self.date_edit = QLineEdit()
self.date_edit.setPlaceholderText("e.g., 2024-01-15")
self.date_edit.setMaximumWidth(FIELD_MAX_WIDTH - 70)
date_layout.addWidget(self.date_edit)
today_btn = QPushButton("Today")
today_btn.setToolTip("Fill in today's date")
today_btn.clicked.connect(self._fill_today_date)
date_layout.addWidget(today_btn)
date_layout.addStretch()
form_layout.addRow("Date Taken:", date_layout)
self.notes_edit = QPlainTextEdit()
self.notes_edit.setPlaceholderText("Optional notes about this image")
self.notes_edit.setMaximumHeight(60)
self.notes_edit.setMaximumWidth(FIELD_MAX_WIDTH)
form_layout.addRow("Notes:", self.notes_edit)
layout.addLayout(form_layout)
# Inline validation feedback (shown instead of popping a dialog
# for every missing field)
self.status_label = QLabel("")
self.status_label.setStyleSheet(f"color: {COLORS['error']};")
self.status_label.setWordWrap(True)
self.status_label.hide()
layout.addWidget(self.status_label)
# Dialog buttons
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self._validate_and_accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
self.setMinimumWidth(460)
self.resize(460, self.sizeHint().height())
def _load_dso_list(self):
"""Load all DSOs from database for the combo box"""
try:
db_manager = DatabaseManager()
with db_manager.get_connection() as conn:
cursor = conn.cursor()
query = """
SELECT d.id as dsodetailid,
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 name,
d.constellation,
d.dsotype
FROM dsodetail d
JOIN cataloguenr c ON d.id = c.dsodetailid
GROUP BY d.id
ORDER BY
CASE
WHEN name LIKE 'M %' THEN 1
WHEN name LIKE 'NGC %' THEN 2
WHEN name LIKE 'IC %' THEN 3
ELSE 4
END,
name
"""
cursor.execute(query)
rows = cursor.fetchall()
# Clear and populate combo box
self.dso_combo.clear()
self.dso_data = []
for row in rows:
dsodetailid, name, constellation, dsotype = row
display_text = f"{name} ({constellation})"
self.dso_combo.addItem(display_text, dsodetailid)
self.dso_data.append((dsodetailid, name))
# Setup completer for search functionality
completer = QCompleter([self.dso_combo.itemText(i) for i in range(self.dso_combo.count())])
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.setFilterMode(Qt.MatchContains)
self.dso_combo.setCompleter(completer)
# Clear selection so placeholder text is shown
self.dso_combo.setCurrentIndex(-1)
self.dso_combo.lineEdit().clear()
except Exception as e:
QMessageBox.warning(self, "Error", f"Failed to load DSO list: {str(e)}")
def _load_equipment_list(self):
"""Load user telescopes and cameras into their respective dropdowns"""
try:
db_manager = DatabaseManager()
with db_manager.get_connection() as conn:
cursor = conn.cursor()
# Load telescopes
cursor.execute("SELECT name FROM usertelescopes ORDER BY name")
for row in cursor.fetchall():
self.telescope_combo.addItem(row[0])
# Load cameras
cursor.execute("SELECT name FROM userequipment WHERE equipment_type = 'camera' ORDER BY name")
for row in cursor.fetchall():
self.camera_combo.addItem(row[0])
# Clear selection so placeholder text is shown
self.telescope_combo.setCurrentIndex(-1)
self.telescope_combo.lineEdit().clear()
self.camera_combo.setCurrentIndex(-1)
self.camera_combo.lineEdit().clear()
except Exception as e:
QMessageBox.warning(self, "Error", f"Failed to load equipment list: {str(e)}")
def _browse_file(self):
"""Open file dialog to select an image"""
file_name, _ = QFileDialog.getOpenFileName(
self,
"Select Image File",
os.path.expanduser("~"),
"Image Files (*.png *.jpg *.jpeg *.tif *.tiff *.fits *.fit *.fts);;"
"PNG Files (*.png);;"
"JPEG Files (*.jpg *.jpeg);;"
"TIFF Files (*.tif *.tiff);;"
"FITS Files (*.fits *.fit *.fts);;"
"All Files (*.*)"
)
if file_name:
self.set_file_path(file_name)
def set_file_path(self, path):
"""Set the selected file path, refresh the preview and try to auto-detect the DSO"""
self.selected_file = path
self.file_path_edit.setText(path)
self._clear_error(self.file_path_edit)
self._update_preview()
self._try_auto_detect_dso()
def _update_preview(self):
"""(Re)load the preview source for the selected file and render it at the
preview box's current size. Loaded once per file at a resolution large
enough to still look sharp when the dialog is enlarged."""
self._preview_source_pixmap = (
_load_preview_pixmap(self.selected_file, max_dim=600) if self.selected_file else None
)
self._render_preview()
def _render_preview(self):
"""Scale the cached preview source to fit the preview box's current size"""
if self._preview_source_pixmap:
scaled = self._preview_source_pixmap.scaled(
self.preview_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation
)
self.preview_label.setPixmap(scaled)
elif self.selected_file:
self.preview_label.setPixmap(QPixmap())
self.preview_label.setText("Preview not\navailable")
else:
self.preview_label.setPixmap(QPixmap())
self.preview_label.setText("Drag && drop\nan image here\nor click to browse")
def resizeEvent(self, event):
"""Re-scale the preview thumbnail to fill the enlarged/shrunk preview box"""
super().resizeEvent(event)
self._render_preview()
def _guess_dso_index_from_filename(self, file_path):
"""Look for a DSO catalogue designation (e.g. 'M31', 'NGC 7000') embedded in the filename"""
# Keep hyphens (but drop other punctuation/whitespace) so distinct
# designations that only differ by a hyphen - e.g. Messier "M 16"
# vs. Minkowski "M 1-6" - don't collapse into the same "M16" string
# and get confused for one another.
basename = os.path.splitext(os.path.basename(file_path))[0]
base_norm = re.sub(r'[^A-Z0-9-]', '', basename.upper())
if not base_norm:
return None
best_index = None
best_len = 0
for index, (dsodetailid, name) in enumerate(self.dso_data):
for designation in name.split(','):
d_norm = re.sub(r'[^A-Z0-9-]', '', designation.upper())
if len(d_norm) >= 2 and len(d_norm) > best_len and d_norm in base_norm:
best_index = index
best_len = len(d_norm)
return best_index
def _try_auto_detect_dso(self):
"""Auto-select the DSO combo if the filename clearly names one, without
overriding a selection the user made themselves"""
if not self.selected_file or (self.dso_combo.currentIndex() >= 0 and not self._dso_auto_selected):
return
index = self._guess_dso_index_from_filename(self.selected_file)
if index is not None:
self.dso_combo.setCurrentIndex(index)
self._dso_auto_selected = True
self.detected_label.setText("Auto-detected from filename — please verify this is correct.")
self.detected_label.show()
elif self._dso_auto_selected:
self.dso_combo.setCurrentIndex(-1)
self.dso_combo.lineEdit().clear()
self._dso_auto_selected = False
self.detected_label.hide()
def _on_dso_manually_changed(self, index):
"""User picked a DSO themselves; stop treating the selection as a guess"""
self._dso_auto_selected = False
self.detected_label.hide()
self._clear_error(self.dso_combo)
def _fill_today_date(self):
"""Fill the date field with today's date"""
self.date_edit.setText(datetime.now().strftime('%Y-%m-%d'))
def _mark_error(self, widget):
widget.setStyleSheet(f"border: 1px solid {COLORS['error']};")
def _clear_error(self, widget):
widget.setStyleSheet("")
def dragEnterEvent(self, event):
"""Accept drag if it is a single supported image file"""
if event.mimeData().hasUrls():
urls = event.mimeData().urls()
if len(urls) == 1 and urls[0].isLocalFile():
ext = os.path.splitext(urls[0].toLocalFile())[1].lower()
if ext in SUPPORTED_IMAGE_EXTENSIONS:
event.acceptProposedAction()
return
event.ignore()
def dropEvent(self, event):
"""Set the dropped file as the selected image"""
urls = event.mimeData().urls()
if urls and urls[0].isLocalFile():
file_path = urls[0].toLocalFile()
ext = os.path.splitext(file_path)[1].lower()
if ext in SUPPORTED_IMAGE_EXTENSIONS:
event.acceptProposedAction()
self.set_file_path(file_path)
def _validate_and_accept(self):
"""Validate inputs before accepting, showing inline feedback instead of popups"""
errors = []
self._clear_error(self.file_path_edit)
self._clear_error(self.dso_combo)
if not self.selected_file:
errors.append("Select an image file.")
self._mark_error(self.file_path_edit)
elif not os.path.exists(self.selected_file):
errors.append("The selected image file no longer exists.")
self._mark_error(self.file_path_edit)
if self.dso_combo.currentIndex() < 0:
errors.append("Choose which DSO to attach the image to.")
self._mark_error(self.dso_combo)
if errors:
self.status_label.setText(" • ".join(errors))
self.status_label.show()
return
self.status_label.hide()
self.accept()
def get_image_data(self):
"""Return the entered image data"""
return {
'dsodetailid': self.dso_combo.currentData(),
'image_path': self.selected_file,
'equipment': ', '.join(filter(None, [self.telescope_combo.currentText().strip(),
self.camera_combo.currentText().strip()])),
'integration_time': self.integration_edit.text().strip(),
'date_taken': self.date_edit.text().strip(),
'notes': self.notes_edit.toPlainText().strip()
}
class GalleryCard(QFrame):
"""Individual card widget displaying a DSO thumbnail and info"""
double_clicked = Signal(dict) # Emits item_data when double-clicked
context_menu_requested = Signal(dict, object) # Emits item_data and position
def __init__(self, item_data, parent=None, thumbnail_size=150):
"""
Initialize gallery card
Args:
item_data (dict): Dictionary describing a single image (one DSO can
have multiple images, and therefore multiple cards)
- dsodetailid: DSO ID
- imageid: userimages.id for this specific image
- name: DSO name
- dsotype: DSO type code
- image_path: Path to this image
- equipment: Equipment used for this image