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.StructureSelectionManager;
40 import jalview.util.MessageManager;
42 import java.awt.event.ItemEvent;
43 import java.util.ArrayList;
44 import java.util.Collection;
45 import java.util.HashSet;
46 import java.util.LinkedHashSet;
47 import java.util.List;
48 import java.util.Objects;
50 import java.util.Vector;
52 import javax.swing.JCheckBox;
53 import javax.swing.JComboBox;
54 import javax.swing.JLabel;
55 import javax.swing.JTable;
56 import javax.swing.SwingUtilities;
57 import javax.swing.table.AbstractTableModel;
60 * Provides the behaviors for the Structure chooser Panel
65 @SuppressWarnings("serial")
66 public class StructureChooser extends GStructureChooser
67 implements IProgressIndicator
69 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
71 private static final int MAX_QLENGTH = 7820;
73 protected SequenceI selectedSequence;
75 public SequenceI[] selectedSequences;
77 private IProgressIndicator progressIndicator;
79 protected Collection<FTSData> discoveredStructuresSet;
81 protected FTSRestRequest lastPdbRequest;
83 protected FTSRestClientI pdbRestClient;
85 protected String selectedPdbFileName;
87 protected boolean isValidPBDEntry;
89 protected boolean cachedPDBExists;
91 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
95 this.selectedSequence = selectedSeq;
96 this.selectedSequences = selectedSeqs;
97 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
102 * Initializes parameters used by the Structure Chooser Panel
104 protected void init()
106 if (!Jalview.isHeadlessMode())
108 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
111 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
113 // ensure a filter option is in force for search
114 populateFilterComboBox(true, cachedPDBExists);
115 Thread discoverPDBStructuresThread = new Thread(new Runnable()
120 long startTime = System.currentTimeMillis();
121 updateProgressIndicator(MessageManager
122 .getString("status.loading_cached_pdb_entries"), startTime);
123 loadLocalCachedPDBEntries();
124 updateProgressIndicator(null, startTime);
125 updateProgressIndicator(MessageManager.getString(
126 "status.searching_for_pdb_structures"), startTime);
127 fetchStructuresMetaData();
128 // revise filter options if no results were found
129 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
130 discoverStructureViews();
131 updateProgressIndicator(null, startTime);
132 mainFrame.setVisible(true);
136 discoverPDBStructuresThread.start();
140 * Builds a drop-down choice list of existing structure viewers to which new
141 * structures may be added. If this list is empty then it, and the 'Add'
142 * button, are hidden.
144 protected void discoverStructureViews()
146 if (Desktop.getInstance() != null)
148 targetView.removeAllItems();
149 Desktop d = Desktop.getInstance();
150 if (d.lastTargetedView != null && !d.lastTargetedView.isVisible())
152 d.lastTargetedView = null;
154 int linkedViewsAt = 0;
155 for (StructureViewerBase view : Desktop.getInstance()
156 .getStructureViewers(null, null))
158 StructureViewer viewHandler = (d.lastTargetedView != null
159 && d.lastTargetedView.sview == view) ? d.lastTargetedView
160 : StructureViewer.reconfigure(view);
162 if (view.isLinkedWith(ap))
164 targetView.insertItemAt(viewHandler,
169 targetView.addItem(viewHandler);
174 * show option to Add to viewer if at least 1 viewer found
176 targetView.setVisible(false);
177 if (targetView.getItemCount() > 0)
179 targetView.setVisible(true);
180 if (d.lastTargetedView != null)
182 targetView.setSelectedItem(d.lastTargetedView);
186 targetView.setSelectedIndex(0);
189 btn_add.setVisible(targetView.isVisible());
194 * Updates the progress indicator with the specified message
197 * displayed message for the operation
199 * unique handle for this indicator
201 protected void updateProgressIndicator(String message, long id)
203 if (progressIndicator != null)
205 progressIndicator.setProgressBar(message, id);
210 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
213 void fetchStructuresMetaData()
215 long startTime = System.currentTimeMillis();
216 pdbRestClient = PDBFTSRestClient.getInstance();
217 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
218 .getStructureSummaryFields();
220 discoveredStructuresSet = new LinkedHashSet<>();
221 HashSet<String> errors = new HashSet<>();
222 for (SequenceI seq : selectedSequences)
224 FTSRestRequest pdbRequest = new FTSRestRequest();
225 pdbRequest.setAllowEmptySeq(false);
226 pdbRequest.setResponseSize(500);
227 pdbRequest.setFieldToSearchBy("(");
228 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
230 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
231 !chk_invertFilter.isSelected());
232 pdbRequest.setWantedFields(wantedFields);
233 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
234 pdbRequest.setAssociatedSequence(seq);
235 FTSRestResponse resultList;
238 resultList = pdbRestClient.executeRequest(pdbRequest);
239 } catch (Exception e)
242 errors.add(e.getMessage());
245 lastPdbRequest = pdbRequest;
246 if (resultList.getSearchSummary() != null
247 && !resultList.getSearchSummary().isEmpty())
249 discoveredStructuresSet.addAll(resultList.getSearchSummary());
253 int noOfStructuresFound = 0;
254 String totalTime = (System.currentTimeMillis() - startTime)
256 if (discoveredStructuresSet != null
257 && !discoveredStructuresSet.isEmpty())
259 getResultTable().setModel(FTSRestResponse
260 .getTableModel(lastPdbRequest, discoveredStructuresSet));
261 noOfStructuresFound = discoveredStructuresSet.size();
262 mainFrame.setTitle(MessageManager.formatMessage(
263 "label.structure_chooser_no_of_structures",
264 noOfStructuresFound, totalTime));
268 mainFrame.setTitle(MessageManager
269 .getString("label.structure_chooser_manual_association"));
270 if (errors.size() > 0)
272 StringBuilder errorMsg = new StringBuilder();
273 for (String error : errors)
275 errorMsg.append(error).append("\n");
277 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
278 MessageManager.getString("label.pdb_web-service_error"),
279 JvOptionPane.ERROR_MESSAGE);
284 protected void loadLocalCachedPDBEntries()
286 ArrayList<CachedPDB> entries = new ArrayList<>();
287 for (SequenceI seq : selectedSequences)
289 if (seq.getDatasetSequence() != null
290 && seq.getDatasetSequence().getAllPDBEntries() != null)
292 for (PDBEntry pdbEntry : seq.getDatasetSequence()
295 if (pdbEntry.getFile() != null)
297 entries.add(new CachedPDB(seq, pdbEntry));
302 cachedPDBExists = !entries.isEmpty();
303 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
304 tbl_local_pdb.setModel(tableModelx);
308 * Builds a query string for a given sequences using its DBRef entries
311 * the sequences to build a query for
312 * @return the built query string
315 static String buildQuery(SequenceI seq)
317 boolean isPDBRefsFound = false;
318 boolean isUniProtRefsFound = false;
319 StringBuilder queryBuilder = new StringBuilder();
320 Set<String> seqRefs = new LinkedHashSet<>();
322 if (seq.getAllPDBEntries() != null
323 && queryBuilder.length() < MAX_QLENGTH)
325 for (PDBEntry entry : seq.getAllPDBEntries())
327 if (isValidSeqName(entry.getId()))
329 queryBuilder.append("pdb_id:").append(entry.getId().toLowerCase())
331 isPDBRefsFound = true;
336 List<DBRefEntry> refs = seq.getDBRefs();
337 if (refs != null && refs.size() != 0)
339 for (int ib = 0, nb = refs.size(); ib < nb; ib++)
341 DBRefEntry dbRef = refs.get(ib);
342 if (isValidSeqName(getDBRefId(dbRef))
343 && queryBuilder.length() < MAX_QLENGTH)
345 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
347 queryBuilder.append("uniprot_accession:")
348 .append(getDBRefId(dbRef)).append(" OR ");
349 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
351 isUniProtRefsFound = true;
353 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
356 queryBuilder.append("pdb_id:")
357 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
358 isPDBRefsFound = true;
362 seqRefs.add(getDBRefId(dbRef));
368 if (!isPDBRefsFound && !isUniProtRefsFound)
370 String seqName = seq.getName();
371 seqName = sanitizeSeqName(seqName);
372 String[] names = seqName.toLowerCase().split("\\|");
373 for (String name : names)
375 // System.out.println("Found name : " + name);
377 if (isValidSeqName(name))
383 for (String seqRef : seqRefs)
385 queryBuilder.append("text:").append(seqRef).append(" OR ");
389 int endIndex = queryBuilder.lastIndexOf(" OR ");
390 if (queryBuilder.toString().length() < 6)
394 String query = queryBuilder.toString().substring(0, endIndex);
399 * Remove the following special characters from input string +, -, &, !, (, ),
400 * {, }, [, ], ^, ", ~, *, ?, :, \
405 static String sanitizeSeqName(String seqName)
407 Objects.requireNonNull(seqName);
408 return seqName.replaceAll("\\[\\d*\\]", "")
409 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
413 * Ensures sequence ref names are not less than 3 characters and does not
414 * contain a database name
419 static boolean isValidSeqName(String seqName)
421 // System.out.println("seqName : " + seqName);
422 String ignoreList = "pdb,uniprot,swiss-prot";
423 if (seqName.length() < 3)
427 if (seqName.contains(":"))
431 seqName = seqName.toLowerCase();
432 for (String ignoredEntry : ignoreList.split(","))
434 if (seqName.contains(ignoredEntry))
442 static String getDBRefId(DBRefEntry dbRef)
444 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
449 * Filters a given list of discovered structures based on supplied argument
451 * @param fieldToFilterBy
452 * the field to filter by
454 void filterResultSet(final String fieldToFilterBy)
456 Thread filterThread = new Thread(new Runnable()
461 long startTime = System.currentTimeMillis();
462 pdbRestClient = PDBFTSRestClient.getInstance();
463 lbl_loading.setVisible(true);
464 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
465 .getStructureSummaryFields();
466 Collection<FTSData> filteredResponse = new HashSet<>();
467 HashSet<String> errors = new HashSet<>();
469 for (SequenceI seq : selectedSequences)
471 FTSRestRequest pdbRequest = new FTSRestRequest();
472 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
474 pdbRequest.setAllowEmptySeq(false);
475 pdbRequest.setResponseSize(1);
476 pdbRequest.setFieldToSearchBy("(");
477 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
478 pdbRequest.setWantedFields(wantedFields);
479 pdbRequest.setAssociatedSequence(seq);
480 pdbRequest.setFacet(true);
481 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
482 pdbRequest.setFacetPivotMinCount(1);
486 pdbRequest.setAllowEmptySeq(false);
487 pdbRequest.setResponseSize(1);
488 pdbRequest.setFieldToSearchBy("(");
489 pdbRequest.setFieldToSortBy(fieldToFilterBy,
490 !chk_invertFilter.isSelected());
491 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
492 pdbRequest.setWantedFields(wantedFields);
493 pdbRequest.setAssociatedSequence(seq);
495 FTSRestResponse resultList;
498 resultList = pdbRestClient.executeRequest(pdbRequest);
499 } catch (Exception e)
502 errors.add(e.getMessage());
505 lastPdbRequest = pdbRequest;
506 if (resultList.getSearchSummary() != null
507 && !resultList.getSearchSummary().isEmpty())
509 filteredResponse.addAll(resultList.getSearchSummary());
513 String totalTime = (System.currentTimeMillis() - startTime)
515 if (!filteredResponse.isEmpty())
517 final int filterResponseCount = filteredResponse.size();
518 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
519 reorderedStructuresSet.addAll(filteredResponse);
520 reorderedStructuresSet.addAll(discoveredStructuresSet);
521 getResultTable().setModel(FTSRestResponse
522 .getTableModel(lastPdbRequest, reorderedStructuresSet));
524 FTSRestResponse.configureTableColumn(getResultTable(),
525 wantedFields, tempUserPrefs);
526 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
527 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
528 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
529 // Update table selection model here
530 getResultTable().addRowSelectionInterval(0,
531 filterResponseCount - 1);
532 mainFrame.setTitle(MessageManager.formatMessage(
533 "label.structure_chooser_filter_time", totalTime));
537 mainFrame.setTitle(MessageManager.formatMessage(
538 "label.structure_chooser_filter_time", totalTime));
539 if (errors.size() > 0)
541 StringBuilder errorMsg = new StringBuilder();
542 for (String error : errors)
544 errorMsg.append(error).append("\n");
546 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
547 MessageManager.getString("label.pdb_web-service_error"),
548 JvOptionPane.ERROR_MESSAGE);
552 lbl_loading.setVisible(false);
554 validateSelections();
557 filterThread.start();
561 * Handles action event for btn_pdbFromFile
564 protected void pdbFromFile_actionPerformed()
566 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and StructureChooser
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 protected StructureViewer sViewer = null;
875 public void showStructures(boolean waitUntilFinished)
878 final int preferredHeight = pnl_filter.getHeight();
880 Runnable viewStruc = new Runnable()
885 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
887 String currentView = selectedFilterOpt.getView();
888 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
891 if (currentView == VIEWS_FILTER)
893 int pdbIdColIndex = restable.getColumn("PDB Id")
895 int refSeqColIndex = restable.getColumn("Ref Sequence")
897 int[] selectedRows = restable.getSelectedRows();
898 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
900 List<SequenceI> selectedSeqsToView = new ArrayList<>();
901 for (int row : selectedRows)
903 String pdbIdStr = restable
904 .getValueAt(row, pdbIdColIndex).toString();
905 SequenceI selectedSeq = (SequenceI) restable
906 .getValueAt(row, refSeqColIndex);
907 selectedSeqsToView.add(selectedSeq);
908 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
909 if (pdbEntry == null)
911 pdbEntry = getFindEntry(pdbIdStr,
912 selectedSeq.getAllPDBEntries());
915 if (pdbEntry == null)
917 pdbEntry = new PDBEntry();
918 pdbEntry.setId(pdbIdStr);
919 pdbEntry.setType(PDBEntry.Type.PDB);
920 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
922 pdbEntriesToView[count++] = pdbEntry;
924 SequenceI[] selectedSeqs = selectedSeqsToView
925 .toArray(new SequenceI[selectedSeqsToView.size()]);
926 sViewer = launchStructureViewer(ap, pdbEntriesToView,
929 else if (currentView == VIEWS_LOCAL_PDB)
931 int[] selectedRows = tbl_local_pdb.getSelectedRows();
932 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
934 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
936 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
938 List<SequenceI> selectedSeqsToView = new ArrayList<>();
939 for (int row : selectedRows)
941 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
943 pdbEntriesToView[count++] = pdbEntry;
944 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
945 .getValueAt(row, refSeqColIndex);
946 selectedSeqsToView.add(selectedSeq);
948 SequenceI[] selectedSeqs = selectedSeqsToView
949 .toArray(new SequenceI[selectedSeqsToView.size()]);
950 sViewer = launchStructureViewer(ap, pdbEntriesToView,
953 else if (currentView == VIEWS_ENTER_ID)
955 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
956 .getCmb_assSeq().getSelectedItem()).getSequence();
957 if (userSelectedSeq != null)
959 selectedSequence = userSelectedSeq;
961 String pdbIdStr = txt_search.getText();
962 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
963 if (pdbEntry == null)
965 pdbEntry = new PDBEntry();
966 if (pdbIdStr.split(":").length > 1)
968 pdbEntry.setId(pdbIdStr.split(":")[0]);
969 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
973 pdbEntry.setId(pdbIdStr);
975 pdbEntry.setType(PDBEntry.Type.PDB);
976 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
979 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
980 sViewer = launchStructureViewer(ap, pdbEntriesToView,
982 { selectedSequence });
984 else if (currentView == VIEWS_FROM_FILE)
986 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
987 .getCmb_assSeq().getSelectedItem()).getSequence();
988 if (userSelectedSeq != null)
990 selectedSequence = userSelectedSeq;
992 PDBEntry fileEntry = AssociatePdbFileWithSeq
993 .associatePdbWithSeq(selectedPdbFileName,
994 DataSourceType.FILE, selectedSequence, true);
996 sViewer = launchStructureViewer(
1000 { selectedSequence });
1002 SwingUtilities.invokeLater(new Runnable()
1007 closeAction(preferredHeight);
1008 mainFrame.dispose();
1013 Thread runner = new Thread(viewStruc);
1015 if (waitUntilFinished)
1017 while (sViewer == null ? runner.isAlive()
1018 : (sViewer.sview == null ? true
1019 : !sViewer.sview.hasMapping()))
1024 } catch (InterruptedException ie)
1032 protected PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1034 Objects.requireNonNull(id);
1035 Objects.requireNonNull(pdbEntries);
1036 PDBEntry foundEntry = null;
1037 for (PDBEntry entry : pdbEntries)
1039 if (entry.getId().equalsIgnoreCase(id))
1048 * Answers a structure viewer (new or existing) configured to superimpose
1049 * added structures or not according to the user's choice
1053 StructureViewer getTargetedStructureViewer()
1055 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1056 Object sv = (targetView == null ? null : targetView.getSelectedItem());
1058 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1062 * Adds PDB structures to a new or existing structure viewer
1065 * @param pdbEntriesToView
1067 * @param superimpose
1070 protected StructureViewer launchStructureViewer(
1071 AlignmentPanel ap, PDBEntry[] pdbEntriesToView,
1072 SequenceI[] selectedSeqs)
1074 boolean superimpose = chk_superpose.isSelected();
1076 * remember user's choice of superimpose or not
1078 Cache.setProperty(AUTOSUPERIMPOSE,
1079 Boolean.valueOf(superimpose).toString());
1080 return StructureViewer.launchStructureViewer(ap, pdbEntriesToView, selectedSeqs,
1081 superimpose, getTargetedStructureViewer(), progressBar);
1085 * Populates the combo-box used in associating manually fetched structures to
1086 * a unique sequence when more than one sequence selection is made.
1089 protected void populateCmbAssociateSeqOptions(
1090 JComboBox<AssociateSeqOptions> cmb_assSeq,
1091 JLabel lbl_associateSeq)
1093 cmb_assSeq.removeAllItems();
1095 new AssociateSeqOptions("-Select Associated Seq-", null));
1096 lbl_associateSeq.setVisible(false);
1097 if (selectedSequences.length > 1)
1099 for (SequenceI seq : selectedSequences)
1101 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1106 String seqName = selectedSequence.getDisplayId(false);
1107 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1108 lbl_associateSeq.setText(seqName);
1109 lbl_associateSeq.setVisible(true);
1110 cmb_assSeq.setVisible(false);
1114 protected boolean isStructuresDiscovered()
1116 return discoveredStructuresSet != null
1117 && !discoveredStructuresSet.isEmpty();
1120 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes this.
1121 // Doing a search for "1" or "1c" is valuable?
1122 // Those work but are enormously slow.
1125 protected void txt_search_ActionPerformed()
1127 String text = txt_search.getText().trim();
1128 if (text.length() >= PDB_ID_MIN)
1136 errorWarning.setLength(0);
1137 isValidPBDEntry = false;
1138 if (text.length() > 0)
1140 String searchTerm = text.toLowerCase();
1141 searchTerm = searchTerm.split(":")[0];
1142 // System.out.println(">>>>> search term : " + searchTerm);
1143 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1144 FTSRestRequest pdbRequest = new FTSRestRequest();
1145 pdbRequest.setAllowEmptySeq(false);
1146 pdbRequest.setResponseSize(1);
1147 pdbRequest.setFieldToSearchBy("(pdb_id:");
1148 pdbRequest.setWantedFields(wantedFields);
1149 pdbRequest.setSearchTerm(searchTerm + ")");
1150 pdbRequest.setAssociatedSequence(selectedSequence);
1151 pdbRestClient = PDBFTSRestClient.getInstance();
1152 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1153 FTSRestResponse resultList;
1156 resultList = pdbRestClient.executeRequest(pdbRequest);
1157 } catch (Exception e)
1159 errorWarning.append(e.getMessage());
1163 validateSelections();
1165 if (resultList.getSearchSummary() != null
1166 && resultList.getSearchSummary().size() > 0)
1168 isValidPBDEntry = true;
1171 validateSelections();
1178 protected void tabRefresh()
1180 if (selectedSequences != null)
1182 Thread refreshThread = new Thread(new Runnable()
1187 fetchStructuresMetaData();
1189 ((FilterOption) cmb_filterOption.getSelectedItem())
1193 refreshThread.start();
1197 public class PDBEntryTableModel extends AbstractTableModel
1199 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1202 private List<CachedPDB> pdbEntries;
1204 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1206 this.pdbEntries = new ArrayList<>(pdbEntries);
1210 public String getColumnName(int columnIndex)
1212 return columns[columnIndex];
1216 public int getRowCount()
1218 return pdbEntries.size();
1222 public int getColumnCount()
1224 return columns.length;
1228 public boolean isCellEditable(int row, int column)
1234 public Object getValueAt(int rowIndex, int columnIndex)
1236 Object value = "??";
1237 CachedPDB entry = pdbEntries.get(rowIndex);
1238 switch (columnIndex)
1241 value = entry.getSequence();
1244 value = entry.getPdbEntry();
1247 value = entry.getPdbEntry().getChainCode() == null ? "_"
1248 : entry.getPdbEntry().getChainCode();
1251 value = entry.getPdbEntry().getType();
1254 value = entry.getPdbEntry().getFile();
1261 public Class<?> getColumnClass(int columnIndex)
1263 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1266 public CachedPDB getPDBEntryAt(int row)
1268 return pdbEntries.get(row);
1273 private class CachedPDB
1275 private SequenceI sequence;
1277 private PDBEntry pdbEntry;
1279 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1281 this.sequence = sequence;
1282 this.pdbEntry = pdbEntry;
1285 public SequenceI getSequence()
1290 public PDBEntry getPdbEntry()
1297 private IProgressIndicator progressBar;
1300 public void setProgressBar(String message, long id)
1302 if (progressBar != null)
1304 progressBar.setProgressBar(message, id);
1309 public void registerHandler(long id, IProgressIndicatorHandler handler)
1311 progressBar.registerHandler(id, handler);
1315 public boolean operationInProgress()
1317 return progressBar.operationInProgress();
1320 public JalviewStructureDisplayI getOpenedStructureViewer()
1322 return sViewer == null ? null : sViewer.sview;