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 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
569 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
570 chooser.setFileView(new jalview.io.JalviewFileView());
571 chooser.setDialogTitle(
572 MessageManager.formatMessage("label.select_pdb_file_for",
573 selectedSequence.getDisplayId(false)));
574 chooser.setToolTipText(MessageManager.formatMessage(
575 "label.load_pdb_file_associate_with_sequence",
576 selectedSequence.getDisplayId(false)));
578 int value = chooser.showOpenDialog(null);
579 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
581 selectedPdbFileName = chooser.getSelectedFile().getPath();
582 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
583 validateSelections();
588 * Populates the filter combo-box options dynamically depending on discovered
591 protected void populateFilterComboBox(boolean haveData,
592 boolean cachedPDBExist)
595 * temporarily suspend the change listener behaviour
597 cmb_filterOption.removeItemListener(this);
599 cmb_filterOption.removeAllItems();
602 cmb_filterOption.addItem(new FilterOption(
603 MessageManager.getString("label.best_quality"),
604 "overall_quality", VIEWS_FILTER, false));
605 cmb_filterOption.addItem(new FilterOption(
606 MessageManager.getString("label.best_resolution"),
607 "resolution", VIEWS_FILTER, false));
608 cmb_filterOption.addItem(new FilterOption(
609 MessageManager.getString("label.most_protein_chain"),
610 "number_of_protein_chains", VIEWS_FILTER, false));
611 cmb_filterOption.addItem(new FilterOption(
612 MessageManager.getString("label.most_bound_molecules"),
613 "number_of_bound_molecules", VIEWS_FILTER, false));
614 cmb_filterOption.addItem(new FilterOption(
615 MessageManager.getString("label.most_polymer_residues"),
616 "number_of_polymer_residues", VIEWS_FILTER, true));
618 cmb_filterOption.addItem(
619 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
620 "-", VIEWS_ENTER_ID, false));
621 cmb_filterOption.addItem(
622 new FilterOption(MessageManager.getString("label.from_file"),
623 "-", VIEWS_FROM_FILE, false));
627 FilterOption cachedOption = new FilterOption(
628 MessageManager.getString("label.cached_structures"),
629 "-", VIEWS_LOCAL_PDB, false);
630 cmb_filterOption.addItem(cachedOption);
631 cmb_filterOption.setSelectedItem(cachedOption);
634 cmb_filterOption.addItemListener(this);
638 * Updates the displayed view based on the selected filter option
640 protected void updateCurrentView()
642 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
644 layout_switchableViews.show(pnl_switchableViews,
645 selectedFilterOpt.getView());
646 String filterTitle = mainFrame.getTitle();
647 mainFrame.setTitle(frameTitle);
648 chk_invertFilter.setVisible(false);
649 if (selectedFilterOpt.getView() == VIEWS_FILTER)
651 mainFrame.setTitle(filterTitle);
652 chk_invertFilter.setVisible(true);
653 filterResultSet(selectedFilterOpt.getValue());
655 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
656 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
658 mainFrame.setTitle(MessageManager
659 .getString("label.structure_chooser_manual_association"));
660 idInputAssSeqPanel.loadCmbAssSeq();
661 fileChooserAssSeqPanel.loadCmbAssSeq();
663 validateSelections();
667 * Validates user selection and enables the 'Add' and 'New View' buttons if
668 * all parameters are correct (the Add button will only be visible if there is
669 * at least one existing structure viewer open). This basically means at least
670 * one structure selected and no error messages.
672 * The 'Superpose Structures' option is enabled if either more than one
673 * structure is selected, or the 'Add' to existing view option is enabled, and
674 * disabled if the only option is to open a new view of a single structure.
677 protected void validateSelections()
679 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
681 btn_add.setEnabled(false);
682 String currentView = selectedFilterOpt.getView();
683 int selectedCount = 0;
684 if (currentView == VIEWS_FILTER)
686 selectedCount = getResultTable().getSelectedRows().length;
687 if (selectedCount > 0)
689 btn_add.setEnabled(true);
692 else if (currentView == VIEWS_LOCAL_PDB)
694 selectedCount = tbl_local_pdb.getSelectedRows().length;
695 if (selectedCount > 0)
697 btn_add.setEnabled(true);
700 else if (currentView == VIEWS_ENTER_ID)
702 validateAssociationEnterPdb();
704 else if (currentView == VIEWS_FROM_FILE)
706 validateAssociationFromFile();
709 btn_newView.setEnabled(btn_add.isEnabled());
712 * enable 'Superpose' option if more than one structure is selected,
713 * or there are view(s) available to add structure(s) to
716 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
720 * Validates inputs from the Manual PDB entry panel
722 protected void validateAssociationEnterPdb()
724 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
725 .getCmb_assSeq().getSelectedItem();
726 lbl_pdbManualFetchStatus.setIcon(errorImage);
727 lbl_pdbManualFetchStatus.setToolTipText("");
728 if (txt_search.getText().length() > 0)
730 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
731 MessageManager.formatMessage("info.no_pdb_entry_found_for",
732 txt_search.getText())));
735 if (errorWarning.length() > 0)
737 lbl_pdbManualFetchStatus.setIcon(warningImage);
738 lbl_pdbManualFetchStatus.setToolTipText(
739 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
742 if (selectedSequences.length == 1 || !assSeqOpt.getName()
743 .equalsIgnoreCase("-Select Associated Seq-"))
745 txt_search.setEnabled(true);
748 btn_add.setEnabled(true);
749 lbl_pdbManualFetchStatus.setToolTipText("");
750 lbl_pdbManualFetchStatus.setIcon(goodImage);
755 txt_search.setEnabled(false);
756 lbl_pdbManualFetchStatus.setIcon(errorImage);
761 * Validates inputs for the manual PDB file selection options
763 protected void validateAssociationFromFile()
765 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
766 .getCmb_assSeq().getSelectedItem();
767 lbl_fromFileStatus.setIcon(errorImage);
768 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
769 .getName().equalsIgnoreCase("-Select Associated Seq-")))
771 btn_pdbFromFile.setEnabled(true);
772 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
774 btn_add.setEnabled(true);
775 lbl_fromFileStatus.setIcon(goodImage);
780 btn_pdbFromFile.setEnabled(false);
781 lbl_fromFileStatus.setIcon(errorImage);
786 protected void cmbAssSeqStateChanged()
788 validateSelections();
792 * Handles the state change event for the 'filter' combo-box and 'invert'
796 protected void stateChanged(ItemEvent e)
798 if (e.getSource() instanceof JCheckBox)
804 if (e.getStateChange() == ItemEvent.SELECTED)
813 * select structures for viewing by their PDB IDs
816 * @return true if structures were found and marked as selected
818 public boolean selectStructure(String... pdbids)
820 boolean found = false;
822 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
824 String currentView = selectedFilterOpt.getView();
825 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
826 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
828 if (restable == null)
830 // can't select (enter PDB ID, or load file - need to also select which
831 // sequence to associate with)
835 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
836 for (int r = 0; r < restable.getRowCount(); r++)
838 for (int p = 0; p < pdbids.length; p++)
840 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
841 .equalsIgnoreCase(pdbids[p]))
843 restable.setRowSelectionInterval(r, r);
852 * Handles the 'New View' action
855 protected void newView_ActionPerformed()
857 targetView.setSelectedItem(null);
858 showStructures(false);
862 * Handles the 'Add to existing viewer' action
865 protected void add_ActionPerformed()
867 showStructures(false);
871 * structure viewer opened by this dialog, or null
873 private StructureViewer sViewer = null;
875 public void showStructures(boolean waitUntilFinished)
878 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
880 final int preferredHeight = pnl_filter.getHeight();
882 Runnable viewStruc = new Runnable()
887 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
889 String currentView = selectedFilterOpt.getView();
890 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
893 if (currentView == VIEWS_FILTER)
895 int pdbIdColIndex = restable.getColumn("PDB Id")
897 int refSeqColIndex = restable.getColumn("Ref Sequence")
899 int[] selectedRows = restable.getSelectedRows();
900 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
902 List<SequenceI> selectedSeqsToView = new ArrayList<>();
903 for (int row : selectedRows)
905 String pdbIdStr = restable
906 .getValueAt(row, pdbIdColIndex).toString();
907 SequenceI selectedSeq = (SequenceI) restable
908 .getValueAt(row, refSeqColIndex);
909 selectedSeqsToView.add(selectedSeq);
910 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
911 if (pdbEntry == null)
913 pdbEntry = getFindEntry(pdbIdStr,
914 selectedSeq.getAllPDBEntries());
917 if (pdbEntry == null)
919 pdbEntry = new PDBEntry();
920 pdbEntry.setId(pdbIdStr);
921 pdbEntry.setType(PDBEntry.Type.PDB);
922 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
924 pdbEntriesToView[count++] = pdbEntry;
926 SequenceI[] selectedSeqs = selectedSeqsToView
927 .toArray(new SequenceI[selectedSeqsToView.size()]);
928 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
931 else if (currentView == VIEWS_LOCAL_PDB)
933 int[] selectedRows = tbl_local_pdb.getSelectedRows();
934 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
936 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
938 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
940 List<SequenceI> selectedSeqsToView = new ArrayList<>();
941 for (int row : selectedRows)
943 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
945 pdbEntriesToView[count++] = pdbEntry;
946 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
947 .getValueAt(row, refSeqColIndex);
948 selectedSeqsToView.add(selectedSeq);
950 SequenceI[] selectedSeqs = selectedSeqsToView
951 .toArray(new SequenceI[selectedSeqsToView.size()]);
952 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
955 else if (currentView == VIEWS_ENTER_ID)
957 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
958 .getCmb_assSeq().getSelectedItem()).getSequence();
959 if (userSelectedSeq != null)
961 selectedSequence = userSelectedSeq;
963 String pdbIdStr = txt_search.getText();
964 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
965 if (pdbEntry == null)
967 pdbEntry = new PDBEntry();
968 if (pdbIdStr.split(":").length > 1)
970 pdbEntry.setId(pdbIdStr.split(":")[0]);
971 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
975 pdbEntry.setId(pdbIdStr);
977 pdbEntry.setType(PDBEntry.Type.PDB);
978 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
981 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
982 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
984 { selectedSequence });
986 else if (currentView == VIEWS_FROM_FILE)
988 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
989 .getCmb_assSeq().getSelectedItem()).getSequence();
990 if (userSelectedSeq != null)
992 selectedSequence = userSelectedSeq;
994 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
995 .associatePdbWithSeq(selectedPdbFileName,
996 DataSourceType.FILE, selectedSequence, true,
999 sViewer = launchStructureViewer(
1003 { selectedSequence });
1005 SwingUtilities.invokeLater(new Runnable()
1010 closeAction(preferredHeight);
1011 mainFrame.dispose();
1016 Thread runner = new Thread(viewStruc);
1018 if (waitUntilFinished)
1020 while (sViewer == null ? runner.isAlive()
1021 : (sViewer.sview == null ? true
1022 : !sViewer.sview.hasMapping()))
1027 } catch (InterruptedException ie)
1035 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1037 Objects.requireNonNull(id);
1038 Objects.requireNonNull(pdbEntries);
1039 PDBEntry foundEntry = null;
1040 for (PDBEntry entry : pdbEntries)
1042 if (entry.getId().equalsIgnoreCase(id))
1051 * Answers a structure viewer (new or existing) configured to superimpose
1052 * added structures or not according to the user's choice
1057 StructureViewer getTargetedStructureViewer(
1058 StructureSelectionManager ssm)
1060 Object sv = targetView.getSelectedItem();
1062 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1066 * Adds PDB structures to a new or existing structure viewer
1069 * @param pdbEntriesToView
1074 private StructureViewer launchStructureViewer(
1075 StructureSelectionManager ssm,
1076 final PDBEntry[] pdbEntriesToView,
1077 final AlignmentPanel alignPanel, SequenceI[] sequences)
1079 long progressId = sequences.hashCode();
1080 setProgressBar(MessageManager
1081 .getString("status.launching_3d_structure_viewer"), progressId);
1082 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1083 boolean superimpose = chk_superpose.isSelected();
1084 theViewer.setSuperpose(superimpose);
1087 * remember user's choice of superimpose or not
1089 Cache.setProperty(AUTOSUPERIMPOSE,
1090 Boolean.valueOf(superimpose).toString());
1092 setProgressBar(null, progressId);
1093 if (SiftsSettings.isMapWithSifts())
1095 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1097 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1098 // real PDB ID. For moment, we can also safely do this if there is already
1099 // a known mapping between the PDBEntry and the sequence.
1100 for (SequenceI seq : sequences)
1102 PDBEntry pdbe = pdbEntriesToView[p++];
1103 if (pdbe != null && pdbe.getFile() != null)
1105 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1106 if (smm != null && smm.length > 0)
1108 for (StructureMapping sm : smm)
1110 if (sm.getSequence() == seq)
1117 if (seq.getPrimaryDBRefs().isEmpty())
1119 seqsWithoutSourceDBRef.add(seq);
1123 if (!seqsWithoutSourceDBRef.isEmpty())
1125 int y = seqsWithoutSourceDBRef.size();
1126 setProgressBar(MessageManager.formatMessage(
1127 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1129 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1130 .toArray(new SequenceI[y]);
1131 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1132 dbRefFetcher.fetchDBRefs(true);
1134 setProgressBar("Fetch complete.", progressId); // todo i18n
1137 if (pdbEntriesToView.length > 1)
1139 setProgressBar(MessageManager.getString(
1140 "status.fetching_3d_structures_for_selected_entries"),
1142 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1146 setProgressBar(MessageManager.formatMessage(
1147 "status.fetching_3d_structures_for",
1148 pdbEntriesToView[0].getId()),progressId);
1149 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1151 setProgressBar(null, progressId);
1152 // remember the last viewer we used...
1153 lastTargetedView = theViewer;
1158 * Populates the combo-box used in associating manually fetched structures to
1159 * a unique sequence when more than one sequence selection is made.
1162 protected void populateCmbAssociateSeqOptions(
1163 JComboBox<AssociateSeqOptions> cmb_assSeq,
1164 JLabel lbl_associateSeq)
1166 cmb_assSeq.removeAllItems();
1168 new AssociateSeqOptions("-Select Associated Seq-", null));
1169 lbl_associateSeq.setVisible(false);
1170 if (selectedSequences.length > 1)
1172 for (SequenceI seq : selectedSequences)
1174 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1179 String seqName = selectedSequence.getDisplayId(false);
1180 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1181 lbl_associateSeq.setText(seqName);
1182 lbl_associateSeq.setVisible(true);
1183 cmb_assSeq.setVisible(false);
1187 protected boolean isStructuresDiscovered()
1189 return discoveredStructuresSet != null
1190 && !discoveredStructuresSet.isEmpty();
1194 protected void txt_search_ActionPerformed()
1201 errorWarning.setLength(0);
1202 isValidPBDEntry = false;
1203 if (txt_search.getText().length() > 0)
1205 String searchTerm = txt_search.getText().toLowerCase();
1206 searchTerm = searchTerm.split(":")[0];
1207 // System.out.println(">>>>> search term : " + searchTerm);
1208 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1209 FTSRestRequest pdbRequest = new FTSRestRequest();
1210 pdbRequest.setAllowEmptySeq(false);
1211 pdbRequest.setResponseSize(1);
1212 pdbRequest.setFieldToSearchBy("(pdb_id:");
1213 pdbRequest.setWantedFields(wantedFields);
1214 pdbRequest.setSearchTerm(searchTerm + ")");
1215 pdbRequest.setAssociatedSequence(selectedSequence);
1216 pdbRestCleint = PDBFTSRestClient.getInstance();
1217 wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
1218 FTSRestResponse resultList;
1221 resultList = pdbRestCleint.executeRequest(pdbRequest);
1222 } catch (Exception e)
1224 errorWarning.append(e.getMessage());
1228 validateSelections();
1230 if (resultList.getSearchSummary() != null
1231 && resultList.getSearchSummary().size() > 0)
1233 isValidPBDEntry = true;
1236 validateSelections();
1242 protected void tabRefresh()
1244 if (selectedSequences != null)
1246 Thread refreshThread = new Thread(new Runnable()
1251 fetchStructuresMetaData();
1253 ((FilterOption) cmb_filterOption.getSelectedItem())
1257 refreshThread.start();
1261 public class PDBEntryTableModel extends AbstractTableModel
1263 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1266 private List<CachedPDB> pdbEntries;
1268 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1270 this.pdbEntries = new ArrayList<>(pdbEntries);
1274 public String getColumnName(int columnIndex)
1276 return columns[columnIndex];
1280 public int getRowCount()
1282 return pdbEntries.size();
1286 public int getColumnCount()
1288 return columns.length;
1292 public boolean isCellEditable(int row, int column)
1298 public Object getValueAt(int rowIndex, int columnIndex)
1300 Object value = "??";
1301 CachedPDB entry = pdbEntries.get(rowIndex);
1302 switch (columnIndex)
1305 value = entry.getSequence();
1308 value = entry.getPdbEntry();
1311 value = entry.getPdbEntry().getChainCode() == null ? "_"
1312 : entry.getPdbEntry().getChainCode();
1315 value = entry.getPdbEntry().getType();
1318 value = entry.getPdbEntry().getFile();
1325 public Class<?> getColumnClass(int columnIndex)
1327 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1330 public CachedPDB getPDBEntryAt(int row)
1332 return pdbEntries.get(row);
1337 private class CachedPDB
1339 private SequenceI sequence;
1341 private PDBEntry pdbEntry;
1343 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1345 this.sequence = sequence;
1346 this.pdbEntry = pdbEntry;
1349 public SequenceI getSequence()
1354 public PDBEntry getPdbEntry()
1361 private IProgressIndicator progressBar;
1364 public void setProgressBar(String message, long id)
1366 progressBar.setProgressBar(message, id);
1370 public void registerHandler(long id, IProgressIndicatorHandler handler)
1372 progressBar.registerHandler(id, handler);
1376 public boolean operationInProgress()
1378 return progressBar.operationInProgress();
1381 public JalviewStructureDisplayI getOpenedStructureViewer()
1383 return sViewer == null ? null : sViewer.sview;