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<>();
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 if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
348 for (DBRefEntry dbRef : seq.getDBRefs())
350 if (isValidSeqName(getDBRefId(dbRef))
351 && queryBuilder.length() < MAX_QLENGTH)
353 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
355 queryBuilder.append("uniprot_accession:")
356 .append(getDBRefId(dbRef)).append(" OR ");
357 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
359 isUniProtRefsFound = true;
361 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
364 String id = getDBRefId(dbRef).toLowerCase();
365 if (!pdbids.contains(id))
367 queryBuilder.append("pdb_id:").append(id).append(" OR ");
368 isPDBRefsFound = true;
374 seqRefs.add(getDBRefId(dbRef));
380 if (!isPDBRefsFound && !isUniProtRefsFound)
382 String seqName = seq.getName();
383 seqName = sanitizeSeqName(seqName);
384 String[] names = seqName.toLowerCase().split("\\|");
385 for (String name : names)
387 // System.out.println("Found name : " + name);
389 if (isValidSeqName(name))
395 for (String seqRef : seqRefs)
397 queryBuilder.append("text:").append(seqRef).append(" OR ");
401 int endIndex = queryBuilder.lastIndexOf(" OR ");
402 if (queryBuilder.toString().length() < 6)
406 String query = queryBuilder.toString().substring(0, endIndex);
411 * Remove the following special characters from input string +, -, &, !, (, ),
412 * {, }, [, ], ^, ", ~, *, ?, :, \
417 static String sanitizeSeqName(String seqName)
419 Objects.requireNonNull(seqName);
420 return seqName.replaceAll("\\[\\d*\\]", "")
421 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
425 * Ensures sequence ref names are not less than 3 characters and does not
426 * contain a database name
431 static boolean isValidSeqName(String seqName)
433 // System.out.println("seqName : " + seqName);
434 String ignoreList = "pdb,uniprot,swiss-prot";
435 if (seqName.length() < 3)
439 if (seqName.contains(":"))
443 seqName = seqName.toLowerCase();
444 for (String ignoredEntry : ignoreList.split(","))
446 if (seqName.contains(ignoredEntry))
454 static String getDBRefId(DBRefEntry dbRef)
456 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
461 * Filters a given list of discovered structures based on supplied argument
463 * @param fieldToFilterBy
464 * the field to filter by
466 void filterResultSet(final String fieldToFilterBy)
468 Thread filterThread = new Thread(new Runnable()
473 long startTime = System.currentTimeMillis();
474 pdbRestCleint = PDBFTSRestClient.getInstance();
475 lbl_loading.setVisible(true);
476 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
477 .getStructureSummaryFields();
478 Collection<FTSData> filteredResponse = new HashSet<>();
479 HashSet<String> errors = new HashSet<>();
481 for (SequenceI seq : selectedSequences)
483 FTSRestRequest pdbRequest = new FTSRestRequest();
484 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
486 pdbRequest.setAllowEmptySeq(false);
487 pdbRequest.setResponseSize(1);
488 pdbRequest.setFieldToSearchBy("(");
489 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
490 pdbRequest.setWantedFields(wantedFields);
491 pdbRequest.setAssociatedSequence(seq);
492 pdbRequest.setFacet(true);
493 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
494 pdbRequest.setFacetPivotMinCount(1);
498 pdbRequest.setAllowEmptySeq(false);
499 pdbRequest.setResponseSize(1);
500 pdbRequest.setFieldToSearchBy("(");
501 pdbRequest.setFieldToSortBy(fieldToFilterBy,
502 !chk_invertFilter.isSelected());
503 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
504 pdbRequest.setWantedFields(wantedFields);
505 pdbRequest.setAssociatedSequence(seq);
507 FTSRestResponse resultList;
510 resultList = pdbRestCleint.executeRequest(pdbRequest);
511 } catch (Exception e)
514 errors.add(e.getMessage());
517 lastPdbRequest = pdbRequest;
518 if (resultList.getSearchSummary() != null
519 && !resultList.getSearchSummary().isEmpty())
521 filteredResponse.addAll(resultList.getSearchSummary());
525 String totalTime = (System.currentTimeMillis() - startTime)
527 if (!filteredResponse.isEmpty())
529 final int filterResponseCount = filteredResponse.size();
530 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
531 reorderedStructuresSet.addAll(filteredResponse);
532 reorderedStructuresSet.addAll(discoveredStructuresSet);
533 getResultTable().setModel(FTSRestResponse
534 .getTableModel(lastPdbRequest, reorderedStructuresSet));
536 FTSRestResponse.configureTableColumn(getResultTable(),
537 wantedFields, tempUserPrefs);
538 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
539 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
540 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
541 // Update table selection model here
542 getResultTable().addRowSelectionInterval(0,
543 filterResponseCount - 1);
544 mainFrame.setTitle(MessageManager.formatMessage(
545 "label.structure_chooser_filter_time", totalTime));
549 mainFrame.setTitle(MessageManager.formatMessage(
550 "label.structure_chooser_filter_time", totalTime));
551 if (errors.size() > 0)
553 StringBuilder errorMsg = new StringBuilder();
554 for (String error : errors)
556 errorMsg.append(error).append("\n");
558 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
559 MessageManager.getString("label.pdb_web-service_error"),
560 JvOptionPane.ERROR_MESSAGE);
564 lbl_loading.setVisible(false);
566 validateSelections();
569 filterThread.start();
573 * Handles action event for btn_pdbFromFile
576 protected void pdbFromFile_actionPerformed()
578 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
579 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
580 chooser.setFileView(new jalview.io.JalviewFileView());
581 chooser.setDialogTitle(
582 MessageManager.formatMessage("label.select_pdb_file_for",
583 selectedSequence.getDisplayId(false)));
584 chooser.setToolTipText(MessageManager.formatMessage(
585 "label.load_pdb_file_associate_with_sequence",
586 selectedSequence.getDisplayId(false)));
588 int value = chooser.showOpenDialog(null);
589 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
591 selectedPdbFileName = chooser.getSelectedFile().getPath();
592 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
593 validateSelections();
598 * Populates the filter combo-box options dynamically depending on discovered
601 protected void populateFilterComboBox(boolean haveData,
602 boolean cachedPDBExist)
605 * temporarily suspend the change listener behaviour
607 cmb_filterOption.removeItemListener(this);
609 cmb_filterOption.removeAllItems();
612 cmb_filterOption.addItem(new FilterOption(
613 MessageManager.getString("label.best_quality"),
614 "overall_quality", VIEWS_FILTER, false));
615 cmb_filterOption.addItem(new FilterOption(
616 MessageManager.getString("label.best_resolution"),
617 "resolution", VIEWS_FILTER, false));
618 cmb_filterOption.addItem(new FilterOption(
619 MessageManager.getString("label.most_protein_chain"),
620 "number_of_protein_chains", VIEWS_FILTER, false));
621 cmb_filterOption.addItem(new FilterOption(
622 MessageManager.getString("label.most_bound_molecules"),
623 "number_of_bound_molecules", VIEWS_FILTER, false));
624 cmb_filterOption.addItem(new FilterOption(
625 MessageManager.getString("label.most_polymer_residues"),
626 "number_of_polymer_residues", VIEWS_FILTER, true));
628 cmb_filterOption.addItem(
629 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
630 "-", VIEWS_ENTER_ID, false));
631 cmb_filterOption.addItem(
632 new FilterOption(MessageManager.getString("label.from_file"),
633 "-", VIEWS_FROM_FILE, false));
637 FilterOption cachedOption = new FilterOption(
638 MessageManager.getString("label.cached_structures"),
639 "-", VIEWS_LOCAL_PDB, false);
640 cmb_filterOption.addItem(cachedOption);
641 cmb_filterOption.setSelectedItem(cachedOption);
644 cmb_filterOption.addItemListener(this);
648 * Updates the displayed view based on the selected filter option
650 protected void updateCurrentView()
652 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
654 layout_switchableViews.show(pnl_switchableViews,
655 selectedFilterOpt.getView());
656 String filterTitle = mainFrame.getTitle();
657 mainFrame.setTitle(frameTitle);
658 chk_invertFilter.setVisible(false);
659 if (selectedFilterOpt.getView() == VIEWS_FILTER)
661 mainFrame.setTitle(filterTitle);
662 chk_invertFilter.setVisible(true);
663 filterResultSet(selectedFilterOpt.getValue());
665 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
666 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
668 mainFrame.setTitle(MessageManager
669 .getString("label.structure_chooser_manual_association"));
670 idInputAssSeqPanel.loadCmbAssSeq();
671 fileChooserAssSeqPanel.loadCmbAssSeq();
673 validateSelections();
677 * Validates user selection and enables the 'Add' and 'New View' buttons if
678 * all parameters are correct (the Add button will only be visible if there is
679 * at least one existing structure viewer open). This basically means at least
680 * one structure selected and no error messages.
682 * The 'Superpose Structures' option is enabled if either more than one
683 * structure is selected, or the 'Add' to existing view option is enabled, and
684 * disabled if the only option is to open a new view of a single structure.
687 protected void validateSelections()
689 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
691 btn_add.setEnabled(false);
692 String currentView = selectedFilterOpt.getView();
693 int selectedCount = 0;
694 if (currentView == VIEWS_FILTER)
696 selectedCount = getResultTable().getSelectedRows().length;
697 if (selectedCount > 0)
699 btn_add.setEnabled(true);
702 else if (currentView == VIEWS_LOCAL_PDB)
704 selectedCount = tbl_local_pdb.getSelectedRows().length;
705 if (selectedCount > 0)
707 btn_add.setEnabled(true);
710 else if (currentView == VIEWS_ENTER_ID)
712 validateAssociationEnterPdb();
714 else if (currentView == VIEWS_FROM_FILE)
716 validateAssociationFromFile();
719 btn_newView.setEnabled(btn_add.isEnabled());
722 * enable 'Superpose' option if more than one structure is selected,
723 * or there are view(s) available to add structure(s) to
726 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
730 * Validates inputs from the Manual PDB entry panel
732 protected void validateAssociationEnterPdb()
734 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
735 .getCmb_assSeq().getSelectedItem();
736 lbl_pdbManualFetchStatus.setIcon(errorImage);
737 lbl_pdbManualFetchStatus.setToolTipText("");
738 if (txt_search.getText().length() > 0)
740 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
741 MessageManager.formatMessage("info.no_pdb_entry_found_for",
742 txt_search.getText())));
745 if (errorWarning.length() > 0)
747 lbl_pdbManualFetchStatus.setIcon(warningImage);
748 lbl_pdbManualFetchStatus.setToolTipText(
749 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
752 if (selectedSequences.length == 1 || !assSeqOpt.getName()
753 .equalsIgnoreCase("-Select Associated Seq-"))
755 txt_search.setEnabled(true);
758 btn_add.setEnabled(true);
759 lbl_pdbManualFetchStatus.setToolTipText("");
760 lbl_pdbManualFetchStatus.setIcon(goodImage);
765 txt_search.setEnabled(false);
766 lbl_pdbManualFetchStatus.setIcon(errorImage);
771 * Validates inputs for the manual PDB file selection options
773 protected void validateAssociationFromFile()
775 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
776 .getCmb_assSeq().getSelectedItem();
777 lbl_fromFileStatus.setIcon(errorImage);
778 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
779 .getName().equalsIgnoreCase("-Select Associated Seq-")))
781 btn_pdbFromFile.setEnabled(true);
782 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
784 btn_add.setEnabled(true);
785 lbl_fromFileStatus.setIcon(goodImage);
790 btn_pdbFromFile.setEnabled(false);
791 lbl_fromFileStatus.setIcon(errorImage);
796 protected void cmbAssSeqStateChanged()
798 validateSelections();
802 * Handles the state change event for the 'filter' combo-box and 'invert'
806 protected void stateChanged(ItemEvent e)
808 if (e.getSource() instanceof JCheckBox)
814 if (e.getStateChange() == ItemEvent.SELECTED)
823 * select structures for viewing by their PDB IDs
826 * @return true if structures were found and marked as selected
828 public boolean selectStructure(String... pdbids)
830 boolean found = false;
832 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
834 String currentView = selectedFilterOpt.getView();
835 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
836 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
838 if (restable == null)
840 // can't select (enter PDB ID, or load file - need to also select which
841 // sequence to associate with)
845 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
846 for (int r = 0; r < restable.getRowCount(); r++)
848 for (int p = 0; p < pdbids.length; p++)
850 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
851 .equalsIgnoreCase(pdbids[p]))
853 restable.setRowSelectionInterval(r, r);
862 * Handles the 'New View' action
865 protected void newView_ActionPerformed()
867 targetView.setSelectedItem(null);
868 showStructures(false);
872 * Handles the 'Add to existing viewer' action
875 protected void add_ActionPerformed()
877 showStructures(false);
881 * structure viewer opened by this dialog, or null
883 private StructureViewer sViewer = null;
885 public void showStructures(boolean waitUntilFinished)
888 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
890 final int preferredHeight = pnl_filter.getHeight();
892 Runnable viewStruc = new Runnable()
897 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
899 String currentView = selectedFilterOpt.getView();
900 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
903 if (currentView == VIEWS_FILTER)
905 int pdbIdColIndex = restable.getColumn("PDB Id")
907 int refSeqColIndex = restable.getColumn("Ref Sequence")
909 int[] selectedRows = restable.getSelectedRows();
910 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
912 List<SequenceI> selectedSeqsToView = new ArrayList<>();
913 for (int row : selectedRows)
915 String pdbIdStr = restable
916 .getValueAt(row, pdbIdColIndex).toString();
917 SequenceI selectedSeq = (SequenceI) restable
918 .getValueAt(row, refSeqColIndex);
919 selectedSeqsToView.add(selectedSeq);
920 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
921 if (pdbEntry == null)
923 pdbEntry = getFindEntry(pdbIdStr,
924 selectedSeq.getAllPDBEntries());
927 if (pdbEntry == null)
929 pdbEntry = new PDBEntry();
930 pdbEntry.setId(pdbIdStr);
931 pdbEntry.setType(PDBEntry.Type.PDB);
932 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
934 pdbEntriesToView[count++] = pdbEntry;
936 SequenceI[] selectedSeqs = selectedSeqsToView
937 .toArray(new SequenceI[selectedSeqsToView.size()]);
938 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
941 else if (currentView == VIEWS_LOCAL_PDB)
943 int[] selectedRows = tbl_local_pdb.getSelectedRows();
944 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
946 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
948 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
950 List<SequenceI> selectedSeqsToView = new ArrayList<>();
951 for (int row : selectedRows)
953 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
955 pdbEntriesToView[count++] = pdbEntry;
956 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
957 .getValueAt(row, refSeqColIndex);
958 selectedSeqsToView.add(selectedSeq);
960 SequenceI[] selectedSeqs = selectedSeqsToView
961 .toArray(new SequenceI[selectedSeqsToView.size()]);
962 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
965 else if (currentView == VIEWS_ENTER_ID)
967 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
968 .getCmb_assSeq().getSelectedItem()).getSequence();
969 if (userSelectedSeq != null)
971 selectedSequence = userSelectedSeq;
973 String pdbIdStr = txt_search.getText();
974 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
975 if (pdbEntry == null)
977 pdbEntry = new PDBEntry();
978 if (pdbIdStr.split(":").length > 1)
980 pdbEntry.setId(pdbIdStr.split(":")[0]);
981 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
985 pdbEntry.setId(pdbIdStr);
987 pdbEntry.setType(PDBEntry.Type.PDB);
988 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
991 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
992 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
994 { selectedSequence });
996 else if (currentView == VIEWS_FROM_FILE)
998 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
999 .getCmb_assSeq().getSelectedItem()).getSequence();
1000 if (userSelectedSeq != null)
1002 selectedSequence = userSelectedSeq;
1004 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1005 .associatePdbWithSeq(selectedPdbFileName,
1006 DataSourceType.FILE, selectedSequence, true,
1009 sViewer = launchStructureViewer(
1013 { selectedSequence });
1015 SwingUtilities.invokeLater(new Runnable()
1020 closeAction(preferredHeight);
1021 mainFrame.dispose();
1026 Thread runner = new Thread(viewStruc);
1028 if (waitUntilFinished)
1030 while (sViewer == null ? runner.isAlive()
1031 : (sViewer.sview == null ? true
1032 : !sViewer.sview.hasMapping()))
1037 } catch (InterruptedException ie)
1045 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1047 Objects.requireNonNull(id);
1048 Objects.requireNonNull(pdbEntries);
1049 PDBEntry foundEntry = null;
1050 for (PDBEntry entry : pdbEntries)
1052 if (entry.getId().equalsIgnoreCase(id))
1061 * Answers a structure viewer (new or existing) configured to superimpose
1062 * added structures or not according to the user's choice
1067 StructureViewer getTargetedStructureViewer(
1068 StructureSelectionManager ssm)
1070 Object sv = targetView.getSelectedItem();
1072 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1076 * Adds PDB structures to a new or existing structure viewer
1079 * @param pdbEntriesToView
1084 private StructureViewer launchStructureViewer(
1085 StructureSelectionManager ssm,
1086 final PDBEntry[] pdbEntriesToView,
1087 final AlignmentPanel alignPanel, SequenceI[] sequences)
1089 long progressId = sequences.hashCode();
1090 setProgressBar(MessageManager
1091 .getString("status.launching_3d_structure_viewer"), progressId);
1092 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1093 boolean superimpose = chk_superpose.isSelected();
1094 theViewer.setSuperpose(superimpose);
1097 * remember user's choice of superimpose or not
1099 Cache.setProperty(AUTOSUPERIMPOSE,
1100 Boolean.valueOf(superimpose).toString());
1102 setProgressBar(null, progressId);
1103 if (SiftsSettings.isMapWithSifts())
1105 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1107 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1108 // real PDB ID. For moment, we can also safely do this if there is already
1109 // a known mapping between the PDBEntry and the sequence.
1110 for (SequenceI seq : sequences)
1112 PDBEntry pdbe = pdbEntriesToView[p++];
1113 if (pdbe != null && pdbe.getFile() != null)
1115 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1116 if (smm != null && smm.length > 0)
1118 for (StructureMapping sm : smm)
1120 if (sm.getSequence() == seq)
1127 if (seq.getPrimaryDBRefs().isEmpty())
1129 seqsWithoutSourceDBRef.add(seq);
1133 if (!seqsWithoutSourceDBRef.isEmpty())
1135 int y = seqsWithoutSourceDBRef.size();
1136 setProgressBar(MessageManager.formatMessage(
1137 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1139 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1140 .toArray(new SequenceI[y]);
1141 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1142 dbRefFetcher.fetchDBRefs(true);
1144 setProgressBar("Fetch complete.", progressId); // todo i18n
1147 if (pdbEntriesToView.length > 1)
1149 setProgressBar(MessageManager.getString(
1150 "status.fetching_3d_structures_for_selected_entries"),
1152 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1156 setProgressBar(MessageManager.formatMessage(
1157 "status.fetching_3d_structures_for",
1158 pdbEntriesToView[0].getId()),progressId);
1159 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1161 setProgressBar(null, progressId);
1162 // remember the last viewer we used...
1163 lastTargetedView = theViewer;
1168 * Populates the combo-box used in associating manually fetched structures to
1169 * a unique sequence when more than one sequence selection is made.
1172 protected void populateCmbAssociateSeqOptions(
1173 JComboBox<AssociateSeqOptions> cmb_assSeq,
1174 JLabel lbl_associateSeq)
1176 cmb_assSeq.removeAllItems();
1178 new AssociateSeqOptions("-Select Associated Seq-", null));
1179 lbl_associateSeq.setVisible(false);
1180 if (selectedSequences.length > 1)
1182 for (SequenceI seq : selectedSequences)
1184 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1189 String seqName = selectedSequence.getDisplayId(false);
1190 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1191 lbl_associateSeq.setText(seqName);
1192 lbl_associateSeq.setVisible(true);
1193 cmb_assSeq.setVisible(false);
1197 protected boolean isStructuresDiscovered()
1199 return discoveredStructuresSet != null
1200 && !discoveredStructuresSet.isEmpty();
1204 protected void txt_search_ActionPerformed()
1211 errorWarning.setLength(0);
1212 isValidPBDEntry = false;
1213 if (txt_search.getText().length() > 0)
1215 String searchTerm = txt_search.getText().toLowerCase();
1216 searchTerm = searchTerm.split(":")[0];
1217 // System.out.println(">>>>> search term : " + searchTerm);
1218 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1219 FTSRestRequest pdbRequest = new FTSRestRequest();
1220 pdbRequest.setAllowEmptySeq(false);
1221 pdbRequest.setResponseSize(1);
1222 pdbRequest.setFieldToSearchBy("(pdb_id:");
1223 pdbRequest.setWantedFields(wantedFields);
1224 pdbRequest.setSearchTerm(searchTerm + ")");
1225 pdbRequest.setAssociatedSequence(selectedSequence);
1226 pdbRestCleint = PDBFTSRestClient.getInstance();
1227 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1228 FTSRestResponse resultList;
1231 resultList = pdbRestCleint.executeRequest(pdbRequest);
1232 } catch (Exception e)
1234 errorWarning.append(e.getMessage());
1238 validateSelections();
1240 if (resultList.getSearchSummary() != null
1241 && resultList.getSearchSummary().size() > 0)
1243 isValidPBDEntry = true;
1246 validateSelections();
1252 protected void tabRefresh()
1254 if (selectedSequences != null)
1256 Thread refreshThread = new Thread(new Runnable()
1261 fetchStructuresMetaData();
1263 ((FilterOption) cmb_filterOption.getSelectedItem())
1267 refreshThread.start();
1271 public class PDBEntryTableModel extends AbstractTableModel
1273 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1276 private List<CachedPDB> pdbEntries;
1278 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1280 this.pdbEntries = new ArrayList<>(pdbEntries);
1284 public String getColumnName(int columnIndex)
1286 return columns[columnIndex];
1290 public int getRowCount()
1292 return pdbEntries.size();
1296 public int getColumnCount()
1298 return columns.length;
1302 public boolean isCellEditable(int row, int column)
1308 public Object getValueAt(int rowIndex, int columnIndex)
1310 Object value = "??";
1311 CachedPDB entry = pdbEntries.get(rowIndex);
1312 switch (columnIndex)
1315 value = entry.getSequence();
1318 value = entry.getPdbEntry();
1321 value = entry.getPdbEntry().getChainCode() == null ? "_"
1322 : entry.getPdbEntry().getChainCode();
1325 value = entry.getPdbEntry().getType();
1328 value = entry.getPdbEntry().getFile();
1335 public Class<?> getColumnClass(int columnIndex)
1337 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1340 public CachedPDB getPDBEntryAt(int row)
1342 return pdbEntries.get(row);
1347 private class CachedPDB
1349 private SequenceI sequence;
1351 private PDBEntry pdbEntry;
1353 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1355 this.sequence = sequence;
1356 this.pdbEntry = pdbEntry;
1359 public SequenceI getSequence()
1364 public PDBEntry getPdbEntry()
1371 private IProgressIndicator progressBar;
1374 public void setProgressBar(String message, long id)
1376 progressBar.setProgressBar(message, id);
1380 public void registerHandler(long id, IProgressIndicatorHandler handler)
1382 progressBar.registerHandler(id, handler);
1386 public boolean operationInProgress()
1388 return progressBar.operationInProgress();
1391 public JalviewStructureDisplayI getOpenedStructureViewer()
1393 return sViewer == null ? null : sViewer.sview;