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 final int MAX_QLENGTH = 7820;
76 protected SequenceI selectedSequence;
78 public SequenceI[] selectedSequences;
80 private IProgressIndicator progressIndicator;
82 protected Collection<FTSData> discoveredStructuresSet;
84 protected FTSRestRequest lastPdbRequest;
86 protected FTSRestClientI pdbRestClient;
88 protected String selectedPdbFileName;
90 protected boolean isValidPBDEntry;
92 protected boolean cachedPDBExists;
94 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
98 this.selectedSequence = selectedSeq;
99 this.selectedSequences = selectedSeqs;
100 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
105 * Initializes parameters used by the Structure Chooser Panel
107 protected void init()
109 if (!Jalview.isHeadlessMode())
111 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
114 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
116 // ensure a filter option is in force for search
117 populateFilterComboBox(true, cachedPDBExists);
118 Thread discoverPDBStructuresThread = new Thread(new Runnable()
123 long startTime = System.currentTimeMillis();
124 updateProgressIndicator(MessageManager
125 .getString("status.loading_cached_pdb_entries"), startTime);
126 loadLocalCachedPDBEntries();
127 updateProgressIndicator(null, startTime);
128 updateProgressIndicator(MessageManager.getString(
129 "status.searching_for_pdb_structures"), startTime);
130 fetchStructuresMetaData();
131 // revise filter options if no results were found
132 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
133 discoverStructureViews();
134 updateProgressIndicator(null, startTime);
135 mainFrame.setVisible(true);
139 discoverPDBStructuresThread.start();
143 * Builds a drop-down choice list of existing structure viewers to which new
144 * structures may be added. If this list is empty then it, and the 'Add'
145 * button, are hidden.
147 protected void discoverStructureViews()
149 if (Desktop.getInstance() != null)
151 targetView.removeAllItems();
152 Desktop d = Desktop.getInstance();
153 if (d.lastTargetedView != null && !d.lastTargetedView.isVisible())
155 d.lastTargetedView = null;
157 int linkedViewsAt = 0;
158 for (StructureViewerBase view : Desktop.getInstance()
159 .getStructureViewers(null, null))
161 StructureViewer viewHandler = (d.lastTargetedView != null
162 && d.lastTargetedView.sview == view) ? d.lastTargetedView
163 : StructureViewer.reconfigure(view);
165 if (view.isLinkedWith(ap))
167 targetView.insertItemAt(viewHandler,
172 targetView.addItem(viewHandler);
177 * show option to Add to viewer if at least 1 viewer found
179 targetView.setVisible(false);
180 if (targetView.getItemCount() > 0)
182 targetView.setVisible(true);
183 if (d.lastTargetedView != null)
185 targetView.setSelectedItem(d.lastTargetedView);
189 targetView.setSelectedIndex(0);
192 btn_add.setVisible(targetView.isVisible());
197 * Updates the progress indicator with the specified message
200 * displayed message for the operation
202 * unique handle for this indicator
204 protected void updateProgressIndicator(String message, long id)
206 if (progressIndicator != null)
208 progressIndicator.setProgressBar(message, id);
213 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
216 void fetchStructuresMetaData()
218 long startTime = System.currentTimeMillis();
219 pdbRestClient = PDBFTSRestClient.getInstance();
220 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
221 .getStructureSummaryFields();
223 discoveredStructuresSet = new LinkedHashSet<>();
224 HashSet<String> errors = new HashSet<>();
225 for (SequenceI seq : selectedSequences)
227 FTSRestRequest pdbRequest = new FTSRestRequest();
228 pdbRequest.setAllowEmptySeq(false);
229 pdbRequest.setResponseSize(500);
230 pdbRequest.setFieldToSearchBy("(");
231 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
233 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
234 !chk_invertFilter.isSelected());
235 pdbRequest.setWantedFields(wantedFields);
236 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
237 pdbRequest.setAssociatedSequence(seq);
238 FTSRestResponse resultList;
241 resultList = pdbRestClient.executeRequest(pdbRequest);
242 } catch (Exception e)
245 errors.add(e.getMessage());
248 lastPdbRequest = pdbRequest;
249 if (resultList.getSearchSummary() != null
250 && !resultList.getSearchSummary().isEmpty())
252 discoveredStructuresSet.addAll(resultList.getSearchSummary());
256 int noOfStructuresFound = 0;
257 String totalTime = (System.currentTimeMillis() - startTime)
259 if (discoveredStructuresSet != null
260 && !discoveredStructuresSet.isEmpty())
262 getResultTable().setModel(FTSRestResponse
263 .getTableModel(lastPdbRequest, discoveredStructuresSet));
264 noOfStructuresFound = discoveredStructuresSet.size();
265 mainFrame.setTitle(MessageManager.formatMessage(
266 "label.structure_chooser_no_of_structures",
267 noOfStructuresFound, totalTime));
271 mainFrame.setTitle(MessageManager
272 .getString("label.structure_chooser_manual_association"));
273 if (errors.size() > 0)
275 StringBuilder errorMsg = new StringBuilder();
276 for (String error : errors)
278 errorMsg.append(error).append("\n");
280 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
281 MessageManager.getString("label.pdb_web-service_error"),
282 JvOptionPane.ERROR_MESSAGE);
287 protected void loadLocalCachedPDBEntries()
289 ArrayList<CachedPDB> entries = new ArrayList<>();
290 for (SequenceI seq : selectedSequences)
292 if (seq.getDatasetSequence() != null
293 && seq.getDatasetSequence().getAllPDBEntries() != null)
295 for (PDBEntry pdbEntry : seq.getDatasetSequence()
298 if (pdbEntry.getFile() != null)
300 entries.add(new CachedPDB(seq, pdbEntry));
305 cachedPDBExists = !entries.isEmpty();
306 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
307 tbl_local_pdb.setModel(tableModelx);
311 * Builds a query string for a given sequences using its DBRef entries
314 * the sequences to build a query for
315 * @return the built query string
318 static String buildQuery(SequenceI seq)
320 boolean isPDBRefsFound = false;
321 boolean isUniProtRefsFound = false;
322 StringBuilder queryBuilder = new StringBuilder();
323 Set<String> seqRefs = new LinkedHashSet<>();
325 if (seq.getAllPDBEntries() != null
326 && queryBuilder.length() < MAX_QLENGTH)
328 for (PDBEntry entry : seq.getAllPDBEntries())
330 if (isValidSeqName(entry.getId()))
332 queryBuilder.append("pdb_id:").append(entry.getId().toLowerCase())
334 isPDBRefsFound = true;
339 List<DBRefEntry> refs = seq.getDBRefs();
340 if (refs != null && refs.size() != 0)
342 for (int ib = 0, nb = refs.size(); ib < nb; ib++)
344 DBRefEntry dbRef = refs.get(ib);
345 if (isValidSeqName(getDBRefId(dbRef))
346 && queryBuilder.length() < MAX_QLENGTH)
348 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
350 queryBuilder.append("uniprot_accession:")
351 .append(getDBRefId(dbRef)).append(" OR ");
352 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
354 isUniProtRefsFound = true;
356 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
359 queryBuilder.append("pdb_id:")
360 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
361 isPDBRefsFound = true;
365 seqRefs.add(getDBRefId(dbRef));
371 if (!isPDBRefsFound && !isUniProtRefsFound)
373 String seqName = seq.getName();
374 seqName = sanitizeSeqName(seqName);
375 String[] names = seqName.toLowerCase().split("\\|");
376 for (String name : names)
378 // System.out.println("Found name : " + name);
380 if (isValidSeqName(name))
386 for (String seqRef : seqRefs)
388 queryBuilder.append("text:").append(seqRef).append(" OR ");
392 int endIndex = queryBuilder.lastIndexOf(" OR ");
393 if (queryBuilder.toString().length() < 6)
397 String query = queryBuilder.toString().substring(0, endIndex);
402 * Remove the following special characters from input string +, -, &, !, (, ),
403 * {, }, [, ], ^, ", ~, *, ?, :, \
408 static String sanitizeSeqName(String seqName)
410 Objects.requireNonNull(seqName);
411 return seqName.replaceAll("\\[\\d*\\]", "")
412 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
416 * Ensures sequence ref names are not less than 3 characters and does not
417 * contain a database name
422 static boolean isValidSeqName(String seqName)
424 // System.out.println("seqName : " + seqName);
425 String ignoreList = "pdb,uniprot,swiss-prot";
426 if (seqName.length() < 3)
430 if (seqName.contains(":"))
434 seqName = seqName.toLowerCase();
435 for (String ignoredEntry : ignoreList.split(","))
437 if (seqName.contains(ignoredEntry))
445 static String getDBRefId(DBRefEntry dbRef)
447 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
452 * Filters a given list of discovered structures based on supplied argument
454 * @param fieldToFilterBy
455 * the field to filter by
457 void filterResultSet(final String fieldToFilterBy)
459 Thread filterThread = new Thread(new Runnable()
464 long startTime = System.currentTimeMillis();
465 pdbRestClient = PDBFTSRestClient.getInstance();
466 lbl_loading.setVisible(true);
467 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
468 .getStructureSummaryFields();
469 Collection<FTSData> filteredResponse = new HashSet<>();
470 HashSet<String> errors = new HashSet<>();
472 for (SequenceI seq : selectedSequences)
474 FTSRestRequest pdbRequest = new FTSRestRequest();
475 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
477 pdbRequest.setAllowEmptySeq(false);
478 pdbRequest.setResponseSize(1);
479 pdbRequest.setFieldToSearchBy("(");
480 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
481 pdbRequest.setWantedFields(wantedFields);
482 pdbRequest.setAssociatedSequence(seq);
483 pdbRequest.setFacet(true);
484 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
485 pdbRequest.setFacetPivotMinCount(1);
489 pdbRequest.setAllowEmptySeq(false);
490 pdbRequest.setResponseSize(1);
491 pdbRequest.setFieldToSearchBy("(");
492 pdbRequest.setFieldToSortBy(fieldToFilterBy,
493 !chk_invertFilter.isSelected());
494 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
495 pdbRequest.setWantedFields(wantedFields);
496 pdbRequest.setAssociatedSequence(seq);
498 FTSRestResponse resultList;
501 resultList = pdbRestClient.executeRequest(pdbRequest);
502 } catch (Exception e)
505 errors.add(e.getMessage());
508 lastPdbRequest = pdbRequest;
509 if (resultList.getSearchSummary() != null
510 && !resultList.getSearchSummary().isEmpty())
512 filteredResponse.addAll(resultList.getSearchSummary());
516 String totalTime = (System.currentTimeMillis() - startTime)
518 if (!filteredResponse.isEmpty())
520 final int filterResponseCount = filteredResponse.size();
521 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
522 reorderedStructuresSet.addAll(filteredResponse);
523 reorderedStructuresSet.addAll(discoveredStructuresSet);
524 getResultTable().setModel(FTSRestResponse
525 .getTableModel(lastPdbRequest, reorderedStructuresSet));
527 FTSRestResponse.configureTableColumn(getResultTable(),
528 wantedFields, tempUserPrefs);
529 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
530 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
531 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
532 // Update table selection model here
533 getResultTable().addRowSelectionInterval(0,
534 filterResponseCount - 1);
535 mainFrame.setTitle(MessageManager.formatMessage(
536 "label.structure_chooser_filter_time", totalTime));
540 mainFrame.setTitle(MessageManager.formatMessage(
541 "label.structure_chooser_filter_time", totalTime));
542 if (errors.size() > 0)
544 StringBuilder errorMsg = new StringBuilder();
545 for (String error : errors)
547 errorMsg.append(error).append("\n");
549 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
550 MessageManager.getString("label.pdb_web-service_error"),
551 JvOptionPane.ERROR_MESSAGE);
555 lbl_loading.setVisible(false);
557 validateSelections();
560 filterThread.start();
564 * Handles action event for btn_pdbFromFile
567 protected void pdbFromFile_actionPerformed()
569 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and StructureChooser
571 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
572 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
573 chooser.setFileView(new jalview.io.JalviewFileView());
574 chooser.setDialogTitle(
575 MessageManager.formatMessage("label.select_pdb_file_for",
576 selectedSequence.getDisplayId(false)));
577 chooser.setToolTipText(MessageManager.formatMessage(
578 "label.load_pdb_file_associate_with_sequence",
579 selectedSequence.getDisplayId(false)));
581 int value = chooser.showOpenDialog(null);
582 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
584 selectedPdbFileName = chooser.getSelectedFile().getPath();
585 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
586 validateSelections();
591 * Populates the filter combo-box options dynamically depending on discovered
594 protected void populateFilterComboBox(boolean haveData,
595 boolean cachedPDBExist)
598 * temporarily suspend the change listener behaviour
600 cmb_filterOption.removeItemListener(this);
602 cmb_filterOption.removeAllItems();
605 cmb_filterOption.addItem(new FilterOption(
606 MessageManager.getString("label.best_quality"),
607 "overall_quality", VIEWS_FILTER, false));
608 cmb_filterOption.addItem(new FilterOption(
609 MessageManager.getString("label.best_resolution"),
610 "resolution", VIEWS_FILTER, false));
611 cmb_filterOption.addItem(new FilterOption(
612 MessageManager.getString("label.most_protein_chain"),
613 "number_of_protein_chains", VIEWS_FILTER, false));
614 cmb_filterOption.addItem(new FilterOption(
615 MessageManager.getString("label.most_bound_molecules"),
616 "number_of_bound_molecules", VIEWS_FILTER, false));
617 cmb_filterOption.addItem(new FilterOption(
618 MessageManager.getString("label.most_polymer_residues"),
619 "number_of_polymer_residues", VIEWS_FILTER, true));
621 cmb_filterOption.addItem(
622 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
623 "-", VIEWS_ENTER_ID, false));
624 cmb_filterOption.addItem(
625 new FilterOption(MessageManager.getString("label.from_file"),
626 "-", VIEWS_FROM_FILE, false));
630 FilterOption cachedOption = new FilterOption(
631 MessageManager.getString("label.cached_structures"),
632 "-", VIEWS_LOCAL_PDB, false);
633 cmb_filterOption.addItem(cachedOption);
634 cmb_filterOption.setSelectedItem(cachedOption);
637 cmb_filterOption.addItemListener(this);
641 * Updates the displayed view based on the selected filter option
643 protected void updateCurrentView()
645 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
647 layout_switchableViews.show(pnl_switchableViews,
648 selectedFilterOpt.getView());
649 String filterTitle = mainFrame.getTitle();
650 mainFrame.setTitle(frameTitle);
651 chk_invertFilter.setVisible(false);
652 if (selectedFilterOpt.getView() == VIEWS_FILTER)
654 mainFrame.setTitle(filterTitle);
655 chk_invertFilter.setVisible(true);
656 filterResultSet(selectedFilterOpt.getValue());
658 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
659 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
661 mainFrame.setTitle(MessageManager
662 .getString("label.structure_chooser_manual_association"));
663 idInputAssSeqPanel.loadCmbAssSeq();
664 fileChooserAssSeqPanel.loadCmbAssSeq();
666 validateSelections();
670 * Validates user selection and enables the 'Add' and 'New View' buttons if
671 * all parameters are correct (the Add button will only be visible if there is
672 * at least one existing structure viewer open). This basically means at least
673 * one structure selected and no error messages.
675 * The 'Superpose Structures' option is enabled if either more than one
676 * structure is selected, or the 'Add' to existing view option is enabled, and
677 * disabled if the only option is to open a new view of a single structure.
680 protected void validateSelections()
682 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
684 btn_add.setEnabled(false);
685 String currentView = selectedFilterOpt.getView();
686 int selectedCount = 0;
687 if (currentView == VIEWS_FILTER)
689 selectedCount = getResultTable().getSelectedRows().length;
690 if (selectedCount > 0)
692 btn_add.setEnabled(true);
695 else if (currentView == VIEWS_LOCAL_PDB)
697 selectedCount = tbl_local_pdb.getSelectedRows().length;
698 if (selectedCount > 0)
700 btn_add.setEnabled(true);
703 else if (currentView == VIEWS_ENTER_ID)
705 validateAssociationEnterPdb();
707 else if (currentView == VIEWS_FROM_FILE)
709 validateAssociationFromFile();
712 btn_newView.setEnabled(btn_add.isEnabled());
715 * enable 'Superpose' option if more than one structure is selected,
716 * or there are view(s) available to add structure(s) to
719 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
723 * Validates inputs from the Manual PDB entry panel
725 protected void validateAssociationEnterPdb()
727 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
728 .getCmb_assSeq().getSelectedItem();
729 lbl_pdbManualFetchStatus.setIcon(errorImage);
730 lbl_pdbManualFetchStatus.setToolTipText("");
731 if (txt_search.getText().length() > 0)
733 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
734 MessageManager.formatMessage("info.no_pdb_entry_found_for",
735 txt_search.getText())));
738 if (errorWarning.length() > 0)
740 lbl_pdbManualFetchStatus.setIcon(warningImage);
741 lbl_pdbManualFetchStatus.setToolTipText(
742 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
745 if (selectedSequences.length == 1 || !assSeqOpt.getName()
746 .equalsIgnoreCase("-Select Associated Seq-"))
748 txt_search.setEnabled(true);
751 btn_add.setEnabled(true);
752 lbl_pdbManualFetchStatus.setToolTipText("");
753 lbl_pdbManualFetchStatus.setIcon(goodImage);
758 txt_search.setEnabled(false);
759 lbl_pdbManualFetchStatus.setIcon(errorImage);
764 * Validates inputs for the manual PDB file selection options
766 protected void validateAssociationFromFile()
768 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
769 .getCmb_assSeq().getSelectedItem();
770 lbl_fromFileStatus.setIcon(errorImage);
771 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
772 .getName().equalsIgnoreCase("-Select Associated Seq-")))
774 btn_pdbFromFile.setEnabled(true);
775 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
777 btn_add.setEnabled(true);
778 lbl_fromFileStatus.setIcon(goodImage);
783 btn_pdbFromFile.setEnabled(false);
784 lbl_fromFileStatus.setIcon(errorImage);
789 protected void cmbAssSeqStateChanged()
791 validateSelections();
795 * Handles the state change event for the 'filter' combo-box and 'invert'
799 protected void stateChanged(ItemEvent e)
801 if (e.getSource() instanceof JCheckBox)
807 if (e.getStateChange() == ItemEvent.SELECTED)
816 * select structures for viewing by their PDB IDs
819 * @return true if structures were found and marked as selected
821 public boolean selectStructure(String... pdbids)
823 boolean found = false;
825 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
827 String currentView = selectedFilterOpt.getView();
828 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
829 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
831 if (restable == null)
833 // can't select (enter PDB ID, or load file - need to also select which
834 // sequence to associate with)
838 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
839 for (int r = 0; r < restable.getRowCount(); r++)
841 for (int p = 0; p < pdbids.length; p++)
843 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
844 .equalsIgnoreCase(pdbids[p]))
846 restable.setRowSelectionInterval(r, r);
855 * Handles the 'New View' action
858 protected void newView_ActionPerformed()
860 targetView.setSelectedItem(null);
861 showStructures(false);
865 * Handles the 'Add to existing viewer' action
868 protected void add_ActionPerformed()
870 showStructures(false);
874 * structure viewer opened by this dialog, or null
876 protected StructureViewer sViewer = null;
878 public void showStructures(boolean waitUntilFinished)
881 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
883 final int preferredHeight = pnl_filter.getHeight();
885 Runnable viewStruc = new Runnable()
890 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
892 String currentView = selectedFilterOpt.getView();
893 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
896 if (currentView == VIEWS_FILTER)
898 int pdbIdColIndex = restable.getColumn("PDB Id")
900 int refSeqColIndex = restable.getColumn("Ref Sequence")
902 int[] selectedRows = restable.getSelectedRows();
903 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
905 List<SequenceI> selectedSeqsToView = new ArrayList<>();
906 for (int row : selectedRows)
908 String pdbIdStr = restable
909 .getValueAt(row, pdbIdColIndex).toString();
910 SequenceI selectedSeq = (SequenceI) restable
911 .getValueAt(row, refSeqColIndex);
912 selectedSeqsToView.add(selectedSeq);
913 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
914 if (pdbEntry == null)
916 pdbEntry = getFindEntry(pdbIdStr,
917 selectedSeq.getAllPDBEntries());
920 if (pdbEntry == null)
922 pdbEntry = new PDBEntry();
923 pdbEntry.setId(pdbIdStr);
924 pdbEntry.setType(PDBEntry.Type.PDB);
925 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
927 pdbEntriesToView[count++] = pdbEntry;
929 SequenceI[] selectedSeqs = selectedSeqsToView
930 .toArray(new SequenceI[selectedSeqsToView.size()]);
931 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
934 else if (currentView == VIEWS_LOCAL_PDB)
936 int[] selectedRows = tbl_local_pdb.getSelectedRows();
937 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
939 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
941 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
943 List<SequenceI> selectedSeqsToView = new ArrayList<>();
944 for (int row : selectedRows)
946 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
948 pdbEntriesToView[count++] = pdbEntry;
949 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
950 .getValueAt(row, refSeqColIndex);
951 selectedSeqsToView.add(selectedSeq);
953 SequenceI[] selectedSeqs = selectedSeqsToView
954 .toArray(new SequenceI[selectedSeqsToView.size()]);
955 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
958 else if (currentView == VIEWS_ENTER_ID)
960 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
961 .getCmb_assSeq().getSelectedItem()).getSequence();
962 if (userSelectedSeq != null)
964 selectedSequence = userSelectedSeq;
966 String pdbIdStr = txt_search.getText();
967 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
968 if (pdbEntry == null)
970 pdbEntry = new PDBEntry();
971 if (pdbIdStr.split(":").length > 1)
973 pdbEntry.setId(pdbIdStr.split(":")[0]);
974 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
978 pdbEntry.setId(pdbIdStr);
980 pdbEntry.setType(PDBEntry.Type.PDB);
981 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
984 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
985 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
987 { selectedSequence });
989 else if (currentView == VIEWS_FROM_FILE)
991 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
992 .getCmb_assSeq().getSelectedItem()).getSequence();
993 if (userSelectedSeq != null)
995 selectedSequence = userSelectedSeq;
997 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
998 .associatePdbWithSeq(selectedPdbFileName,
999 DataSourceType.FILE, selectedSequence, true,
1000 Desktop.getInstance());
1002 sViewer = launchStructureViewer(
1006 { selectedSequence });
1008 SwingUtilities.invokeLater(new Runnable()
1013 closeAction(preferredHeight);
1014 mainFrame.dispose();
1019 Thread runner = new Thread(viewStruc);
1021 if (waitUntilFinished)
1023 while (sViewer == null ? runner.isAlive()
1024 : (sViewer.sview == null ? true
1025 : !sViewer.sview.hasMapping()))
1030 } catch (InterruptedException ie)
1038 protected PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1040 Objects.requireNonNull(id);
1041 Objects.requireNonNull(pdbEntries);
1042 PDBEntry foundEntry = null;
1043 for (PDBEntry entry : pdbEntries)
1045 if (entry.getId().equalsIgnoreCase(id))
1054 * Answers a structure viewer (new or existing) configured to superimpose
1055 * added structures or not according to the user's choice
1060 StructureViewer getTargetedStructureViewer(
1061 StructureSelectionManager ssm)
1063 Object sv = targetView.getSelectedItem();
1065 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1069 * Adds PDB structures to a new or existing structure viewer
1072 * @param pdbEntriesToView
1077 protected StructureViewer launchStructureViewer(
1078 StructureSelectionManager ssm,
1079 final PDBEntry[] pdbEntriesToView,
1080 final AlignmentPanel alignPanel, SequenceI[] sequences)
1082 long progressId = sequences.hashCode();
1083 setProgressBar(MessageManager
1084 .getString("status.launching_3d_structure_viewer"), progressId);
1085 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1086 boolean superimpose = chk_superpose.isSelected();
1087 theViewer.setSuperpose(superimpose);
1090 * remember user's choice of superimpose or not
1092 Cache.setProperty(AUTOSUPERIMPOSE,
1093 Boolean.valueOf(superimpose).toString());
1095 setProgressBar(null, progressId);
1096 if (SiftsSettings.isMapWithSifts())
1098 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1100 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1101 // real PDB ID. For moment, we can also safely do this if there is already
1102 // a known mapping between the PDBEntry and the sequence.
1103 for (SequenceI seq : sequences)
1105 PDBEntry pdbe = pdbEntriesToView[p++];
1106 if (pdbe != null && pdbe.getFile() != null)
1108 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1109 if (smm != null && smm.length > 0)
1111 for (StructureMapping sm : smm)
1113 if (sm.getSequence() == seq)
1120 if (seq.getPrimaryDBRefs().isEmpty())
1122 seqsWithoutSourceDBRef.add(seq);
1126 if (!seqsWithoutSourceDBRef.isEmpty())
1128 int y = seqsWithoutSourceDBRef.size();
1129 setProgressBar(MessageManager.formatMessage(
1130 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1132 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1133 .toArray(new SequenceI[y]);
1134 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1135 dbRefFetcher.fetchDBRefs(true);
1137 setProgressBar("Fetch complete.", progressId); // todo i18n
1140 if (pdbEntriesToView.length > 1)
1142 setProgressBar(MessageManager.getString(
1143 "status.fetching_3d_structures_for_selected_entries"),
1145 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1149 setProgressBar(MessageManager.formatMessage(
1150 "status.fetching_3d_structures_for",
1151 pdbEntriesToView[0].getId()),progressId);
1152 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1154 setProgressBar(null, progressId);
1155 // remember the last viewer we used...
1156 Desktop.getInstance().lastTargetedView = theViewer;
1161 * Populates the combo-box used in associating manually fetched structures to
1162 * a unique sequence when more than one sequence selection is made.
1165 protected void populateCmbAssociateSeqOptions(
1166 JComboBox<AssociateSeqOptions> cmb_assSeq,
1167 JLabel lbl_associateSeq)
1169 cmb_assSeq.removeAllItems();
1171 new AssociateSeqOptions("-Select Associated Seq-", null));
1172 lbl_associateSeq.setVisible(false);
1173 if (selectedSequences.length > 1)
1175 for (SequenceI seq : selectedSequences)
1177 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1182 String seqName = selectedSequence.getDisplayId(false);
1183 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1184 lbl_associateSeq.setText(seqName);
1185 lbl_associateSeq.setVisible(true);
1186 cmb_assSeq.setVisible(false);
1190 protected boolean isStructuresDiscovered()
1192 return discoveredStructuresSet != null
1193 && !discoveredStructuresSet.isEmpty();
1196 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes this.
1197 // Doing a search for "1" or "1c" is valuable?
1198 // Those work but are enormously slow.
1201 protected void txt_search_ActionPerformed()
1203 String text = txt_search.getText().trim();
1204 if (text.length() >= PDB_ID_MIN)
1212 errorWarning.setLength(0);
1213 isValidPBDEntry = false;
1214 if (text.length() > 0)
1216 String searchTerm = text.toLowerCase();
1217 searchTerm = searchTerm.split(":")[0];
1218 // System.out.println(">>>>> search term : " + searchTerm);
1219 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1220 FTSRestRequest pdbRequest = new FTSRestRequest();
1221 pdbRequest.setAllowEmptySeq(false);
1222 pdbRequest.setResponseSize(1);
1223 pdbRequest.setFieldToSearchBy("(pdb_id:");
1224 pdbRequest.setWantedFields(wantedFields);
1225 pdbRequest.setSearchTerm(searchTerm + ")");
1226 pdbRequest.setAssociatedSequence(selectedSequence);
1227 pdbRestClient = PDBFTSRestClient.getInstance();
1228 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1229 FTSRestResponse resultList;
1232 resultList = pdbRestClient.executeRequest(pdbRequest);
1233 } catch (Exception e)
1235 errorWarning.append(e.getMessage());
1239 validateSelections();
1241 if (resultList.getSearchSummary() != null
1242 && resultList.getSearchSummary().size() > 0)
1244 isValidPBDEntry = true;
1247 validateSelections();
1254 protected void tabRefresh()
1256 if (selectedSequences != null)
1258 Thread refreshThread = new Thread(new Runnable()
1263 fetchStructuresMetaData();
1265 ((FilterOption) cmb_filterOption.getSelectedItem())
1269 refreshThread.start();
1273 public class PDBEntryTableModel extends AbstractTableModel
1275 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1278 private List<CachedPDB> pdbEntries;
1280 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1282 this.pdbEntries = new ArrayList<>(pdbEntries);
1286 public String getColumnName(int columnIndex)
1288 return columns[columnIndex];
1292 public int getRowCount()
1294 return pdbEntries.size();
1298 public int getColumnCount()
1300 return columns.length;
1304 public boolean isCellEditable(int row, int column)
1310 public Object getValueAt(int rowIndex, int columnIndex)
1312 Object value = "??";
1313 CachedPDB entry = pdbEntries.get(rowIndex);
1314 switch (columnIndex)
1317 value = entry.getSequence();
1320 value = entry.getPdbEntry();
1323 value = entry.getPdbEntry().getChainCode() == null ? "_"
1324 : entry.getPdbEntry().getChainCode();
1327 value = entry.getPdbEntry().getType();
1330 value = entry.getPdbEntry().getFile();
1337 public Class<?> getColumnClass(int columnIndex)
1339 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1342 public CachedPDB getPDBEntryAt(int row)
1344 return pdbEntries.get(row);
1349 private class CachedPDB
1351 private SequenceI sequence;
1353 private PDBEntry pdbEntry;
1355 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1357 this.sequence = sequence;
1358 this.pdbEntry = pdbEntry;
1361 public SequenceI getSequence()
1366 public PDBEntry getPdbEntry()
1373 private IProgressIndicator progressBar;
1376 public void setProgressBar(String message, long id)
1378 progressBar.setProgressBar(message, id);
1382 public void registerHandler(long id, IProgressIndicatorHandler handler)
1384 progressBar.registerHandler(id, handler);
1388 public boolean operationInProgress()
1390 return progressBar.operationInProgress();
1393 public JalviewStructureDisplayI getOpenedStructureViewer()
1395 return sViewer == null ? null : sViewer.sview;