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 pdbRestCleint;
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 pdbRestCleint = 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 = pdbRestCleint.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<>();
326 if (seq.getAllPDBEntries() != null
327 && queryBuilder.length() < MAX_QLENGTH)
329 for (PDBEntry entry : seq.getAllPDBEntries())
331 if (isValidSeqName(entry.getId()))
333 queryBuilder.append("pdb_id:").append(entry.getId().toLowerCase())
335 isPDBRefsFound = true;
340 if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
342 for (DBRefEntry dbRef : seq.getDBRefs())
344 if (isValidSeqName(getDBRefId(dbRef))
345 && queryBuilder.length() < MAX_QLENGTH)
347 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
349 queryBuilder.append("uniprot_accession:")
350 .append(getDBRefId(dbRef)).append(" OR ");
351 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
353 isUniProtRefsFound = true;
355 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
358 queryBuilder.append("pdb_id:")
359 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
360 isPDBRefsFound = true;
364 seqRefs.add(getDBRefId(dbRef));
370 if (!isPDBRefsFound && !isUniProtRefsFound)
372 String seqName = seq.getName();
373 seqName = sanitizeSeqName(seqName);
374 String[] names = seqName.toLowerCase().split("\\|");
375 for (String name : names)
377 // System.out.println("Found name : " + name);
379 if (isValidSeqName(name))
385 for (String seqRef : seqRefs)
387 queryBuilder.append("text:").append(seqRef).append(" OR ");
391 int endIndex = queryBuilder.lastIndexOf(" OR ");
392 if (queryBuilder.toString().length() < 6)
396 String query = queryBuilder.toString().substring(0, endIndex);
401 * Remove the following special characters from input string +, -, &, !, (, ),
402 * {, }, [, ], ^, ", ~, *, ?, :, \
407 static String sanitizeSeqName(String seqName)
409 Objects.requireNonNull(seqName);
410 return seqName.replaceAll("\\[\\d*\\]", "")
411 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
415 * Ensures sequence ref names are not less than 3 characters and does not
416 * contain a database name
421 static boolean isValidSeqName(String seqName)
423 // System.out.println("seqName : " + seqName);
424 String ignoreList = "pdb,uniprot,swiss-prot";
425 if (seqName.length() < 3)
429 if (seqName.contains(":"))
433 seqName = seqName.toLowerCase();
434 for (String ignoredEntry : ignoreList.split(","))
436 if (seqName.contains(ignoredEntry))
444 static String getDBRefId(DBRefEntry dbRef)
446 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
451 * Filters a given list of discovered structures based on supplied argument
453 * @param fieldToFilterBy
454 * the field to filter by
456 void filterResultSet(final String fieldToFilterBy)
458 Thread filterThread = new Thread(new Runnable()
463 long startTime = System.currentTimeMillis();
464 pdbRestCleint = PDBFTSRestClient.getInstance();
465 lbl_loading.setVisible(true);
466 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
467 .getStructureSummaryFields();
468 Collection<FTSData> filteredResponse = new HashSet<>();
469 HashSet<String> errors = new HashSet<>();
471 for (SequenceI seq : selectedSequences)
473 FTSRestRequest pdbRequest = new FTSRestRequest();
474 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
476 pdbRequest.setAllowEmptySeq(false);
477 pdbRequest.setResponseSize(1);
478 pdbRequest.setFieldToSearchBy("(");
479 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
480 pdbRequest.setWantedFields(wantedFields);
481 pdbRequest.setAssociatedSequence(seq);
482 pdbRequest.setFacet(true);
483 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
484 pdbRequest.setFacetPivotMinCount(1);
488 pdbRequest.setAllowEmptySeq(false);
489 pdbRequest.setResponseSize(1);
490 pdbRequest.setFieldToSearchBy("(");
491 pdbRequest.setFieldToSortBy(fieldToFilterBy,
492 !chk_invertFilter.isSelected());
493 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
494 pdbRequest.setWantedFields(wantedFields);
495 pdbRequest.setAssociatedSequence(seq);
497 FTSRestResponse resultList;
500 resultList = pdbRestCleint.executeRequest(pdbRequest);
501 } catch (Exception e)
504 errors.add(e.getMessage());
507 lastPdbRequest = pdbRequest;
508 if (resultList.getSearchSummary() != null
509 && !resultList.getSearchSummary().isEmpty())
511 filteredResponse.addAll(resultList.getSearchSummary());
515 String totalTime = (System.currentTimeMillis() - startTime)
517 if (!filteredResponse.isEmpty())
519 final int filterResponseCount = filteredResponse.size();
520 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
521 reorderedStructuresSet.addAll(filteredResponse);
522 reorderedStructuresSet.addAll(discoveredStructuresSet);
523 getResultTable().setModel(FTSRestResponse
524 .getTableModel(lastPdbRequest, reorderedStructuresSet));
526 FTSRestResponse.configureTableColumn(getResultTable(),
527 wantedFields, tempUserPrefs);
528 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
529 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
530 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
531 // Update table selection model here
532 getResultTable().addRowSelectionInterval(0,
533 filterResponseCount - 1);
534 mainFrame.setTitle(MessageManager.formatMessage(
535 "label.structure_chooser_filter_time", totalTime));
539 mainFrame.setTitle(MessageManager.formatMessage(
540 "label.structure_chooser_filter_time", totalTime));
541 if (errors.size() > 0)
543 StringBuilder errorMsg = new StringBuilder();
544 for (String error : errors)
546 errorMsg.append(error).append("\n");
548 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
549 MessageManager.getString("label.pdb_web-service_error"),
550 JvOptionPane.ERROR_MESSAGE);
554 lbl_loading.setVisible(false);
556 validateSelections();
559 filterThread.start();
563 * Handles action event for btn_pdbFromFile
566 protected void pdbFromFile_actionPerformed()
568 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and StructureChooser
570 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
571 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
572 chooser.setFileView(new jalview.io.JalviewFileView());
573 chooser.setDialogTitle(
574 MessageManager.formatMessage("label.select_pdb_file_for",
575 selectedSequence.getDisplayId(false)));
576 chooser.setToolTipText(MessageManager.formatMessage(
577 "label.load_pdb_file_associate_with_sequence",
578 selectedSequence.getDisplayId(false)));
580 int value = chooser.showOpenDialog(null);
581 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
583 selectedPdbFileName = chooser.getSelectedFile().getPath();
584 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
585 validateSelections();
590 * Populates the filter combo-box options dynamically depending on discovered
593 protected void populateFilterComboBox(boolean haveData,
594 boolean cachedPDBExist)
597 * temporarily suspend the change listener behaviour
599 cmb_filterOption.removeItemListener(this);
601 cmb_filterOption.removeAllItems();
604 cmb_filterOption.addItem(new FilterOption(
605 MessageManager.getString("label.best_quality"),
606 "overall_quality", VIEWS_FILTER, false));
607 cmb_filterOption.addItem(new FilterOption(
608 MessageManager.getString("label.best_resolution"),
609 "resolution", VIEWS_FILTER, false));
610 cmb_filterOption.addItem(new FilterOption(
611 MessageManager.getString("label.most_protein_chain"),
612 "number_of_protein_chains", VIEWS_FILTER, false));
613 cmb_filterOption.addItem(new FilterOption(
614 MessageManager.getString("label.most_bound_molecules"),
615 "number_of_bound_molecules", VIEWS_FILTER, false));
616 cmb_filterOption.addItem(new FilterOption(
617 MessageManager.getString("label.most_polymer_residues"),
618 "number_of_polymer_residues", VIEWS_FILTER, true));
620 cmb_filterOption.addItem(
621 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
622 "-", VIEWS_ENTER_ID, false));
623 cmb_filterOption.addItem(
624 new FilterOption(MessageManager.getString("label.from_file"),
625 "-", VIEWS_FROM_FILE, false));
629 FilterOption cachedOption = new FilterOption(
630 MessageManager.getString("label.cached_structures"),
631 "-", VIEWS_LOCAL_PDB, false);
632 cmb_filterOption.addItem(cachedOption);
633 cmb_filterOption.setSelectedItem(cachedOption);
636 cmb_filterOption.addItemListener(this);
640 * Updates the displayed view based on the selected filter option
642 protected void updateCurrentView()
644 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
646 layout_switchableViews.show(pnl_switchableViews,
647 selectedFilterOpt.getView());
648 String filterTitle = mainFrame.getTitle();
649 mainFrame.setTitle(frameTitle);
650 chk_invertFilter.setVisible(false);
651 if (selectedFilterOpt.getView() == VIEWS_FILTER)
653 mainFrame.setTitle(filterTitle);
654 chk_invertFilter.setVisible(true);
655 filterResultSet(selectedFilterOpt.getValue());
657 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
658 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
660 mainFrame.setTitle(MessageManager
661 .getString("label.structure_chooser_manual_association"));
662 idInputAssSeqPanel.loadCmbAssSeq();
663 fileChooserAssSeqPanel.loadCmbAssSeq();
665 validateSelections();
669 * Validates user selection and enables the 'Add' and 'New View' buttons if
670 * all parameters are correct (the Add button will only be visible if there is
671 * at least one existing structure viewer open). This basically means at least
672 * one structure selected and no error messages.
674 * The 'Superpose Structures' option is enabled if either more than one
675 * structure is selected, or the 'Add' to existing view option is enabled, and
676 * disabled if the only option is to open a new view of a single structure.
679 protected void validateSelections()
681 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
683 btn_add.setEnabled(false);
684 String currentView = selectedFilterOpt.getView();
685 int selectedCount = 0;
686 if (currentView == VIEWS_FILTER)
688 selectedCount = getResultTable().getSelectedRows().length;
689 if (selectedCount > 0)
691 btn_add.setEnabled(true);
694 else if (currentView == VIEWS_LOCAL_PDB)
696 selectedCount = tbl_local_pdb.getSelectedRows().length;
697 if (selectedCount > 0)
699 btn_add.setEnabled(true);
702 else if (currentView == VIEWS_ENTER_ID)
704 validateAssociationEnterPdb();
706 else if (currentView == VIEWS_FROM_FILE)
708 validateAssociationFromFile();
711 btn_newView.setEnabled(btn_add.isEnabled());
714 * enable 'Superpose' option if more than one structure is selected,
715 * or there are view(s) available to add structure(s) to
718 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
722 * Validates inputs from the Manual PDB entry panel
724 protected void validateAssociationEnterPdb()
726 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
727 .getCmb_assSeq().getSelectedItem();
728 lbl_pdbManualFetchStatus.setIcon(errorImage);
729 lbl_pdbManualFetchStatus.setToolTipText("");
730 if (txt_search.getText().length() > 0)
732 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
733 MessageManager.formatMessage("info.no_pdb_entry_found_for",
734 txt_search.getText())));
737 if (errorWarning.length() > 0)
739 lbl_pdbManualFetchStatus.setIcon(warningImage);
740 lbl_pdbManualFetchStatus.setToolTipText(
741 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
744 if (selectedSequences.length == 1 || !assSeqOpt.getName()
745 .equalsIgnoreCase("-Select Associated Seq-"))
747 txt_search.setEnabled(true);
750 btn_add.setEnabled(true);
751 lbl_pdbManualFetchStatus.setToolTipText("");
752 lbl_pdbManualFetchStatus.setIcon(goodImage);
757 txt_search.setEnabled(false);
758 lbl_pdbManualFetchStatus.setIcon(errorImage);
763 * Validates inputs for the manual PDB file selection options
765 protected void validateAssociationFromFile()
767 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
768 .getCmb_assSeq().getSelectedItem();
769 lbl_fromFileStatus.setIcon(errorImage);
770 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
771 .getName().equalsIgnoreCase("-Select Associated Seq-")))
773 btn_pdbFromFile.setEnabled(true);
774 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
776 btn_add.setEnabled(true);
777 lbl_fromFileStatus.setIcon(goodImage);
782 btn_pdbFromFile.setEnabled(false);
783 lbl_fromFileStatus.setIcon(errorImage);
788 protected void cmbAssSeqStateChanged()
790 validateSelections();
794 * Handles the state change event for the 'filter' combo-box and 'invert'
798 protected void stateChanged(ItemEvent e)
800 if (e.getSource() instanceof JCheckBox)
806 if (e.getStateChange() == ItemEvent.SELECTED)
815 * select structures for viewing by their PDB IDs
818 * @return true if structures were found and marked as selected
820 public boolean selectStructure(String... pdbids)
822 boolean found = false;
824 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
826 String currentView = selectedFilterOpt.getView();
827 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
828 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
830 if (restable == null)
832 // can't select (enter PDB ID, or load file - need to also select which
833 // sequence to associate with)
837 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
838 for (int r = 0; r < restable.getRowCount(); r++)
840 for (int p = 0; p < pdbids.length; p++)
842 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
843 .equalsIgnoreCase(pdbids[p]))
845 restable.setRowSelectionInterval(r, r);
854 * Handles the 'New View' action
857 protected void newView_ActionPerformed()
859 targetView.setSelectedItem(null);
860 showStructures(false);
864 * Handles the 'Add to existing viewer' action
867 protected void add_ActionPerformed()
869 showStructures(false);
873 * structure viewer opened by this dialog, or null
875 private StructureViewer sViewer = null;
877 public void showStructures(boolean waitUntilFinished)
880 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
882 final int preferredHeight = pnl_filter.getHeight();
884 Runnable viewStruc = new Runnable()
889 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
891 String currentView = selectedFilterOpt.getView();
892 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
895 if (currentView == VIEWS_FILTER)
897 int pdbIdColIndex = restable.getColumn("PDB Id")
899 int refSeqColIndex = restable.getColumn("Ref Sequence")
901 int[] selectedRows = restable.getSelectedRows();
902 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
904 List<SequenceI> selectedSeqsToView = new ArrayList<>();
905 for (int row : selectedRows)
907 String pdbIdStr = restable
908 .getValueAt(row, pdbIdColIndex).toString();
909 SequenceI selectedSeq = (SequenceI) restable
910 .getValueAt(row, refSeqColIndex);
911 selectedSeqsToView.add(selectedSeq);
912 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
913 if (pdbEntry == null)
915 pdbEntry = getFindEntry(pdbIdStr,
916 selectedSeq.getAllPDBEntries());
919 if (pdbEntry == null)
921 pdbEntry = new PDBEntry();
922 pdbEntry.setId(pdbIdStr);
923 pdbEntry.setType(PDBEntry.Type.PDB);
924 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
926 pdbEntriesToView[count++] = pdbEntry;
928 SequenceI[] selectedSeqs = selectedSeqsToView
929 .toArray(new SequenceI[selectedSeqsToView.size()]);
930 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
933 else if (currentView == VIEWS_LOCAL_PDB)
935 int[] selectedRows = tbl_local_pdb.getSelectedRows();
936 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
938 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
940 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
942 List<SequenceI> selectedSeqsToView = new ArrayList<>();
943 for (int row : selectedRows)
945 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
947 pdbEntriesToView[count++] = pdbEntry;
948 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
949 .getValueAt(row, refSeqColIndex);
950 selectedSeqsToView.add(selectedSeq);
952 SequenceI[] selectedSeqs = selectedSeqsToView
953 .toArray(new SequenceI[selectedSeqsToView.size()]);
954 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
957 else if (currentView == VIEWS_ENTER_ID)
959 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
960 .getCmb_assSeq().getSelectedItem()).getSequence();
961 if (userSelectedSeq != null)
963 selectedSequence = userSelectedSeq;
965 String pdbIdStr = txt_search.getText();
966 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
967 if (pdbEntry == null)
969 pdbEntry = new PDBEntry();
970 if (pdbIdStr.split(":").length > 1)
972 pdbEntry.setId(pdbIdStr.split(":")[0]);
973 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
977 pdbEntry.setId(pdbIdStr);
979 pdbEntry.setType(PDBEntry.Type.PDB);
980 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
983 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
984 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
986 { selectedSequence });
988 else if (currentView == VIEWS_FROM_FILE)
990 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
991 .getCmb_assSeq().getSelectedItem()).getSequence();
992 if (userSelectedSeq != null)
994 selectedSequence = userSelectedSeq;
996 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
997 .associatePdbWithSeq(selectedPdbFileName,
998 DataSourceType.FILE, selectedSequence, true,
1001 sViewer = launchStructureViewer(
1005 { selectedSequence });
1007 SwingUtilities.invokeLater(new Runnable()
1012 closeAction(preferredHeight);
1013 mainFrame.dispose();
1018 Thread runner = new Thread(viewStruc);
1020 if (waitUntilFinished)
1022 while (sViewer == null ? runner.isAlive()
1023 : (sViewer.sview == null ? true
1024 : !sViewer.sview.hasMapping()))
1029 } catch (InterruptedException ie)
1037 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1039 Objects.requireNonNull(id);
1040 Objects.requireNonNull(pdbEntries);
1041 PDBEntry foundEntry = null;
1042 for (PDBEntry entry : pdbEntries)
1044 if (entry.getId().equalsIgnoreCase(id))
1053 * Answers a structure viewer (new or existing) configured to superimpose
1054 * added structures or not according to the user's choice
1059 StructureViewer getTargetedStructureViewer(
1060 StructureSelectionManager ssm)
1062 Object sv = targetView.getSelectedItem();
1064 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1068 * Adds PDB structures to a new or existing structure viewer
1071 * @param pdbEntriesToView
1076 private StructureViewer launchStructureViewer(
1077 StructureSelectionManager ssm,
1078 final PDBEntry[] pdbEntriesToView,
1079 final AlignmentPanel alignPanel, SequenceI[] sequences)
1081 long progressId = sequences.hashCode();
1082 setProgressBar(MessageManager
1083 .getString("status.launching_3d_structure_viewer"), progressId);
1084 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1085 boolean superimpose = chk_superpose.isSelected();
1086 theViewer.setSuperpose(superimpose);
1089 * remember user's choice of superimpose or not
1091 Cache.setProperty(AUTOSUPERIMPOSE,
1092 Boolean.valueOf(superimpose).toString());
1094 setProgressBar(null, progressId);
1095 if (SiftsSettings.isMapWithSifts())
1097 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1099 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1100 // real PDB ID. For moment, we can also safely do this if there is already
1101 // a known mapping between the PDBEntry and the sequence.
1102 for (SequenceI seq : sequences)
1104 PDBEntry pdbe = pdbEntriesToView[p++];
1105 if (pdbe != null && pdbe.getFile() != null)
1107 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1108 if (smm != null && smm.length > 0)
1110 for (StructureMapping sm : smm)
1112 if (sm.getSequence() == seq)
1119 if (seq.getPrimaryDBRefs().isEmpty())
1121 seqsWithoutSourceDBRef.add(seq);
1125 if (!seqsWithoutSourceDBRef.isEmpty())
1127 int y = seqsWithoutSourceDBRef.size();
1128 setProgressBar(MessageManager.formatMessage(
1129 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1131 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1132 .toArray(new SequenceI[y]);
1133 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1134 dbRefFetcher.fetchDBRefs(true);
1136 setProgressBar("Fetch complete.", progressId); // todo i18n
1139 if (pdbEntriesToView.length > 1)
1141 setProgressBar(MessageManager.getString(
1142 "status.fetching_3d_structures_for_selected_entries"),
1144 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1148 setProgressBar(MessageManager.formatMessage(
1149 "status.fetching_3d_structures_for",
1150 pdbEntriesToView[0].getId()),progressId);
1151 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1153 setProgressBar(null, progressId);
1154 // remember the last viewer we used...
1155 lastTargetedView = theViewer;
1160 * Populates the combo-box used in associating manually fetched structures to
1161 * a unique sequence when more than one sequence selection is made.
1164 protected void populateCmbAssociateSeqOptions(
1165 JComboBox<AssociateSeqOptions> cmb_assSeq,
1166 JLabel lbl_associateSeq)
1168 cmb_assSeq.removeAllItems();
1170 new AssociateSeqOptions("-Select Associated Seq-", null));
1171 lbl_associateSeq.setVisible(false);
1172 if (selectedSequences.length > 1)
1174 for (SequenceI seq : selectedSequences)
1176 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1181 String seqName = selectedSequence.getDisplayId(false);
1182 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1183 lbl_associateSeq.setText(seqName);
1184 lbl_associateSeq.setVisible(true);
1185 cmb_assSeq.setVisible(false);
1189 protected boolean isStructuresDiscovered()
1191 return discoveredStructuresSet != null
1192 && !discoveredStructuresSet.isEmpty();
1196 protected void txt_search_ActionPerformed()
1203 errorWarning.setLength(0);
1204 isValidPBDEntry = false;
1205 if (txt_search.getText().length() > 0)
1207 String searchTerm = txt_search.getText().toLowerCase();
1208 searchTerm = searchTerm.split(":")[0];
1209 // System.out.println(">>>>> search term : " + searchTerm);
1210 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1211 FTSRestRequest pdbRequest = new FTSRestRequest();
1212 pdbRequest.setAllowEmptySeq(false);
1213 pdbRequest.setResponseSize(1);
1214 pdbRequest.setFieldToSearchBy("(pdb_id:");
1215 pdbRequest.setWantedFields(wantedFields);
1216 pdbRequest.setSearchTerm(searchTerm + ")");
1217 pdbRequest.setAssociatedSequence(selectedSequence);
1218 pdbRestCleint = PDBFTSRestClient.getInstance();
1219 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1220 FTSRestResponse resultList;
1223 resultList = pdbRestCleint.executeRequest(pdbRequest);
1224 } catch (Exception e)
1226 errorWarning.append(e.getMessage());
1230 validateSelections();
1232 if (resultList.getSearchSummary() != null
1233 && resultList.getSearchSummary().size() > 0)
1235 isValidPBDEntry = true;
1238 validateSelections();
1244 protected void tabRefresh()
1246 if (selectedSequences != null)
1248 Thread refreshThread = new Thread(new Runnable()
1253 fetchStructuresMetaData();
1255 ((FilterOption) cmb_filterOption.getSelectedItem())
1259 refreshThread.start();
1263 public class PDBEntryTableModel extends AbstractTableModel
1265 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1268 private List<CachedPDB> pdbEntries;
1270 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1272 this.pdbEntries = new ArrayList<>(pdbEntries);
1276 public String getColumnName(int columnIndex)
1278 return columns[columnIndex];
1282 public int getRowCount()
1284 return pdbEntries.size();
1288 public int getColumnCount()
1290 return columns.length;
1294 public boolean isCellEditable(int row, int column)
1300 public Object getValueAt(int rowIndex, int columnIndex)
1302 Object value = "??";
1303 CachedPDB entry = pdbEntries.get(rowIndex);
1304 switch (columnIndex)
1307 value = entry.getSequence();
1310 value = entry.getPdbEntry();
1313 value = entry.getPdbEntry().getChainCode() == null ? "_"
1314 : entry.getPdbEntry().getChainCode();
1317 value = entry.getPdbEntry().getType();
1320 value = entry.getPdbEntry().getFile();
1327 public Class<?> getColumnClass(int columnIndex)
1329 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1332 public CachedPDB getPDBEntryAt(int row)
1334 return pdbEntries.get(row);
1339 private class CachedPDB
1341 private SequenceI sequence;
1343 private PDBEntry pdbEntry;
1345 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1347 this.sequence = sequence;
1348 this.pdbEntry = pdbEntry;
1351 public SequenceI getSequence()
1356 public PDBEntry getPdbEntry()
1363 private IProgressIndicator progressBar;
1366 public void setProgressBar(String message, long id)
1368 progressBar.setProgressBar(message, id);
1372 public void registerHandler(long id, IProgressIndicatorHandler handler)
1374 progressBar.registerHandler(id, handler);
1378 public boolean operationInProgress()
1380 return progressBar.operationInProgress();
1383 public JalviewStructureDisplayI getOpenedStructureViewer()
1385 return sViewer == null ? null : sViewer.sview;