2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
24 import jalview.api.structures.JalviewStructureDisplayI;
25 import jalview.bin.Cache;
26 import jalview.bin.Jalview;
27 import jalview.datamodel.DBRefEntry;
28 import jalview.datamodel.DBRefSource;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.fts.api.FTSData;
32 import jalview.fts.api.FTSDataColumnI;
33 import jalview.fts.api.FTSRestClientI;
34 import jalview.fts.core.FTSRestRequest;
35 import jalview.fts.core.FTSRestResponse;
36 import jalview.fts.service.pdb.PDBFTSRestClient;
37 import jalview.io.DataSourceType;
38 import jalview.jbgui.GStructureChooser;
39 import jalview.structure.StructureMapping;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.MessageManager;
42 import jalview.ws.DBRefFetcher;
43 import jalview.ws.sifts.SiftsSettings;
45 import java.awt.event.ItemEvent;
46 import java.util.ArrayList;
47 import java.util.Collection;
48 import java.util.HashSet;
49 import java.util.LinkedHashSet;
50 import java.util.List;
51 import java.util.Objects;
53 import java.util.Vector;
55 import javax.swing.JCheckBox;
56 import javax.swing.JComboBox;
57 import javax.swing.JLabel;
58 import javax.swing.JTable;
59 import javax.swing.SwingUtilities;
60 import javax.swing.table.AbstractTableModel;
63 * Provides the behaviors for the Structure chooser Panel
68 @SuppressWarnings("serial")
69 public class StructureChooser extends GStructureChooser
70 implements IProgressIndicator
72 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
74 private static int MAX_QLENGTH = 7820;
76 private SequenceI selectedSequence;
78 private SequenceI[] selectedSequences;
80 private IProgressIndicator progressIndicator;
82 private Collection<FTSData> discoveredStructuresSet;
84 private FTSRestRequest lastPdbRequest;
86 private FTSRestClientI pdbRestClient;
88 private String selectedPdbFileName;
90 private boolean isValidPBDEntry;
92 private boolean cachedPDBExists;
94 private static StructureViewer lastTargetedView = null;
96 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
100 this.selectedSequence = selectedSeq;
101 this.selectedSequences = selectedSeqs;
102 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
107 * Initializes parameters used by the Structure Chooser Panel
109 protected void init()
111 if (!Jalview.isHeadlessMode())
113 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
116 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
118 // ensure a filter option is in force for search
119 populateFilterComboBox(true, cachedPDBExists);
120 Thread discoverPDBStructuresThread = new Thread(new Runnable()
125 long startTime = System.currentTimeMillis();
126 updateProgressIndicator(MessageManager
127 .getString("status.loading_cached_pdb_entries"), startTime);
128 loadLocalCachedPDBEntries();
129 updateProgressIndicator(null, startTime);
130 updateProgressIndicator(MessageManager.getString(
131 "status.searching_for_pdb_structures"), startTime);
132 fetchStructuresMetaData();
133 // revise filter options if no results were found
134 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
135 discoverStructureViews();
136 updateProgressIndicator(null, startTime);
137 mainFrame.setVisible(true);
141 discoverPDBStructuresThread.start();
145 * Builds a drop-down choice list of existing structure viewers to which new
146 * structures may be added. If this list is empty then it, and the 'Add'
147 * button, are hidden.
149 private void discoverStructureViews()
151 if (Desktop.instance != null)
153 targetView.removeAllItems();
154 if (lastTargetedView != null && !lastTargetedView.isVisible())
156 lastTargetedView = null;
158 int linkedViewsAt = 0;
159 for (StructureViewerBase view : Desktop.instance
160 .getStructureViewers(null, null))
162 StructureViewer viewHandler = (lastTargetedView != null
163 && lastTargetedView.sview == view) ? lastTargetedView
164 : StructureViewer.reconfigure(view);
166 if (view.isLinkedWith(ap))
168 targetView.insertItemAt(viewHandler,
173 targetView.addItem(viewHandler);
178 * show option to Add to viewer if at least 1 viewer found
180 targetView.setVisible(false);
181 if (targetView.getItemCount() > 0)
183 targetView.setVisible(true);
184 if (lastTargetedView != null)
186 targetView.setSelectedItem(lastTargetedView);
190 targetView.setSelectedIndex(0);
193 btn_add.setVisible(targetView.isVisible());
198 * Updates the progress indicator with the specified message
201 * displayed message for the operation
203 * unique handle for this indicator
205 protected void updateProgressIndicator(String message, long id)
207 if (progressIndicator != null)
209 progressIndicator.setProgressBar(message, id);
214 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
217 void fetchStructuresMetaData()
219 long startTime = System.currentTimeMillis();
220 pdbRestClient = PDBFTSRestClient.getInstance();
221 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
222 .getStructureSummaryFields();
224 discoveredStructuresSet = new LinkedHashSet<>();
225 HashSet<String> errors = new HashSet<>();
226 for (SequenceI seq : selectedSequences)
228 FTSRestRequest pdbRequest = new FTSRestRequest();
229 pdbRequest.setAllowEmptySeq(false);
230 pdbRequest.setResponseSize(500);
231 pdbRequest.setFieldToSearchBy("(");
232 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
234 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
235 !chk_invertFilter.isSelected());
236 pdbRequest.setWantedFields(wantedFields);
237 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
238 pdbRequest.setAssociatedSequence(seq);
239 FTSRestResponse resultList;
242 resultList = pdbRestClient.executeRequest(pdbRequest);
243 } catch (Exception e)
246 errors.add(e.getMessage());
249 lastPdbRequest = pdbRequest;
250 if (resultList.getSearchSummary() != null
251 && !resultList.getSearchSummary().isEmpty())
253 discoveredStructuresSet.addAll(resultList.getSearchSummary());
257 int noOfStructuresFound = 0;
258 String totalTime = (System.currentTimeMillis() - startTime)
260 if (discoveredStructuresSet != null
261 && !discoveredStructuresSet.isEmpty())
263 getResultTable().setModel(FTSRestResponse
264 .getTableModel(lastPdbRequest, discoveredStructuresSet));
265 noOfStructuresFound = discoveredStructuresSet.size();
266 mainFrame.setTitle(MessageManager.formatMessage(
267 "label.structure_chooser_no_of_structures",
268 noOfStructuresFound, totalTime));
272 mainFrame.setTitle(MessageManager
273 .getString("label.structure_chooser_manual_association"));
274 if (errors.size() > 0)
276 StringBuilder errorMsg = new StringBuilder();
277 for (String error : errors)
279 errorMsg.append(error).append("\n");
281 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
282 MessageManager.getString("label.pdb_web-service_error"),
283 JvOptionPane.ERROR_MESSAGE);
288 protected void loadLocalCachedPDBEntries()
290 ArrayList<CachedPDB> entries = new ArrayList<>();
291 for (SequenceI seq : selectedSequences)
293 if (seq.getDatasetSequence() != null
294 && seq.getDatasetSequence().getAllPDBEntries() != null)
296 for (PDBEntry pdbEntry : seq.getDatasetSequence()
299 if (pdbEntry.getFile() != null)
301 entries.add(new CachedPDB(seq, pdbEntry));
306 cachedPDBExists = !entries.isEmpty();
307 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
308 tbl_local_pdb.setModel(tableModelx);
312 * Builds a query string for a given sequences using its DBRef entries
315 * the sequences to build a query for
316 * @return the built query string
319 static String buildQuery(SequenceI seq)
321 boolean isPDBRefsFound = false;
322 boolean isUniProtRefsFound = false;
323 StringBuilder queryBuilder = new StringBuilder();
324 Set<String> seqRefs = new LinkedHashSet<>();
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 List<DBRefEntry> refs = seq.getDBRefs();
341 if (refs != null && refs.size() != 0)
343 for (int ib = 0, nb = refs.size(); ib < nb; ib++)
345 DBRefEntry dbRef = refs.get(ib);
346 if (isValidSeqName(getDBRefId(dbRef))
347 && queryBuilder.length() < MAX_QLENGTH)
349 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
351 queryBuilder.append("uniprot_accession:")
352 .append(getDBRefId(dbRef)).append(" OR ");
353 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
355 isUniProtRefsFound = true;
357 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
360 queryBuilder.append("pdb_id:")
361 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
362 isPDBRefsFound = true;
366 seqRefs.add(getDBRefId(dbRef));
372 if (!isPDBRefsFound && !isUniProtRefsFound)
374 String seqName = seq.getName();
375 seqName = sanitizeSeqName(seqName);
376 String[] names = seqName.toLowerCase().split("\\|");
377 for (String name : names)
379 // System.out.println("Found name : " + name);
381 if (isValidSeqName(name))
387 for (String seqRef : seqRefs)
389 queryBuilder.append("text:").append(seqRef).append(" OR ");
393 int endIndex = queryBuilder.lastIndexOf(" OR ");
394 if (queryBuilder.toString().length() < 6)
398 String query = queryBuilder.toString().substring(0, endIndex);
403 * Remove the following special characters from input string +, -, &, !, (, ),
404 * {, }, [, ], ^, ", ~, *, ?, :, \
409 static String sanitizeSeqName(String seqName)
411 Objects.requireNonNull(seqName);
412 return seqName.replaceAll("\\[\\d*\\]", "")
413 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
417 * Ensures sequence ref names are not less than 3 characters and does not
418 * contain a database name
423 static boolean isValidSeqName(String seqName)
425 // System.out.println("seqName : " + seqName);
426 String ignoreList = "pdb,uniprot,swiss-prot";
427 if (seqName.length() < 3)
431 if (seqName.contains(":"))
435 seqName = seqName.toLowerCase();
436 for (String ignoredEntry : ignoreList.split(","))
438 if (seqName.contains(ignoredEntry))
446 static String getDBRefId(DBRefEntry dbRef)
448 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
453 * Filters a given list of discovered structures based on supplied argument
455 * @param fieldToFilterBy
456 * the field to filter by
458 void filterResultSet(final String fieldToFilterBy)
460 Thread filterThread = new Thread(new Runnable()
465 long startTime = System.currentTimeMillis();
466 pdbRestClient = PDBFTSRestClient.getInstance();
467 lbl_loading.setVisible(true);
468 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
469 .getStructureSummaryFields();
470 Collection<FTSData> filteredResponse = new HashSet<>();
471 HashSet<String> errors = new HashSet<>();
473 for (SequenceI seq : selectedSequences)
475 FTSRestRequest pdbRequest = new FTSRestRequest();
476 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
478 pdbRequest.setAllowEmptySeq(false);
479 pdbRequest.setResponseSize(1);
480 pdbRequest.setFieldToSearchBy("(");
481 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
482 pdbRequest.setWantedFields(wantedFields);
483 pdbRequest.setAssociatedSequence(seq);
484 pdbRequest.setFacet(true);
485 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
486 pdbRequest.setFacetPivotMinCount(1);
490 pdbRequest.setAllowEmptySeq(false);
491 pdbRequest.setResponseSize(1);
492 pdbRequest.setFieldToSearchBy("(");
493 pdbRequest.setFieldToSortBy(fieldToFilterBy,
494 !chk_invertFilter.isSelected());
495 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
496 pdbRequest.setWantedFields(wantedFields);
497 pdbRequest.setAssociatedSequence(seq);
499 FTSRestResponse resultList;
502 resultList = pdbRestClient.executeRequest(pdbRequest);
503 } catch (Exception e)
506 errors.add(e.getMessage());
509 lastPdbRequest = pdbRequest;
510 if (resultList.getSearchSummary() != null
511 && !resultList.getSearchSummary().isEmpty())
513 filteredResponse.addAll(resultList.getSearchSummary());
517 String totalTime = (System.currentTimeMillis() - startTime)
519 if (!filteredResponse.isEmpty())
521 final int filterResponseCount = filteredResponse.size();
522 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
523 reorderedStructuresSet.addAll(filteredResponse);
524 reorderedStructuresSet.addAll(discoveredStructuresSet);
525 getResultTable().setModel(FTSRestResponse
526 .getTableModel(lastPdbRequest, reorderedStructuresSet));
528 FTSRestResponse.configureTableColumn(getResultTable(),
529 wantedFields, tempUserPrefs);
530 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
531 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
532 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
533 // Update table selection model here
534 getResultTable().addRowSelectionInterval(0,
535 filterResponseCount - 1);
536 mainFrame.setTitle(MessageManager.formatMessage(
537 "label.structure_chooser_filter_time", totalTime));
541 mainFrame.setTitle(MessageManager.formatMessage(
542 "label.structure_chooser_filter_time", totalTime));
543 if (errors.size() > 0)
545 StringBuilder errorMsg = new StringBuilder();
546 for (String error : errors)
548 errorMsg.append(error).append("\n");
550 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
551 MessageManager.getString("label.pdb_web-service_error"),
552 JvOptionPane.ERROR_MESSAGE);
556 lbl_loading.setVisible(false);
558 validateSelections();
561 filterThread.start();
565 * Handles action event for btn_pdbFromFile
568 protected void pdbFromFile_actionPerformed()
570 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and StructureChooser
572 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
573 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
574 chooser.setFileView(new jalview.io.JalviewFileView());
575 chooser.setDialogTitle(
576 MessageManager.formatMessage("label.select_pdb_file_for",
577 selectedSequence.getDisplayId(false)));
578 chooser.setToolTipText(MessageManager.formatMessage(
579 "label.load_pdb_file_associate_with_sequence",
580 selectedSequence.getDisplayId(false)));
582 int value = chooser.showOpenDialog(null);
583 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
585 selectedPdbFileName = chooser.getSelectedFile().getPath();
586 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
587 validateSelections();
592 * Populates the filter combo-box options dynamically depending on discovered
595 protected void populateFilterComboBox(boolean haveData,
596 boolean cachedPDBExist)
599 * temporarily suspend the change listener behaviour
601 cmb_filterOption.removeItemListener(this);
603 cmb_filterOption.removeAllItems();
606 cmb_filterOption.addItem(new FilterOption(
607 MessageManager.getString("label.best_quality"),
608 "overall_quality", VIEWS_FILTER, false));
609 cmb_filterOption.addItem(new FilterOption(
610 MessageManager.getString("label.best_resolution"),
611 "resolution", VIEWS_FILTER, false));
612 cmb_filterOption.addItem(new FilterOption(
613 MessageManager.getString("label.most_protein_chain"),
614 "number_of_protein_chains", VIEWS_FILTER, false));
615 cmb_filterOption.addItem(new FilterOption(
616 MessageManager.getString("label.most_bound_molecules"),
617 "number_of_bound_molecules", VIEWS_FILTER, false));
618 cmb_filterOption.addItem(new FilterOption(
619 MessageManager.getString("label.most_polymer_residues"),
620 "number_of_polymer_residues", VIEWS_FILTER, true));
622 cmb_filterOption.addItem(
623 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
624 "-", VIEWS_ENTER_ID, false));
625 cmb_filterOption.addItem(
626 new FilterOption(MessageManager.getString("label.from_file"),
627 "-", VIEWS_FROM_FILE, false));
631 FilterOption cachedOption = new FilterOption(
632 MessageManager.getString("label.cached_structures"),
633 "-", VIEWS_LOCAL_PDB, false);
634 cmb_filterOption.addItem(cachedOption);
635 cmb_filterOption.setSelectedItem(cachedOption);
638 cmb_filterOption.addItemListener(this);
642 * Updates the displayed view based on the selected filter option
644 protected void updateCurrentView()
646 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
648 layout_switchableViews.show(pnl_switchableViews,
649 selectedFilterOpt.getView());
650 String filterTitle = mainFrame.getTitle();
651 mainFrame.setTitle(frameTitle);
652 chk_invertFilter.setVisible(false);
653 if (selectedFilterOpt.getView() == VIEWS_FILTER)
655 mainFrame.setTitle(filterTitle);
656 chk_invertFilter.setVisible(true);
657 filterResultSet(selectedFilterOpt.getValue());
659 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
660 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
662 mainFrame.setTitle(MessageManager
663 .getString("label.structure_chooser_manual_association"));
664 idInputAssSeqPanel.loadCmbAssSeq();
665 fileChooserAssSeqPanel.loadCmbAssSeq();
667 validateSelections();
671 * Validates user selection and enables the 'Add' and 'New View' buttons if
672 * all parameters are correct (the Add button will only be visible if there is
673 * at least one existing structure viewer open). This basically means at least
674 * one structure selected and no error messages.
676 * The 'Superpose Structures' option is enabled if either more than one
677 * structure is selected, or the 'Add' to existing view option is enabled, and
678 * disabled if the only option is to open a new view of a single structure.
681 protected void validateSelections()
683 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
685 btn_add.setEnabled(false);
686 String currentView = selectedFilterOpt.getView();
687 int selectedCount = 0;
688 if (currentView == VIEWS_FILTER)
690 selectedCount = getResultTable().getSelectedRows().length;
691 if (selectedCount > 0)
693 btn_add.setEnabled(true);
696 else if (currentView == VIEWS_LOCAL_PDB)
698 selectedCount = tbl_local_pdb.getSelectedRows().length;
699 if (selectedCount > 0)
701 btn_add.setEnabled(true);
704 else if (currentView == VIEWS_ENTER_ID)
706 validateAssociationEnterPdb();
708 else if (currentView == VIEWS_FROM_FILE)
710 validateAssociationFromFile();
713 btn_newView.setEnabled(btn_add.isEnabled());
716 * enable 'Superpose' option if more than one structure is selected,
717 * or there are view(s) available to add structure(s) to
720 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
724 * Validates inputs from the Manual PDB entry panel
726 protected void validateAssociationEnterPdb()
728 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
729 .getCmb_assSeq().getSelectedItem();
730 lbl_pdbManualFetchStatus.setIcon(errorImage);
731 lbl_pdbManualFetchStatus.setToolTipText("");
732 if (txt_search.getText().length() > 0)
734 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
735 MessageManager.formatMessage("info.no_pdb_entry_found_for",
736 txt_search.getText())));
739 if (errorWarning.length() > 0)
741 lbl_pdbManualFetchStatus.setIcon(warningImage);
742 lbl_pdbManualFetchStatus.setToolTipText(
743 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
746 if (selectedSequences.length == 1 || !assSeqOpt.getName()
747 .equalsIgnoreCase("-Select Associated Seq-"))
749 txt_search.setEnabled(true);
752 btn_add.setEnabled(true);
753 lbl_pdbManualFetchStatus.setToolTipText("");
754 lbl_pdbManualFetchStatus.setIcon(goodImage);
759 txt_search.setEnabled(false);
760 lbl_pdbManualFetchStatus.setIcon(errorImage);
765 * Validates inputs for the manual PDB file selection options
767 protected void validateAssociationFromFile()
769 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
770 .getCmb_assSeq().getSelectedItem();
771 lbl_fromFileStatus.setIcon(errorImage);
772 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
773 .getName().equalsIgnoreCase("-Select Associated Seq-")))
775 btn_pdbFromFile.setEnabled(true);
776 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
778 btn_add.setEnabled(true);
779 lbl_fromFileStatus.setIcon(goodImage);
784 btn_pdbFromFile.setEnabled(false);
785 lbl_fromFileStatus.setIcon(errorImage);
790 protected void cmbAssSeqStateChanged()
792 validateSelections();
796 * Handles the state change event for the 'filter' combo-box and 'invert'
800 protected void stateChanged(ItemEvent e)
802 if (e.getSource() instanceof JCheckBox)
808 if (e.getStateChange() == ItemEvent.SELECTED)
817 * select structures for viewing by their PDB IDs
820 * @return true if structures were found and marked as selected
822 public boolean selectStructure(String... pdbids)
824 boolean found = false;
826 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
828 String currentView = selectedFilterOpt.getView();
829 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
830 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
832 if (restable == null)
834 // can't select (enter PDB ID, or load file - need to also select which
835 // sequence to associate with)
839 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
840 for (int r = 0; r < restable.getRowCount(); r++)
842 for (int p = 0; p < pdbids.length; p++)
844 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
845 .equalsIgnoreCase(pdbids[p]))
847 restable.setRowSelectionInterval(r, r);
856 * Handles the 'New View' action
859 protected void newView_ActionPerformed()
861 targetView.setSelectedItem(null);
862 showStructures(false);
866 * Handles the 'Add to existing viewer' action
869 protected void add_ActionPerformed()
871 showStructures(false);
875 * structure viewer opened by this dialog, or null
877 private StructureViewer sViewer = null;
879 public void showStructures(boolean waitUntilFinished)
882 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
884 final int preferredHeight = pnl_filter.getHeight();
886 Runnable viewStruc = new Runnable()
891 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
893 String currentView = selectedFilterOpt.getView();
894 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
897 if (currentView == VIEWS_FILTER)
899 int pdbIdColIndex = restable.getColumn("PDB Id")
901 int refSeqColIndex = restable.getColumn("Ref Sequence")
903 int[] selectedRows = restable.getSelectedRows();
904 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
906 List<SequenceI> selectedSeqsToView = new ArrayList<>();
907 for (int row : selectedRows)
909 String pdbIdStr = restable
910 .getValueAt(row, pdbIdColIndex).toString();
911 SequenceI selectedSeq = (SequenceI) restable
912 .getValueAt(row, refSeqColIndex);
913 selectedSeqsToView.add(selectedSeq);
914 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
915 if (pdbEntry == null)
917 pdbEntry = getFindEntry(pdbIdStr,
918 selectedSeq.getAllPDBEntries());
921 if (pdbEntry == null)
923 pdbEntry = new PDBEntry();
924 pdbEntry.setId(pdbIdStr);
925 pdbEntry.setType(PDBEntry.Type.PDB);
926 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
928 pdbEntriesToView[count++] = pdbEntry;
930 SequenceI[] selectedSeqs = selectedSeqsToView
931 .toArray(new SequenceI[selectedSeqsToView.size()]);
932 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
935 else if (currentView == VIEWS_LOCAL_PDB)
937 int[] selectedRows = tbl_local_pdb.getSelectedRows();
938 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
940 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
942 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
944 List<SequenceI> selectedSeqsToView = new ArrayList<>();
945 for (int row : selectedRows)
947 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
949 pdbEntriesToView[count++] = pdbEntry;
950 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
951 .getValueAt(row, refSeqColIndex);
952 selectedSeqsToView.add(selectedSeq);
954 SequenceI[] selectedSeqs = selectedSeqsToView
955 .toArray(new SequenceI[selectedSeqsToView.size()]);
956 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
959 else if (currentView == VIEWS_ENTER_ID)
961 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
962 .getCmb_assSeq().getSelectedItem()).getSequence();
963 if (userSelectedSeq != null)
965 selectedSequence = userSelectedSeq;
967 String pdbIdStr = txt_search.getText();
968 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
969 if (pdbEntry == null)
971 pdbEntry = new PDBEntry();
972 if (pdbIdStr.split(":").length > 1)
974 pdbEntry.setId(pdbIdStr.split(":")[0]);
975 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
979 pdbEntry.setId(pdbIdStr);
981 pdbEntry.setType(PDBEntry.Type.PDB);
982 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
985 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
986 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
988 { selectedSequence });
990 else if (currentView == VIEWS_FROM_FILE)
992 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
993 .getCmb_assSeq().getSelectedItem()).getSequence();
994 if (userSelectedSeq != null)
996 selectedSequence = userSelectedSeq;
998 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
999 .associatePdbWithSeq(selectedPdbFileName,
1000 DataSourceType.FILE, selectedSequence, true,
1003 sViewer = launchStructureViewer(
1007 { selectedSequence });
1009 SwingUtilities.invokeLater(new Runnable()
1014 closeAction(preferredHeight);
1015 mainFrame.dispose();
1020 Thread runner = new Thread(viewStruc);
1022 if (waitUntilFinished)
1024 while (sViewer == null ? runner.isAlive()
1025 : (sViewer.sview == null ? true
1026 : !sViewer.sview.hasMapping()))
1031 } catch (InterruptedException ie)
1039 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1041 Objects.requireNonNull(id);
1042 Objects.requireNonNull(pdbEntries);
1043 PDBEntry foundEntry = null;
1044 for (PDBEntry entry : pdbEntries)
1046 if (entry.getId().equalsIgnoreCase(id))
1055 * Answers a structure viewer (new or existing) configured to superimpose
1056 * added structures or not according to the user's choice
1061 StructureViewer getTargetedStructureViewer(
1062 StructureSelectionManager ssm)
1064 Object sv = targetView.getSelectedItem();
1066 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1070 * Adds PDB structures to a new or existing structure viewer
1073 * @param pdbEntriesToView
1078 private StructureViewer launchStructureViewer(
1079 StructureSelectionManager ssm,
1080 final PDBEntry[] pdbEntriesToView,
1081 final AlignmentPanel alignPanel, SequenceI[] sequences)
1083 long progressId = sequences.hashCode();
1084 setProgressBar(MessageManager
1085 .getString("status.launching_3d_structure_viewer"), progressId);
1086 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1087 boolean superimpose = chk_superpose.isSelected();
1088 theViewer.setSuperpose(superimpose);
1091 * remember user's choice of superimpose or not
1093 Cache.setProperty(AUTOSUPERIMPOSE,
1094 Boolean.valueOf(superimpose).toString());
1096 setProgressBar(null, progressId);
1097 if (SiftsSettings.isMapWithSifts())
1099 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1101 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1102 // real PDB ID. For moment, we can also safely do this if there is already
1103 // a known mapping between the PDBEntry and the sequence.
1104 for (SequenceI seq : sequences)
1106 PDBEntry pdbe = pdbEntriesToView[p++];
1107 if (pdbe != null && pdbe.getFile() != null)
1109 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1110 if (smm != null && smm.length > 0)
1112 for (StructureMapping sm : smm)
1114 if (sm.getSequence() == seq)
1121 if (seq.getPrimaryDBRefs().isEmpty())
1123 seqsWithoutSourceDBRef.add(seq);
1127 if (!seqsWithoutSourceDBRef.isEmpty())
1129 int y = seqsWithoutSourceDBRef.size();
1130 setProgressBar(MessageManager.formatMessage(
1131 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1133 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1134 .toArray(new SequenceI[y]);
1135 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1136 dbRefFetcher.fetchDBRefs(true);
1138 setProgressBar("Fetch complete.", progressId); // todo i18n
1141 if (pdbEntriesToView.length > 1)
1143 setProgressBar(MessageManager.getString(
1144 "status.fetching_3d_structures_for_selected_entries"),
1146 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1150 setProgressBar(MessageManager.formatMessage(
1151 "status.fetching_3d_structures_for",
1152 pdbEntriesToView[0].getId()),progressId);
1153 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1155 setProgressBar(null, progressId);
1156 // remember the last viewer we used...
1157 lastTargetedView = theViewer;
1162 * Populates the combo-box used in associating manually fetched structures to
1163 * a unique sequence when more than one sequence selection is made.
1166 protected void populateCmbAssociateSeqOptions(
1167 JComboBox<AssociateSeqOptions> cmb_assSeq,
1168 JLabel lbl_associateSeq)
1170 cmb_assSeq.removeAllItems();
1172 new AssociateSeqOptions("-Select Associated Seq-", null));
1173 lbl_associateSeq.setVisible(false);
1174 if (selectedSequences.length > 1)
1176 for (SequenceI seq : selectedSequences)
1178 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1183 String seqName = selectedSequence.getDisplayId(false);
1184 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1185 lbl_associateSeq.setText(seqName);
1186 lbl_associateSeq.setVisible(true);
1187 cmb_assSeq.setVisible(false);
1191 protected boolean isStructuresDiscovered()
1193 return discoveredStructuresSet != null
1194 && !discoveredStructuresSet.isEmpty();
1197 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes this.
1198 // Doing a search for "1" or "1c" is valuable?
1199 // Those work but are enormously slow.
1202 protected void txt_search_ActionPerformed()
1204 String text = txt_search.getText().trim();
1205 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();
1253 protected void tabRefresh()
1255 if (selectedSequences != null)
1257 Thread refreshThread = new Thread(new Runnable()
1262 fetchStructuresMetaData();
1264 ((FilterOption) cmb_filterOption.getSelectedItem())
1268 refreshThread.start();
1272 public class PDBEntryTableModel extends AbstractTableModel
1274 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1277 private List<CachedPDB> pdbEntries;
1279 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1281 this.pdbEntries = new ArrayList<>(pdbEntries);
1285 public String getColumnName(int columnIndex)
1287 return columns[columnIndex];
1291 public int getRowCount()
1293 return pdbEntries.size();
1297 public int getColumnCount()
1299 return columns.length;
1303 public boolean isCellEditable(int row, int column)
1309 public Object getValueAt(int rowIndex, int columnIndex)
1311 Object value = "??";
1312 CachedPDB entry = pdbEntries.get(rowIndex);
1313 switch (columnIndex)
1316 value = entry.getSequence();
1319 value = entry.getPdbEntry();
1322 value = entry.getPdbEntry().getChainCode() == null ? "_"
1323 : entry.getPdbEntry().getChainCode();
1326 value = entry.getPdbEntry().getType();
1329 value = entry.getPdbEntry().getFile();
1336 public Class<?> getColumnClass(int columnIndex)
1338 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1341 public CachedPDB getPDBEntryAt(int row)
1343 return pdbEntries.get(row);
1348 private class CachedPDB
1350 private SequenceI sequence;
1352 private PDBEntry pdbEntry;
1354 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1356 this.sequence = sequence;
1357 this.pdbEntry = pdbEntry;
1360 public SequenceI getSequence()
1365 public PDBEntry getPdbEntry()
1372 private IProgressIndicator progressBar;
1375 public void setProgressBar(String message, long id)
1377 progressBar.setProgressBar(message, id);
1381 public void registerHandler(long id, IProgressIndicatorHandler handler)
1383 progressBar.registerHandler(id, handler);
1387 public boolean operationInProgress()
1389 return progressBar.operationInProgress();
1392 public JalviewStructureDisplayI getOpenedStructureViewer()
1394 return sViewer == null ? null : sViewer.sview;