-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
2284 lines (1866 loc) · 104 KB
/
gui.py
File metadata and controls
2284 lines (1866 loc) · 104 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
"""
3decision Plugin GUI v1.2
Main dialog and interface components for the 3decision PyMOL plugin.
Version: 1.2
"""
import sys
import json
import time
import requests
from typing import Optional, Dict, List, Any
try:
# Import from pymol.Qt - the correct way for PyMOL plugins
from pymol.Qt import QtWidgets, QtCore, QtGui
from pymol.Qt.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QLineEdit, QPushButton,
QTableWidget, QTableWidgetItem, QLabel, QMessageBox, QHeaderView,
QProgressBar, QCheckBox, QAbstractItemView, QSplitter, QTabWidget, QWidget
)
from pymol.Qt.QtCore import Qt, QThread, pyqtSignal, QTimer
from pymol.Qt.QtGui import QIcon, QPixmap, QPainter, QBrush, QColor
except ImportError:
# Fallback for testing outside PyMOL
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QLineEdit, QPushButton,
QTableWidget, QTableWidgetItem, QLabel, QMessageBox, QHeaderView,
QProgressBar, QCheckBox, QAbstractItemView, QSplitter, QTabWidget, QWidget
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTimer
from PyQt5.QtGui import QIcon, QPixmap, QPainter, QBrush, QColor
import os
from .api_client import ThreeDecisionAPIClient
from .settings import SettingsDialog
class NumericTableWidgetItem(QTableWidgetItem):
"""Custom QTableWidgetItem that sorts numerically instead of alphabetically"""
def __init__(self, text, numeric_value):
super().__init__(text)
self.numeric_value = numeric_value
def __lt__(self, other):
"""Override less-than comparison for sorting"""
if isinstance(other, NumericTableWidgetItem):
return self.numeric_value < other.numeric_value
return super().__lt__(other)
# Simple logging functions - will check the api_client module for logging state
def log_debug(message):
"""Log a debug message if logging is enabled"""
# Import here to avoid circular imports
from .api_client import is_logging_enabled
if is_logging_enabled():
print(f"DEBUG: {message}")
def log_error(message):
"""Log an error message if logging is enabled"""
from .api_client import is_logging_enabled
if is_logging_enabled():
print(f"ERROR: {message}")
def log_info(message):
"""Log an info message if logging is enabled"""
from .api_client import is_logging_enabled
if is_logging_enabled():
print(f"INFO: {message}")
class SearchThread(QThread):
"""Thread for handling search operations"""
results_ready = pyqtSignal(list)
error_occurred = pyqtSignal(str)
status_update = pyqtSignal(str)
def __init__(self, api_client: ThreeDecisionAPIClient, search_query: str):
super().__init__()
self.api_client = api_client
self.search_query = search_query
def run(self):
try:
self.status_update.emit("Submitting search...")
# Submit search and get job info (now includes structure details)
job_response = self.api_client.submit_search(self.search_query)
if not job_response:
self.error_occurred.emit("Failed to submit search")
return
# Check if we have structure info already included (job completed)
if 'structures_info' in job_response:
structures = job_response['structures_info']
self.status_update.emit(f"Search completed. Found {len(structures)} structures.")
self.results_ready.emit(structures)
return
# Check if we need to poll for progress
if job_response.get('polling_needed'):
job_id = job_response.get('id')
queue_name = job_response.get('queue', 'basicSearch')
if not job_id:
self.error_occurred.emit("No job ID received from search")
return
self.status_update.emit(f"Job submitted (ID: {job_id}). Waiting for completion...")
max_attempts = 60 # 60 attempts with 2-second intervals = 2 minutes max
attempt = 0
while attempt < max_attempts:
try:
# Poll the queue endpoint until progress reaches 100
result = self.api_client.get_job_status(queue_name, job_id)
if result:
progress = result.get('progress', 0)
self.status_update.emit(f"Search progress: {progress}%")
# Check if we have results available (even if progress < 100)
structure_ids = []
if 'returnvalue' in result and 'STRUCTURE_ID' in result['returnvalue']:
structure_ids = result['returnvalue']['STRUCTURE_ID']
# Stop polling if job is complete OR if we have empty results
if progress == 100 or (isinstance(structure_ids, list) and len(structure_ids) == 0 and progress > 0):
if structure_ids:
self.status_update.emit("Fetching structure details...")
structures = self.api_client.get_structures_info(structure_ids)
self.results_ready.emit(structures)
else:
self.status_update.emit("Search completed with no results.")
self.results_ready.emit([])
return
elif result.get('status') == 'failed':
self.error_occurred.emit("Search job failed")
return
# Wait before next poll
self.msleep(2000) # 2 seconds
attempt += 1
except Exception as e:
log_error(f"Polling error: {e}")
attempt += 1
self.msleep(2000)
self.error_occurred.emit("Search timed out waiting for completion")
return
# Fallback to old logic for backwards compatibility
job_id = job_response.get('id')
queue_name = job_response.get('queue', 'basicSearch')
if not job_id:
self.error_occurred.emit("No job ID received from search")
return
# Check if results are already available (direct response)
if job_response.get('status') == 'completed':
structure_ids = job_response.get('result', [])
if structure_ids:
self.status_update.emit("Fetching structure details...")
structures = self.api_client.get_structures_info(structure_ids)
self.results_ready.emit(structures)
else:
self.results_ready.emit([])
return
self.status_update.emit(f"Polling for results (Job ID: {job_id})...")
# Poll for results (skip if direct response)
if job_id == 'direct':
return # Already handled above
max_attempts = 30 # 30 attempts with 2-second intervals = 1 minute max
attempt = 0
while attempt < max_attempts:
try:
result = self.api_client.get_job_status(queue_name, job_id)
if result and result.get('status') == 'completed':
structure_ids = result.get('result', [])
if structure_ids:
# Get structure details
self.status_update.emit("Fetching structure details...")
structures = self.api_client.get_structures_info(structure_ids)
self.results_ready.emit(structures)
else:
self.results_ready.emit([])
return
elif result and result.get('status') == 'failed':
self.error_occurred.emit("Search job failed")
return
except Exception as e:
log_error(f"Polling attempt {attempt + 1} failed: {e}")
attempt += 1
self.msleep(2000) # Wait 2 seconds
self.error_occurred.emit("Search timed out")
except Exception as e:
self.error_occurred.emit(f"Search error: {str(e)}")
def get_object_name(external_code: str, label: str = None, source: str = None, title: str = None, internal_id: str = None) -> str:
"""
Determine the best object name for a structure in PyMOL.
Naming logic:
- For public domain structures (RCSB PDB, PDB, AlphaFold, etc.): use external_code (e.g., '1abo')
- For private/internal structures: use the attribute configured in settings
(label, title, external_code, or internal_id)
- Fallback: use external_code
The name is sanitized to be valid for PyMOL (no spaces, special chars replaced).
"""
from .api_client import get_private_structure_naming_attribute
# Define public/known sources where external_code is meaningful
public_sources = [
'rcsb', 'pdb', 'alphafold', 'uniprot', 'chembl', 'drugbank',
'pubchem', 'zinc', 'emdb', 'wwpdb'
]
# Check if it's a public domain structure
is_public = False
if source:
source_lower = source.lower()
is_public = any(ps in source_lower for ps in public_sources)
# Determine the name to use
if is_public:
# Use external_code for public structures (it's the PDB code, etc.)
name = external_code
else:
# For private structures, use the configured naming attribute
naming_attr = get_private_structure_naming_attribute()
if naming_attr == 'label' and label and label.strip() and label.lower() not in ['n/a', 'null', 'none', '']:
name = label.strip()
elif naming_attr == 'title' and title and title.strip() and title.lower() not in ['n/a', 'null', 'none', '']:
name = title.strip()
elif naming_attr == 'internal_id' and internal_id and internal_id.strip() and internal_id.lower() not in ['n/a', 'null', 'none', '']:
name = internal_id.strip()
else:
# Fallback to external_code
name = external_code
# Strip '3dec_' prefix if present (from API file naming)
if name.lower().startswith('3dec_'):
name = name[5:]
# Sanitize name for PyMOL (replace invalid characters)
# PyMOL object names should be alphanumeric with underscores
sanitized = ''.join(c if c.isalnum() or c == '_' else '_' for c in name)
# Ensure we have a valid name
if not sanitized:
sanitized = external_code if external_code else 'structure'
return sanitized
class LoadStructureThread(QThread):
"""Thread for loading structures into PyMOL"""
structure_loaded = pyqtSignal(str, str) # structure_id, object_name
error_occurred = pyqtSignal(str)
status_update = pyqtSignal(str)
all_structures_loaded = pyqtSignal() # Signal when all structures are done loading
def __init__(self, api_client: ThreeDecisionAPIClient, structure_data: List[Dict[str, str]]):
super().__init__()
self.api_client = api_client
self.structure_data = structure_data # List of {structure_id, external_code, label?, title?, source?, matrix?}
def run(self):
try:
from pymol import cmd
# Check if any structures have transformation matrices
has_matrices = any(s.get('matrix') is not None for s in self.structure_data)
if has_matrices:
# Use batch export with transformation matrices
log_debug("Loading structures with transformation matrices using batch export")
self.status_update.emit("Loading structures with transformations...")
# Prepare structures for batch export
structures_with_transforms = []
for structure_info in self.structure_data:
structure_id = int(structure_info['structure_id'])
external_code = structure_info['external_code']
matrix = structure_info.get('matrix')
# Identity matrix as default (no transformation)
identity_matrix = [
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]
if matrix:
# Matrix should be a 4x4 nested list, flatten it to 16 values
if isinstance(matrix, list) and len(matrix) == 4:
flat_matrix = []
for row in matrix:
if isinstance(row, list) and len(row) == 4:
flat_matrix.extend(row)
else:
log_error(f"Invalid matrix row format for structure {structure_id}: {row}")
flat_matrix = None
break
if flat_matrix and len(flat_matrix) == 16:
structures_with_transforms.append({
"structure_id": structure_id,
"external_code": external_code,
"transform": flat_matrix
})
else:
log_error(f"Invalid matrix format for structure {structure_id}, using identity matrix")
structures_with_transforms.append({
"structure_id": structure_id,
"external_code": external_code,
"transform": identity_matrix
})
else:
log_error(f"Invalid matrix structure for {structure_id}, using identity matrix")
structures_with_transforms.append({
"structure_id": structure_id,
"external_code": external_code,
"transform": identity_matrix
})
else:
# No matrix provided, use identity matrix (no transformation)
log_debug(f"No matrix for structure {structure_id}, using identity matrix")
structures_with_transforms.append({
"structure_id": structure_id,
"external_code": external_code,
"transform": identity_matrix
})
# Get batch PDB with transformations applied
# Returns a dict mapping filename to PDB content
pdb_files_dict = self.api_client.export_structures_with_transforms(structures_with_transforms)
if pdb_files_dict:
# Load each structure as a separate object
# Try to match filenames to structure info
loaded_count = 0
for structure_info in self.structure_data:
structure_id = structure_info['structure_id']
external_code = structure_info['external_code']
label = structure_info.get('label')
source = structure_info.get('source')
title = structure_info.get('title')
# Fetch internal_id if the naming attribute is set to 'internal_id'
from .api_client import get_private_structure_naming_attribute
internal_id = None
if get_private_structure_naming_attribute() == 'internal_id':
internal_id = self.api_client.get_structure_internal_id(structure_id)
object_name = get_object_name(external_code, label, source, title, internal_id)
# Find matching PDB file in the dict
# The API may use different naming conventions (e.g., "3dec_code.pdb" or "code.pdb")
pdb_content = None
for filename, content in pdb_files_dict.items():
# Check if filename contains the external_code
filename_lower = filename.lower()
code_lower = external_code.lower()
if code_lower in filename_lower or filename_lower.replace('3dec_', '').startswith(code_lower):
pdb_content = content
log_debug(f"Matched {external_code} to file {filename}")
break
if not pdb_content and len(pdb_files_dict) == 1:
# If only one file and one structure, use it
pdb_content = list(pdb_files_dict.values())[0]
log_debug(f"Using single PDB file for {external_code}")
if pdb_content:
try:
# Load the PDB content as a separate object
cmd.read_pdbstr(pdb_content, object_name)
# Attach 3decision metadata
cmd.set_property("3decision_structure_id", structure_id, object_name)
cmd.set_property("3decision_external_code", external_code, object_name)
cmd.set_property("3decision_label", label or '', object_name)
cmd.set_property("3decision_source", source or 'unknown', object_name)
log_info(f"3decision Plugin: Loaded {object_name} with structure_id: {structure_id} (with transformation)")
self.structure_loaded.emit(structure_id, object_name)
loaded_count += 1
except Exception as e:
log_error(f"Failed to load object {object_name}: {e}")
self.error_occurred.emit(f"Failed to load object {external_code}: {str(e)}")
else:
log_error(f"Could not find PDB content for {external_code}")
self.error_occurred.emit(f"Could not find PDB content for {external_code}")
if loaded_count == 0:
self.error_occurred.emit("Failed to load any structures")
else:
self.error_occurred.emit("Failed to load structures with transformations")
else:
# Load structures individually without transformations (search results)
log_debug("Loading structures individually without transformations")
for structure_info in self.structure_data:
structure_id = structure_info['structure_id']
external_code = structure_info['external_code']
label = structure_info.get('label')
source = structure_info.get('source')
title = structure_info.get('title')
self.status_update.emit(f"Loading structure {external_code} ({structure_id})...")
# Get PDB content
pdb_content = self.api_client.export_structure_pdb(structure_id)
if pdb_content:
# Fetch internal_id if the naming attribute is set to 'internal_id'
from .api_client import get_private_structure_naming_attribute
internal_id = None
if get_private_structure_naming_attribute() == 'internal_id':
internal_id = self.api_client.get_structure_internal_id(structure_id)
# Load into PyMOL using smart object naming
object_name = get_object_name(external_code, label, source, title, internal_id)
cmd.read_pdbstr(pdb_content, object_name)
# Attach 3decision metadata as object properties
cmd.set_property("3decision_structure_id", structure_id, object_name)
cmd.set_property("3decision_external_code", external_code, object_name)
cmd.set_property("3decision_label", label or '', object_name)
cmd.set_property("3decision_source", source or 'unknown', object_name)
log_info(f"3decision Plugin: Loaded {object_name} with structure_id: {structure_id}")
self.structure_loaded.emit(structure_id, object_name)
else:
self.error_occurred.emit(f"Failed to load structure {external_code} ({structure_id})")
# Signal that all structures are done loading
self.all_structures_loaded.emit()
except Exception as e:
self.error_occurred.emit(f"Loading error: {str(e)}")
class ThreeDecisionDialog(QDialog):
"""Main 3decision plugin dialog"""
def __init__(self, parent=None):
super().__init__(parent)
self.api_client = ThreeDecisionAPIClient()
self.search_thread = None
self.load_thread = None
self.all_results = [] # Initialize empty results list for filtering
self.projects_data = [] # Initialize empty projects list
self.current_project_structures = [] # Current project structures
self.projects_loaded = False # Track if projects have been loaded
# Associated files state
self.current_structure = None
self.current_structure_id = None
self.current_external_code = None
self.current_transform_matrix = None
self.init_ui()
self.check_login_status()
def init_ui(self):
"""Initialize the user interface"""
self.setWindowTitle("3decision Structure Search v1.1")
self.setMinimumSize(800, 600)
# Remove the question mark from the title bar on Windows
self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
# Main layout
main_layout = QVBoxLayout()
# Settings button in top right
settings_layout = QHBoxLayout()
settings_layout.addStretch()
self.settings_button = QPushButton()
self.settings_button.setFixedSize(30, 30)
self.settings_button.clicked.connect(self.open_settings)
self.settings_button.setToolTip("Settings")
# Prevent this button from being triggered by Enter key (fixes Windows issue)
self.settings_button.setAutoDefault(False)
# Try to load the cog icon
cog_icon = self.load_cog_icon()
if cog_icon:
self.settings_button.setIcon(QIcon(cog_icon))
self.settings_button.setText("") # Remove text when icon is available
else:
self.settings_button.setText("⚙") # Fallback to text symbol
settings_layout.addWidget(self.settings_button)
main_layout.addLayout(settings_layout)
# Tab widget for Search and Projects
self.tab_widget = QTabWidget()
# Search tab
self.search_widget = self._create_search_tab()
self.tab_widget.addTab(self.search_widget, "Search")
# Projects tab
self.projects_widget = self._create_projects_tab()
self.tab_widget.addTab(self.projects_widget, "Projects")
# Associated Files tab
self.files_widget = self._create_files_tab()
self.tab_widget.addTab(self.files_widget, "Associated Files")
main_layout.addWidget(self.tab_widget)
# Status label at bottom
self.status_label = QLabel("Not logged in")
self.status_label.setStyleSheet("color: red; padding: 5px;")
main_layout.addWidget(self.status_label)
self.setLayout(main_layout)
def _create_search_tab(self):
"""Create the search tab content"""
widget = QWidget()
layout = QVBoxLayout()
# Search section
search_layout = QHBoxLayout()
search_layout.addWidget(QLabel("Search:"))
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Enter search term (e.g., ABL1)")
self.search_input.returnPressed.connect(self.submit_search)
search_layout.addWidget(self.search_input)
self.submit_button = QPushButton("Submit")
self.submit_button.clicked.connect(self.submit_search)
self.submit_button.setEnabled(False)
# Prevent this button from being triggered by Enter key when disabled (search_input handles Enter)
self.submit_button.setAutoDefault(False)
search_layout.addWidget(self.submit_button)
layout.addLayout(search_layout)
# Progress bar
self.progress_bar = QProgressBar()
self.progress_bar.setVisible(False)
layout.addWidget(self.progress_bar)
# Column filters section
filters_label = QLabel("Filter Results:")
filters_label.setStyleSheet("font-weight: bold; margin-top: 10px;")
layout.addWidget(filters_label)
filters_layout = QHBoxLayout()
# Filter inputs for each column (skip "Select" checkbox column)
self.filter_external_code = QLineEdit()
self.filter_external_code.setPlaceholderText("External Code")
self.filter_external_code.textChanged.connect(self.apply_filters)
filters_layout.addWidget(self.filter_external_code)
self.filter_label = QLineEdit()
self.filter_label.setPlaceholderText("Label")
self.filter_label.textChanged.connect(self.apply_filters)
filters_layout.addWidget(self.filter_label)
self.filter_title = QLineEdit()
self.filter_title.setPlaceholderText("Title")
self.filter_title.textChanged.connect(self.apply_filters)
filters_layout.addWidget(self.filter_title)
self.filter_method = QLineEdit()
self.filter_method.setPlaceholderText("Method")
self.filter_method.textChanged.connect(self.apply_filters)
filters_layout.addWidget(self.filter_method)
# Resolution filter with range support (min-max)
self.filter_resolution = QLineEdit()
self.filter_resolution.setPlaceholderText("Resolution (e.g., <2.0 or 1.5-3.0)")
self.filter_resolution.textChanged.connect(self.apply_filters)
filters_layout.addWidget(self.filter_resolution)
self.filter_source = QLineEdit()
self.filter_source.setPlaceholderText("Source")
self.filter_source.textChanged.connect(self.apply_filters)
filters_layout.addWidget(self.filter_source)
# Clear filters button
clear_filters_btn = QPushButton("Clear Filters")
clear_filters_btn.setAutoDefault(False)
clear_filters_btn.clicked.connect(self.clear_filters)
filters_layout.addWidget(clear_filters_btn)
layout.addLayout(filters_layout)
# Results table
self.results_table = QTableWidget()
self.results_table.setColumnCount(6)
self.results_table.setHorizontalHeaderLabels([
"External Code", "Label", "Title", "Method", "Resolution", "Source"
])
self.results_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.results_table.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.results_table.setEditTriggers(QAbstractItemView.NoEditTriggers) # Disable editing
self.results_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.results_table.setAlternatingRowColors(True)
# Enable sorting by clicking column headers
self.results_table.setSortingEnabled(True)
layout.addWidget(self.results_table)
# Load button
button_layout = QHBoxLayout()
button_layout.addStretch()
self.load_button = QPushButton("Load Selected in PyMOL")
self.load_button.setAutoDefault(False)
self.load_button.clicked.connect(self.load_selected_structures)
self.load_button.setEnabled(False)
button_layout.addWidget(self.load_button)
layout.addLayout(button_layout)
widget.setLayout(layout)
return widget
def _create_projects_tab(self):
"""Create the projects tab content"""
widget = QWidget()
layout = QVBoxLayout()
# Instructions
layout.addWidget(QLabel("Browse and load structures from your 3decision projects"))
# Projects table
layout.addWidget(QLabel("Projects:"))
# Projects filters (above table)
projects_filters_layout = QHBoxLayout()
self.projects_filter_name = QLineEdit()
self.projects_filter_name.setPlaceholderText("Project Name")
self.projects_filter_name.textChanged.connect(self.apply_projects_filters)
projects_filters_layout.addWidget(self.projects_filter_name)
self.projects_filter_owner = QLineEdit()
self.projects_filter_owner.setPlaceholderText("Owner")
self.projects_filter_owner.textChanged.connect(self.apply_projects_filters)
projects_filters_layout.addWidget(self.projects_filter_owner)
self.projects_filter_structures = QLineEdit()
self.projects_filter_structures.setPlaceholderText("Structures (e.g., >10)")
self.projects_filter_structures.textChanged.connect(self.apply_projects_filters)
projects_filters_layout.addWidget(self.projects_filter_structures)
self.projects_filter_id = QLineEdit()
self.projects_filter_id.setPlaceholderText("Project ID")
self.projects_filter_id.textChanged.connect(self.apply_projects_filters)
projects_filters_layout.addWidget(self.projects_filter_id)
# Clear projects filters button
clear_projects_filters_btn = QPushButton("Clear Filters")
clear_projects_filters_btn.setAutoDefault(False)
clear_projects_filters_btn.clicked.connect(self.clear_projects_filters)
projects_filters_layout.addWidget(clear_projects_filters_btn)
layout.addLayout(projects_filters_layout)
self.projects_table = QTableWidget()
self.projects_table.setColumnCount(4)
self.projects_table.setHorizontalHeaderLabels([
"Project Name", "Owner", "Structures", "Project ID"
])
# Configure table
header = self.projects_table.horizontalHeader()
header.setStretchLastSection(True)
header.resizeSection(0, 200) # Project Name
header.resizeSection(1, 120) # Owner
header.resizeSection(2, 80) # Structures
header.resizeSection(3, 150) # Project ID
self.projects_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.projects_table.setEditTriggers(QAbstractItemView.NoEditTriggers) # Disable editing
self.projects_table.setAlternatingRowColors(True)
self.projects_table.setSortingEnabled(True)
self.projects_table.itemSelectionChanged.connect(self.on_project_selection_changed)
layout.addWidget(self.projects_table)
# Projects buttons
projects_buttons = QHBoxLayout()
refresh_button = QPushButton("Refresh Projects")
refresh_button.setAutoDefault(False)
refresh_button.clicked.connect(self.load_projects_for_tab)
projects_buttons.addWidget(refresh_button)
projects_buttons.addStretch()
layout.addLayout(projects_buttons)
# Project structures list below
layout.addWidget(QLabel("Project Structures (click to select):"))
# Column filters for project structures
project_filters_layout = QHBoxLayout()
self.project_filter_external_code = QLineEdit()
self.project_filter_external_code.setPlaceholderText("External Code")
self.project_filter_external_code.textChanged.connect(self.apply_project_filters)
project_filters_layout.addWidget(self.project_filter_external_code)
self.project_filter_label = QLineEdit()
self.project_filter_label.setPlaceholderText("Label")
self.project_filter_label.textChanged.connect(self.apply_project_filters)
project_filters_layout.addWidget(self.project_filter_label)
self.project_filter_title = QLineEdit()
self.project_filter_title.setPlaceholderText("Title")
self.project_filter_title.textChanged.connect(self.apply_project_filters)
project_filters_layout.addWidget(self.project_filter_title)
self.project_filter_method = QLineEdit()
self.project_filter_method.setPlaceholderText("Method")
self.project_filter_method.textChanged.connect(self.apply_project_filters)
project_filters_layout.addWidget(self.project_filter_method)
# Clear filters button
clear_project_filters_btn = QPushButton("Clear Filters")
clear_project_filters_btn.setAutoDefault(False)
clear_project_filters_btn.clicked.connect(self.clear_project_filters)
project_filters_layout.addWidget(clear_project_filters_btn)
layout.addLayout(project_filters_layout)
self.project_structures_table = QTableWidget()
self.project_structures_table.setColumnCount(5)
self.project_structures_table.setHorizontalHeaderLabels([
"External Code", "Label", "Title", "Method", "Files"
])
self.project_structures_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.project_structures_table.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.project_structures_table.setEditTriggers(QAbstractItemView.NoEditTriggers) # Disable editing
header = self.project_structures_table.horizontalHeader()
header.setSectionResizeMode(QHeaderView.Stretch)
header.setSectionResizeMode(4, QHeaderView.Fixed) # Files column fixed width
self.project_structures_table.setColumnWidth(4, 80) # Files button column
self.project_structures_table.setAlternatingRowColors(True)
self.project_structures_table.setSortingEnabled(True)
layout.addWidget(self.project_structures_table)
# Structure selection buttons
structure_buttons = QHBoxLayout()
select_all_btn = QPushButton("Select All")
select_all_btn.setAutoDefault(False)
select_all_btn.clicked.connect(self.select_all_project_structures)
structure_buttons.addWidget(select_all_btn)
select_none_btn = QPushButton("Select None")
select_none_btn.setAutoDefault(False)
select_none_btn.clicked.connect(self.select_none_project_structures)
structure_buttons.addWidget(select_none_btn)
structure_buttons.addStretch()
self.load_project_structures_button = QPushButton("Load Selected Structures")
self.load_project_structures_button.setAutoDefault(False)
self.load_project_structures_button.clicked.connect(self.load_selected_project_structures)
self.load_project_structures_button.setEnabled(False)
structure_buttons.addWidget(self.load_project_structures_button)
layout.addLayout(structure_buttons)
widget.setLayout(layout)
return widget
def _create_files_tab(self):
"""Create the associated files tab"""
widget = QWidget()
layout = QVBoxLayout()
# Header with current structure info
self.files_header_label = QLabel("Associated Files - Select a structure from the Projects tab to view its files")
self.files_header_label.setStyleSheet("font-weight: bold; padding: 5px;")
layout.addWidget(self.files_header_label)
# Checkbox to apply transformation matrix
transform_layout = QHBoxLayout()
self.apply_transform_checkbox = QCheckBox("Apply transformation matrix to associated files (if available)")
self.apply_transform_checkbox.setToolTip("When enabled, associated files (maps, etc.) will be transformed using the structure's reference transformation matrix")
self.apply_transform_checkbox.setChecked(True) # Default to enabled
transform_layout.addWidget(self.apply_transform_checkbox)
transform_layout.addStretch()
layout.addLayout(transform_layout)
# Files table
self.files_table = QTableWidget()
self.files_table.setColumnCount(5)
self.files_table.setHorizontalHeaderLabels(["File Name", "Type", "Size", "Format", "Description"])
self.files_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.files_table.setAlternatingRowColors(True)
self.files_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.files_table.setSortingEnabled(True)
# Configure header for resizable columns
header = self.files_table.horizontalHeader()
header.setStretchLastSection(True)
header.setSectionResizeMode(QHeaderView.Interactive)
# Set reasonable default column widths
self.files_table.setColumnWidth(0, 200) # File Name
self.files_table.setColumnWidth(1, 100) # Type
self.files_table.setColumnWidth(2, 80) # Size
self.files_table.setColumnWidth(3, 100) # Format
# Description column stretches
self.files_table.itemSelectionChanged.connect(self._on_file_selection_changed)
layout.addWidget(self.files_table)
# Buttons for file operations
files_buttons = QHBoxLayout()
self.refresh_files_button = QPushButton("Refresh Files")
self.refresh_files_button.setAutoDefault(False)
self.refresh_files_button.clicked.connect(self.refresh_associated_files)
self.refresh_files_button.setEnabled(False)
files_buttons.addWidget(self.refresh_files_button)
files_buttons.addStretch()
self.open_file_button = QPushButton("Open in PyMOL")
self.open_file_button.setAutoDefault(False)
self.open_file_button.clicked.connect(self.open_selected_file)
self.open_file_button.setEnabled(False)
files_buttons.addWidget(self.open_file_button)
self.open_system_button = QPushButton("Download && Open")
self.open_system_button.setToolTip("Download the file and open it with the system's default application (useful for PDFs, images, etc.)")
self.open_system_button.setAutoDefault(False)
self.open_system_button.clicked.connect(self.download_and_open_with_system)
self.open_system_button.setEnabled(False)
files_buttons.addWidget(self.open_system_button)
layout.addLayout(files_buttons)
# Status label for file operations
self.files_status_label = QLabel("")
self.files_status_label.setStyleSheet("color: gray; padding: 5px;")
layout.addWidget(self.files_status_label)
widget.setLayout(layout)
return widget
def load_projects_for_tab(self):
"""Load projects when Projects tab is accessed"""
try:
# Check authentication first
if not self.api_client.is_authenticated():
log_debug("Not authenticated, attempting to authenticate with saved token")
# Try to authenticate with saved token
if self.api_client.test_connection():
log_debug("Successfully authenticated with saved token")
self.check_login_status()
else:
# Authentication failed, prompt user
reply = QMessageBox.question(
self,
"Authentication Required",
"You need to be logged in to view projects.\n\n"
"Would you like to open settings to configure your API token?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.Yes
)
if reply == QMessageBox.Yes:
self.open_settings()
return
projects = self.api_client.get_projects()
# Filter out the "3decision" project
filtered_projects = []
for project in projects:
project_label = project.get('project_label', '').lower()
project_name = project.get('project_name', '').lower()
# Skip if project label or name is "3decision"
if project_label != '3decision' and project_name != '3decision':
filtered_projects.append(project)
else:
log_debug(f"Filtering out 3decision system project: {project.get('project_label', '')}")
self.projects_data = filtered_projects
self.populate_projects_table()
except Exception as e:
log_error(f"Failed to load projects: {e}")
# Check if it's an authentication error
error_str = str(e).lower()
if 'auth' in error_str or 'token' in error_str or '401' in error_str or '403' in error_str:
reply = QMessageBox.critical(
self,
"Authentication Error",
f"Failed to load projects: {str(e)}\n\n"
"Your authentication token may have expired.\n"
"Would you like to open settings to update your API token?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.Yes
)
if reply == QMessageBox.Yes:
self.open_settings()
else:
QMessageBox.critical(self, "Error", f"Failed to load projects: {str(e)}")
def populate_projects_table(self):
"""Populate the projects table with data"""
# Disable sorting while populating for better performance
self.projects_table.setSortingEnabled(False)
self.projects_table.setRowCount(len(self.projects_data))
# Debug: Log the structure of the first project to help identify owner field
if self.projects_data:
log_debug(f"Project data structure (first project): {json.dumps(self.projects_data[0], indent=2)}")
for row, project in enumerate(self.projects_data):
# Project Name
name_item = QTableWidgetItem(project.get('project_label', ''))
name_item.setFlags(name_item.flags() & ~Qt.ItemIsEditable)
# Store the full project data in the first column for easy retrieval
name_item.setData(Qt.UserRole, project)
self.projects_table.setItem(row, 0, name_item)
# Owner - try multiple possible field names for project owner
owner_field = None
owner = None
for field in ['owner', 'project_owner', 'created_by', 'owner_username', 'creator', 'author', 'username']:
if project.get(field):
owner = project.get(field)
owner_field = field
break
if not owner:
owner = ''
owner_field = 'none'
# Debug: Log which field was used for owner (only for first project to avoid spam)
if row == 0:
log_debug(f"Using '{owner_field}' field for project owner: '{owner}'")
owner_item = QTableWidgetItem(str(owner))
owner_item.setFlags(owner_item.flags() & ~Qt.ItemIsEditable)
self.projects_table.setItem(row, 1, owner_item)
# Structures count - use numeric sorting
count = project.get('count_structures_in_project', 0)
count_item = NumericTableWidgetItem(str(count), count)
count_item.setFlags(count_item.flags() & ~Qt.ItemIsEditable)
self.projects_table.setItem(row, 2, count_item)
# Project ID
id_item = QTableWidgetItem(str(project.get('project_id', '')))
id_item.setFlags(id_item.flags() & ~Qt.ItemIsEditable)
self.projects_table.setItem(row, 3, id_item)
# Re-enable sorting after populating
self.projects_table.setSortingEnabled(True)
def on_project_selection_changed(self):
"""Handle project table selection change"""
selected_rows = self.projects_table.selectionModel().selectedRows()
if selected_rows:
self.load_project_structures_button.setEnabled(False)
# Load structures for selected project
row = selected_rows[0].row()
project_data = self.projects_table.item(row, 0).data(Qt.UserRole)
project_id = project_data.get('project_id')
self.load_project_structures_in_tab(project_id)