2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
24 import jalview.api.structures.JalviewStructureDisplayI;
25 import jalview.bin.Cache;
26 import jalview.bin.Jalview;
27 import jalview.datamodel.DBRefEntry;
28 import jalview.datamodel.DBRefSource;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.fts.api.FTSData;
32 import jalview.fts.api.FTSDataColumnI;
33 import jalview.fts.api.FTSRestClientI;
34 import jalview.fts.core.FTSRestRequest;
35 import jalview.fts.core.FTSRestResponse;
36 import jalview.fts.service.pdb.PDBFTSRestClient;
37 import jalview.io.DataSourceType;
38 import jalview.jbgui.GStructureChooser;
39 import jalview.structure.StructureMapping;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
42 import jalview.ws.DBRefFetcher;
43 import jalview.ws.sifts.SiftsSettings;
45 import java.awt.event.ItemEvent;
46 import java.util.ArrayList;
47 import java.util.Collection;
48 import java.util.HashSet;
49 import java.util.LinkedHashSet;
50 import java.util.List;
51 import java.util.Objects;
53 import java.util.Vector;
55 import javax.swing.JCheckBox;
56 import javax.swing.JComboBox;
57 import javax.swing.JLabel;
58 import javax.swing.JTable;
59 import javax.swing.SwingUtilities;
60 import javax.swing.table.AbstractTableModel;
63 * Provides the behaviors for the Structure chooser Panel
68 @SuppressWarnings("serial")
69 public class StructureChooser extends GStructureChooser
70 implements IProgressIndicator
72 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
74 private static int MAX_QLENGTH = 7820;
76 private SequenceI selectedSequence;
78 private SequenceI[] selectedSequences;
80 private IProgressIndicator progressIndicator;
82 private Collection<FTSData> discoveredStructuresSet;
84 private FTSRestRequest lastPdbRequest;
86 private FTSRestClientI pdbRestClient;
88 private String selectedPdbFileName;
90 private boolean isValidPBDEntry;
92 private boolean cachedPDBExists;
94 private static StructureViewer lastTargetedView = null;
96 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
100 this.selectedSequence = selectedSeq;
101 this.selectedSequences = selectedSeqs;
102 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
107 * Initializes parameters used by the Structure Chooser Panel
109 protected void init()
111 if (!Jalview.isHeadlessMode())
113 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
116 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
118 // ensure a filter option is in force for search
119 populateFilterComboBox(true, cachedPDBExists);
120 Thread discoverPDBStructuresThread = new Thread(new Runnable()
125 long startTime = System.currentTimeMillis();
126 updateProgressIndicator(MessageManager
127 .getString("status.loading_cached_pdb_entries"), startTime);
128 loadLocalCachedPDBEntries();
129 updateProgressIndicator(null, startTime);
130 updateProgressIndicator(MessageManager.getString(
131 "status.searching_for_pdb_structures"), startTime);
132 fetchStructuresMetaData();
133 // revise filter options if no results were found
134 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
135 discoverStructureViews();
136 updateProgressIndicator(null, startTime);
137 mainFrame.setVisible(true);
141 discoverPDBStructuresThread.start();
145 * Builds a drop-down choice list of existing structure viewers to which new
146 * structures may be added. If this list is empty then it, and the 'Add'
147 * button, are hidden.
149 private void discoverStructureViews()
151 if (Desktop.instance != null)
153 targetView.removeAllItems();
154 if (lastTargetedView != null && !lastTargetedView.isVisible())
156 lastTargetedView = null;
158 int linkedViewsAt = 0;
159 for (StructureViewerBase view : Desktop.instance
160 .getStructureViewers(null, null))
162 StructureViewer viewHandler = (lastTargetedView != null
163 && lastTargetedView.sview == view) ? lastTargetedView
164 : StructureViewer.reconfigure(view);
166 if (view.isLinkedWith(ap))
168 targetView.insertItemAt(viewHandler,
173 targetView.addItem(viewHandler);
178 * show option to Add to viewer if at least 1 viewer found
180 targetView.setVisible(false);
181 if (targetView.getItemCount() > 0)
183 targetView.setVisible(true);
184 if (lastTargetedView != null)
186 targetView.setSelectedItem(lastTargetedView);
190 targetView.setSelectedIndex(0);
193 btn_add.setVisible(targetView.isVisible());
198 * Updates the progress indicator with the specified message
201 * displayed message for the operation
203 * unique handle for this indicator
205 protected void updateProgressIndicator(String message, long id)
207 if (progressIndicator != null)
209 progressIndicator.setProgressBar(message, id);
214 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
217 void fetchStructuresMetaData()
219 long startTime = System.currentTimeMillis();
220 pdbRestClient = PDBFTSRestClient.getInstance();
221 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
222 .getStructureSummaryFields();
224 discoveredStructuresSet = new LinkedHashSet<>();
225 HashSet<String> errors = new HashSet<>();
226 for (SequenceI seq : selectedSequences)
228 FTSRestRequest pdbRequest = new FTSRestRequest();
229 pdbRequest.setAllowEmptySeq(false);
230 pdbRequest.setResponseSize(500);
231 pdbRequest.setFieldToSearchBy("(");
232 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
234 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
235 !chk_invertFilter.isSelected());
236 pdbRequest.setWantedFields(wantedFields);
237 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
238 pdbRequest.setAssociatedSequence(seq);
239 FTSRestResponse resultList;
242 resultList = pdbRestClient.executeRequest(pdbRequest);
243 } catch (Exception e)
246 errors.add(e.getMessage());
249 lastPdbRequest = pdbRequest;
250 if (resultList.getSearchSummary() != null
251 && !resultList.getSearchSummary().isEmpty())
253 discoveredStructuresSet.addAll(resultList.getSearchSummary());
257 int noOfStructuresFound = 0;
258 String totalTime = (System.currentTimeMillis() - startTime)
260 if (discoveredStructuresSet != null
261 && !discoveredStructuresSet.isEmpty())
263 getResultTable().setModel(FTSRestResponse
264 .getTableModel(lastPdbRequest, discoveredStructuresSet));
265 noOfStructuresFound = discoveredStructuresSet.size();
266 mainFrame.setTitle(MessageManager.formatMessage(
267 "label.structure_chooser_no_of_structures",
268 noOfStructuresFound, totalTime));
272 mainFrame.setTitle(MessageManager
273 .getString("label.structure_chooser_manual_association"));
274 if (errors.size() > 0)
276 StringBuilder errorMsg = new StringBuilder();
277 for (String error : errors)
279 errorMsg.append(error).append("\n");
281 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
282 MessageManager.getString("label.pdb_web-service_error"),
283 JvOptionPane.ERROR_MESSAGE);
288 protected void loadLocalCachedPDBEntries()
290 ArrayList<CachedPDB> entries = new ArrayList<>();
291 for (SequenceI seq : selectedSequences)
293 if (seq.getDatasetSequence() != null
294 && seq.getDatasetSequence().getAllPDBEntries() != null)
296 for (PDBEntry pdbEntry : seq.getDatasetSequence()
299 if (pdbEntry.getFile() != null)
301 entries.add(new CachedPDB(seq, pdbEntry));
306 cachedPDBExists = !entries.isEmpty();
307 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
308 tbl_local_pdb.setModel(tableModelx);
312 * Builds a query string for a given sequences using its DBRef entries
315 * the sequences to build a query for
316 * @return the built query string
319 static String buildQuery(SequenceI seq)
321 boolean isPDBRefsFound = false;
322 boolean isUniProtRefsFound = false;
323 StringBuilder queryBuilder = new StringBuilder();
324 Set<String> seqRefs = new LinkedHashSet<>();
327 * note PDBs as DBRefEntry so they are not duplicated in query
329 Set<String> pdbids = new HashSet<>();
331 if (seq.getAllPDBEntries() != null
332 && queryBuilder.length() < MAX_QLENGTH)
334 for (PDBEntry entry : seq.getAllPDBEntries())
336 if (isValidSeqName(entry.getId()))
338 String id = entry.getId().toLowerCase();
339 queryBuilder.append("pdb_id:").append(id).append(" OR ");
340 isPDBRefsFound = true;
346 List<DBRefEntry> refs = seq.getDBRefs();
347 if (refs != null && refs.size() != 0)
349 for (int ib = 0, nb = refs.size(); ib < nb; ib++)
351 DBRefEntry dbRef = refs.get(ib);
352 if (isValidSeqName(getDBRefId(dbRef))
353 && queryBuilder.length() < MAX_QLENGTH)
355 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
357 queryBuilder.append("uniprot_accession:")
358 .append(getDBRefId(dbRef)).append(" OR ");
359 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
361 isUniProtRefsFound = true;
363 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
366 String id = getDBRefId(dbRef).toLowerCase();
367 if (!pdbids.contains(id))
369 queryBuilder.append("pdb_id:").append(id).append(" OR ");
370 isPDBRefsFound = true;
376 seqRefs.add(getDBRefId(dbRef));
382 if (!isPDBRefsFound && !isUniProtRefsFound)
384 String seqName = seq.getName();
385 seqName = sanitizeSeqName(seqName);
386 String[] names = seqName.toLowerCase().split("\\|");
387 for (String name : names)
389 // System.out.println("Found name : " + name);
391 if (isValidSeqName(name))
397 for (String seqRef : seqRefs)
399 queryBuilder.append("text:").append(seqRef).append(" OR ");
403 int endIndex = queryBuilder.lastIndexOf(" OR ");
404 if (queryBuilder.toString().length() < 6)
408 String query = queryBuilder.toString().substring(0, endIndex);
413 * Remove the following special characters from input string +, -, &, !, (, ),
414 * {, }, [, ], ^, ", ~, *, ?, :, \
419 static String sanitizeSeqName(String seqName)
421 Objects.requireNonNull(seqName);
422 return seqName.replaceAll("\\[\\d*\\]", "")
423 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
427 * Ensures sequence ref names are not less than 3 characters and does not
428 * contain a database name
433 static boolean isValidSeqName(String seqName)
435 // System.out.println("seqName : " + seqName);
436 String ignoreList = "pdb,uniprot,swiss-prot";
437 if (seqName.length() < 3)
441 if (seqName.contains(":"))
445 seqName = seqName.toLowerCase();
446 for (String ignoredEntry : ignoreList.split(","))
448 if (seqName.contains(ignoredEntry))
456 static String getDBRefId(DBRefEntry dbRef)
458 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
463 * Filters a given list of discovered structures based on supplied argument
465 * @param fieldToFilterBy
466 * the field to filter by
468 void filterResultSet(final String fieldToFilterBy)
470 Thread filterThread = new Thread(new Runnable()
475 long startTime = System.currentTimeMillis();
476 pdbRestClient = PDBFTSRestClient.getInstance();
477 lbl_loading.setVisible(true);
478 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
479 .getStructureSummaryFields();
480 Collection<FTSData> filteredResponse = new HashSet<>();
481 HashSet<String> errors = new HashSet<>();
483 for (SequenceI seq : selectedSequences)
485 FTSRestRequest pdbRequest = new FTSRestRequest();
486 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
488 pdbRequest.setAllowEmptySeq(false);
489 pdbRequest.setResponseSize(1);
490 pdbRequest.setFieldToSearchBy("(");
491 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
492 pdbRequest.setWantedFields(wantedFields);
493 pdbRequest.setAssociatedSequence(seq);
494 pdbRequest.setFacet(true);
495 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
496 pdbRequest.setFacetPivotMinCount(1);
500 pdbRequest.setAllowEmptySeq(false);
501 pdbRequest.setResponseSize(1);
502 pdbRequest.setFieldToSearchBy("(");
503 pdbRequest.setFieldToSortBy(fieldToFilterBy,
504 !chk_invertFilter.isSelected());
505 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
506 pdbRequest.setWantedFields(wantedFields);
507 pdbRequest.setAssociatedSequence(seq);
509 FTSRestResponse resultList;
512 resultList = pdbRestClient.executeRequest(pdbRequest);
513 } catch (Exception e)
516 errors.add(e.getMessage());
519 lastPdbRequest = pdbRequest;
520 if (resultList.getSearchSummary() != null
521 && !resultList.getSearchSummary().isEmpty())
523 filteredResponse.addAll(resultList.getSearchSummary());
527 String totalTime = (System.currentTimeMillis() - startTime)
529 if (!filteredResponse.isEmpty())
531 final int filterResponseCount = filteredResponse.size();
532 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
533 reorderedStructuresSet.addAll(filteredResponse);
534 reorderedStructuresSet.addAll(discoveredStructuresSet);
535 getResultTable().setModel(FTSRestResponse
536 .getTableModel(lastPdbRequest, reorderedStructuresSet));
538 FTSRestResponse.configureTableColumn(getResultTable(),
539 wantedFields, tempUserPrefs);
540 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
541 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
542 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
543 // Update table selection model here
544 getResultTable().addRowSelectionInterval(0,
545 filterResponseCount - 1);
546 mainFrame.setTitle(MessageManager.formatMessage(
547 "label.structure_chooser_filter_time", totalTime));
551 mainFrame.setTitle(MessageManager.formatMessage(
552 "label.structure_chooser_filter_time", totalTime));
553 if (errors.size() > 0)
555 StringBuilder errorMsg = new StringBuilder();
556 for (String error : errors)
558 errorMsg.append(error).append("\n");
560 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
561 MessageManager.getString("label.pdb_web-service_error"),
562 JvOptionPane.ERROR_MESSAGE);
566 lbl_loading.setVisible(false);
568 validateSelections();
571 filterThread.start();
575 * Handles action event for btn_pdbFromFile
578 protected void pdbFromFile_actionPerformed()
580 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and StructureChooser
582 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
583 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
584 chooser.setFileView(new jalview.io.JalviewFileView());
585 chooser.setDialogTitle(
586 MessageManager.formatMessage("label.select_pdb_file_for",
587 selectedSequence.getDisplayId(false)));
588 chooser.setToolTipText(MessageManager.formatMessage(
589 "label.load_pdb_file_associate_with_sequence",
590 selectedSequence.getDisplayId(false)));
592 int value = chooser.showOpenDialog(null);
593 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
595 selectedPdbFileName = chooser.getSelectedFile().getPath();
596 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
597 validateSelections();
602 * Populates the filter combo-box options dynamically depending on discovered
605 protected void populateFilterComboBox(boolean haveData,
606 boolean cachedPDBExist)
609 * temporarily suspend the change listener behaviour
611 cmb_filterOption.removeItemListener(this);
613 cmb_filterOption.removeAllItems();
616 cmb_filterOption.addItem(new FilterOption(
617 MessageManager.getString("label.best_quality"),
618 "overall_quality", VIEWS_FILTER, false));
619 cmb_filterOption.addItem(new FilterOption(
620 MessageManager.getString("label.best_resolution"),
621 "resolution", VIEWS_FILTER, false));
622 cmb_filterOption.addItem(new FilterOption(
623 MessageManager.getString("label.most_protein_chain"),
624 "number_of_protein_chains", VIEWS_FILTER, false));
625 cmb_filterOption.addItem(new FilterOption(
626 MessageManager.getString("label.most_bound_molecules"),
627 "number_of_bound_molecules", VIEWS_FILTER, false));
628 cmb_filterOption.addItem(new FilterOption(
629 MessageManager.getString("label.most_polymer_residues"),
630 "number_of_polymer_residues", VIEWS_FILTER, true));
632 cmb_filterOption.addItem(
633 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
634 "-", VIEWS_ENTER_ID, false));
635 cmb_filterOption.addItem(
636 new FilterOption(MessageManager.getString("label.from_file"),
637 "-", VIEWS_FROM_FILE, false));
641 FilterOption cachedOption = new FilterOption(
642 MessageManager.getString("label.cached_structures"),
643 "-", VIEWS_LOCAL_PDB, false);
644 cmb_filterOption.addItem(cachedOption);
645 cmb_filterOption.setSelectedItem(cachedOption);
648 cmb_filterOption.addItemListener(this);
652 * Updates the displayed view based on the selected filter option
654 protected void updateCurrentView()
656 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
658 layout_switchableViews.show(pnl_switchableViews,
659 selectedFilterOpt.getView());
660 String filterTitle = mainFrame.getTitle();
661 mainFrame.setTitle(frameTitle);
662 chk_invertFilter.setVisible(false);
663 if (selectedFilterOpt.getView() == VIEWS_FILTER)
665 mainFrame.setTitle(filterTitle);
666 chk_invertFilter.setVisible(true);
667 filterResultSet(selectedFilterOpt.getValue());
669 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
670 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
672 mainFrame.setTitle(MessageManager
673 .getString("label.structure_chooser_manual_association"));
674 idInputAssSeqPanel.loadCmbAssSeq();
675 fileChooserAssSeqPanel.loadCmbAssSeq();
677 validateSelections();
681 * Validates user selection and enables the 'Add' and 'New View' buttons if
682 * all parameters are correct (the Add button will only be visible if there is
683 * at least one existing structure viewer open). This basically means at least
684 * one structure selected and no error messages.
686 * The 'Superpose Structures' option is enabled if either more than one
687 * structure is selected, or the 'Add' to existing view option is enabled, and
688 * disabled if the only option is to open a new view of a single structure.
691 protected void validateSelections()
693 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
695 btn_add.setEnabled(false);
696 String currentView = selectedFilterOpt.getView();
697 int selectedCount = 0;
698 if (currentView == VIEWS_FILTER)
700 selectedCount = getResultTable().getSelectedRows().length;
701 if (selectedCount > 0)
703 btn_add.setEnabled(true);
706 else if (currentView == VIEWS_LOCAL_PDB)
708 selectedCount = tbl_local_pdb.getSelectedRows().length;
709 if (selectedCount > 0)
711 btn_add.setEnabled(true);
714 else if (currentView == VIEWS_ENTER_ID)
716 validateAssociationEnterPdb();
718 else if (currentView == VIEWS_FROM_FILE)
720 validateAssociationFromFile();
723 btn_newView.setEnabled(btn_add.isEnabled());
726 * enable 'Superpose' option if more than one structure is selected,
727 * or there are view(s) available to add structure(s) to
730 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
734 * Validates inputs from the Manual PDB entry panel
736 protected void validateAssociationEnterPdb()
738 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
739 .getCmb_assSeq().getSelectedItem();
740 lbl_pdbManualFetchStatus.setIcon(errorImage);
741 lbl_pdbManualFetchStatus.setToolTipText("");
742 if (txt_search.getText().length() > 0)
744 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
745 MessageManager.formatMessage("info.no_pdb_entry_found_for",
746 txt_search.getText())));
749 if (errorWarning.length() > 0)
751 lbl_pdbManualFetchStatus.setIcon(warningImage);
752 lbl_pdbManualFetchStatus.setToolTipText(
753 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
756 if (selectedSequences.length == 1 || !assSeqOpt.getName()
757 .equalsIgnoreCase("-Select Associated Seq-"))
759 txt_search.setEnabled(true);
762 btn_add.setEnabled(true);
763 lbl_pdbManualFetchStatus.setToolTipText("");
764 lbl_pdbManualFetchStatus.setIcon(goodImage);
769 txt_search.setEnabled(false);
770 lbl_pdbManualFetchStatus.setIcon(errorImage);
775 * Validates inputs for the manual PDB file selection options
777 protected void validateAssociationFromFile()
779 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
780 .getCmb_assSeq().getSelectedItem();
781 lbl_fromFileStatus.setIcon(errorImage);
782 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
783 .getName().equalsIgnoreCase("-Select Associated Seq-")))
785 btn_pdbFromFile.setEnabled(true);
786 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
788 btn_add.setEnabled(true);
789 lbl_fromFileStatus.setIcon(goodImage);
794 btn_pdbFromFile.setEnabled(false);
795 lbl_fromFileStatus.setIcon(errorImage);
800 protected void cmbAssSeqStateChanged()
802 validateSelections();
806 * Handles the state change event for the 'filter' combo-box and 'invert'
810 protected void stateChanged(ItemEvent e)
812 if (e.getSource() instanceof JCheckBox)
818 if (e.getStateChange() == ItemEvent.SELECTED)
827 * select structures for viewing by their PDB IDs
830 * @return true if structures were found and marked as selected
832 public boolean selectStructure(String... pdbids)
834 boolean found = false;
836 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
838 String currentView = selectedFilterOpt.getView();
839 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
840 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
842 if (restable == null)
844 // can't select (enter PDB ID, or load file - need to also select which
845 // sequence to associate with)
849 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
850 for (int r = 0; r < restable.getRowCount(); r++)
852 for (int p = 0; p < pdbids.length; p++)
854 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
855 .equalsIgnoreCase(pdbids[p]))
857 restable.setRowSelectionInterval(r, r);
866 * Handles the 'New View' action
869 protected void newView_ActionPerformed()
871 targetView.setSelectedItem(null);
872 showStructures(false);
876 * Handles the 'Add to existing viewer' action
879 protected void add_ActionPerformed()
881 showStructures(false);
885 * structure viewer opened by this dialog, or null
887 private StructureViewer sViewer = null;
889 public void showStructures(boolean waitUntilFinished)
892 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
894 final int preferredHeight = pnl_filter.getHeight();
896 Runnable viewStruc = new Runnable()
901 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
903 String currentView = selectedFilterOpt.getView();
904 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
907 if (currentView == VIEWS_FILTER)
909 int pdbIdColIndex = restable.getColumn("PDB Id")
911 int refSeqColIndex = restable.getColumn("Ref Sequence")
913 int[] selectedRows = restable.getSelectedRows();
914 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
916 List<SequenceI> selectedSeqsToView = new ArrayList<>();
917 for (int row : selectedRows)
919 String pdbIdStr = restable
920 .getValueAt(row, pdbIdColIndex).toString();
921 SequenceI selectedSeq = (SequenceI) restable
922 .getValueAt(row, refSeqColIndex);
923 selectedSeqsToView.add(selectedSeq);
924 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
925 if (pdbEntry == null)
927 pdbEntry = getFindEntry(pdbIdStr,
928 selectedSeq.getAllPDBEntries());
931 if (pdbEntry == null)
933 pdbEntry = new PDBEntry();
934 pdbEntry.setId(pdbIdStr);
935 pdbEntry.setType(PDBEntry.Type.PDB);
936 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
938 pdbEntriesToView[count++] = pdbEntry;
940 SequenceI[] selectedSeqs = selectedSeqsToView
941 .toArray(new SequenceI[selectedSeqsToView.size()]);
942 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
945 else if (currentView == VIEWS_LOCAL_PDB)
947 int[] selectedRows = tbl_local_pdb.getSelectedRows();
948 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
950 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
952 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
954 List<SequenceI> selectedSeqsToView = new ArrayList<>();
955 for (int row : selectedRows)
957 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
959 pdbEntriesToView[count++] = pdbEntry;
960 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
961 .getValueAt(row, refSeqColIndex);
962 selectedSeqsToView.add(selectedSeq);
964 SequenceI[] selectedSeqs = selectedSeqsToView
965 .toArray(new SequenceI[selectedSeqsToView.size()]);
966 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
969 else if (currentView == VIEWS_ENTER_ID)
971 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
972 .getCmb_assSeq().getSelectedItem()).getSequence();
973 if (userSelectedSeq != null)
975 selectedSequence = userSelectedSeq;
977 String pdbIdStr = txt_search.getText();
978 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
979 if (pdbEntry == null)
981 pdbEntry = new PDBEntry();
982 if (pdbIdStr.split(":").length > 1)
984 pdbEntry.setId(pdbIdStr.split(":")[0]);
985 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
989 pdbEntry.setId(pdbIdStr);
991 pdbEntry.setType(PDBEntry.Type.PDB);
992 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
995 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
996 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
998 { selectedSequence });
1000 else if (currentView == VIEWS_FROM_FILE)
1002 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1003 .getCmb_assSeq().getSelectedItem()).getSequence();
1004 if (userSelectedSeq != null)
1006 selectedSequence = userSelectedSeq;
1008 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1009 .associatePdbWithSeq(selectedPdbFileName,
1010 DataSourceType.FILE, selectedSequence, true,
1013 sViewer = launchStructureViewer(
1017 { selectedSequence });
1019 SwingUtilities.invokeLater(new Runnable()
1024 closeAction(preferredHeight);
1025 mainFrame.dispose();
1030 Thread runner = new Thread(viewStruc);
1032 if (waitUntilFinished)
1034 while (sViewer == null ? runner.isAlive()
1035 : (sViewer.sview == null ? true
1036 : !sViewer.sview.hasMapping()))
1041 } catch (InterruptedException ie)
1049 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1051 Objects.requireNonNull(id);
1052 Objects.requireNonNull(pdbEntries);
1053 PDBEntry foundEntry = null;
1054 for (PDBEntry entry : pdbEntries)
1056 if (entry.getId().equalsIgnoreCase(id))
1065 * Answers a structure viewer (new or existing) configured to superimpose
1066 * added structures or not according to the user's choice
1071 StructureViewer getTargetedStructureViewer(
1072 StructureSelectionManager ssm)
1074 Object sv = targetView.getSelectedItem();
1076 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1080 * Adds PDB structures to a new or existing structure viewer
1083 * @param pdbEntriesToView
1088 private StructureViewer launchStructureViewer(
1089 StructureSelectionManager ssm,
1090 final PDBEntry[] pdbEntriesToView,
1091 final AlignmentPanel alignPanel, SequenceI[] sequences)
1093 long progressId = sequences.hashCode();
1094 setProgressBar(MessageManager
1095 .getString("status.launching_3d_structure_viewer"), progressId);
1096 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1097 boolean superimpose = chk_superpose.isSelected();
1098 theViewer.setSuperpose(superimpose);
1101 * remember user's choice of superimpose or not
1103 Cache.setProperty(AUTOSUPERIMPOSE,
1104 Boolean.valueOf(superimpose).toString());
1106 setProgressBar(null, progressId);
1107 if (SiftsSettings.isMapWithSifts())
1109 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1111 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1112 // real PDB ID. For moment, we can also safely do this if there is already
1113 // a known mapping between the PDBEntry and the sequence.
1114 for (SequenceI seq : sequences)
1116 PDBEntry pdbe = pdbEntriesToView[p++];
1117 if (pdbe != null && pdbe.getFile() != null)
1119 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1120 if (smm != null && smm.length > 0)
1122 for (StructureMapping sm : smm)
1124 if (sm.getSequence() == seq)
1131 if (seq.getPrimaryDBRefs().isEmpty())
1133 seqsWithoutSourceDBRef.add(seq);
1137 if (!seqsWithoutSourceDBRef.isEmpty())
1139 int y = seqsWithoutSourceDBRef.size();
1140 setProgressBar(MessageManager.formatMessage(
1141 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1143 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1144 .toArray(new SequenceI[y]);
1145 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1146 dbRefFetcher.fetchDBRefs(true);
1148 setProgressBar("Fetch complete.", progressId); // todo i18n
1151 if (pdbEntriesToView.length > 1)
1153 setProgressBar(MessageManager.getString(
1154 "status.fetching_3d_structures_for_selected_entries"),
1156 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1160 setProgressBar(MessageManager.formatMessage(
1161 "status.fetching_3d_structures_for",
1162 pdbEntriesToView[0].getId()),progressId);
1163 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1165 setProgressBar(null, progressId);
1166 // remember the last viewer we used...
1167 lastTargetedView = theViewer;
1172 * Populates the combo-box used in associating manually fetched structures to
1173 * a unique sequence when more than one sequence selection is made.
1176 protected void populateCmbAssociateSeqOptions(
1177 JComboBox<AssociateSeqOptions> cmb_assSeq,
1178 JLabel lbl_associateSeq)
1180 cmb_assSeq.removeAllItems();
1182 new AssociateSeqOptions("-Select Associated Seq-", null));
1183 lbl_associateSeq.setVisible(false);
1184 if (selectedSequences.length > 1)
1186 for (SequenceI seq : selectedSequences)
1188 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1193 String seqName = selectedSequence.getDisplayId(false);
1194 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1195 lbl_associateSeq.setText(seqName);
1196 lbl_associateSeq.setVisible(true);
1197 cmb_assSeq.setVisible(false);
1201 protected boolean isStructuresDiscovered()
1203 return discoveredStructuresSet != null
1204 && !discoveredStructuresSet.isEmpty();
1207 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes this.
1208 // Doing a search for "1" or "1c" is valuable?
1209 // Those work but are enormously slow.
1212 protected void txt_search_ActionPerformed()
1214 String text = txt_search.getText().trim();
1215 if (text.length() >= PDB_ID_MIN)
1222 errorWarning.setLength(0);
1223 isValidPBDEntry = false;
1224 if (text.length() > 0)
1226 String searchTerm = text.toLowerCase();
1227 searchTerm = searchTerm.split(":")[0];
1228 // System.out.println(">>>>> search term : " + searchTerm);
1229 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1230 FTSRestRequest pdbRequest = new FTSRestRequest();
1231 pdbRequest.setAllowEmptySeq(false);
1232 pdbRequest.setResponseSize(1);
1233 pdbRequest.setFieldToSearchBy("(pdb_id:");
1234 pdbRequest.setWantedFields(wantedFields);
1235 pdbRequest.setSearchTerm(searchTerm + ")");
1236 pdbRequest.setAssociatedSequence(selectedSequence);
1237 pdbRestClient = PDBFTSRestClient.getInstance();
1238 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1239 FTSRestResponse resultList;
1242 resultList = pdbRestClient.executeRequest(pdbRequest);
1243 } catch (Exception e)
1245 errorWarning.append(e.getMessage());
1249 validateSelections();
1251 if (resultList.getSearchSummary() != null
1252 && resultList.getSearchSummary().size() > 0)
1254 isValidPBDEntry = true;
1257 validateSelections();
1263 protected void tabRefresh()
1265 if (selectedSequences != null)
1267 Thread refreshThread = new Thread(new Runnable()
1272 fetchStructuresMetaData();
1274 ((FilterOption) cmb_filterOption.getSelectedItem())
1278 refreshThread.start();
1282 public class PDBEntryTableModel extends AbstractTableModel
1284 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1287 private List<CachedPDB> pdbEntries;
1289 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1291 this.pdbEntries = new ArrayList<>(pdbEntries);
1295 public String getColumnName(int columnIndex)
1297 return columns[columnIndex];
1301 public int getRowCount()
1303 return pdbEntries.size();
1307 public int getColumnCount()
1309 return columns.length;
1313 public boolean isCellEditable(int row, int column)
1319 public Object getValueAt(int rowIndex, int columnIndex)
1321 Object value = "??";
1322 CachedPDB entry = pdbEntries.get(rowIndex);
1323 switch (columnIndex)
1326 value = entry.getSequence();
1329 value = entry.getPdbEntry();
1332 value = entry.getPdbEntry().getChainCode() == null ? "_"
1333 : entry.getPdbEntry().getChainCode();
1336 value = entry.getPdbEntry().getType();
1339 value = entry.getPdbEntry().getFile();
1346 public Class<?> getColumnClass(int columnIndex)
1348 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1351 public CachedPDB getPDBEntryAt(int row)
1353 return pdbEntries.get(row);
1358 private class CachedPDB
1360 private SequenceI sequence;
1362 private PDBEntry pdbEntry;
1364 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1366 this.sequence = sequence;
1367 this.pdbEntry = pdbEntry;
1370 public SequenceI getSequence()
1375 public PDBEntry getPdbEntry()
1382 private IProgressIndicator progressBar;
1385 public void setProgressBar(String message, long id)
1387 progressBar.setProgressBar(message, id);
1391 public void registerHandler(long id, IProgressIndicatorHandler handler)
1393 progressBar.registerHandler(id, handler);
1397 public boolean operationInProgress()
1399 return progressBar.operationInProgress();
1402 public JalviewStructureDisplayI getOpenedStructureViewer()
1404 return sViewer == null ? null : sViewer.sview;