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 static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
71 private static int MAX_QLENGTH = 7820;
73 private SequenceI selectedSequence;
75 private SequenceI[] selectedSequences;
77 private IProgressIndicator progressIndicator;
79 private Collection<FTSData> discoveredStructuresSet;
81 private FTSRestRequest lastPdbRequest;
83 private FTSRestClientI pdbRestClient;
85 private String selectedPdbFileName;
87 private boolean isValidPBDEntry;
89 private boolean cachedPDBExists;
91 static StructureViewer lastTargetedView = null;
93 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
97 this.selectedSequence = selectedSeq;
98 this.selectedSequences = selectedSeqs;
99 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
104 * Initializes parameters used by the Structure Chooser Panel
106 protected void init()
108 if (!Jalview.isHeadlessMode())
110 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
113 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
115 // ensure a filter option is in force for search
116 populateFilterComboBox(true, cachedPDBExists);
117 Thread discoverPDBStructuresThread = new Thread(new Runnable()
122 long startTime = System.currentTimeMillis();
123 updateProgressIndicator(MessageManager
124 .getString("status.loading_cached_pdb_entries"), startTime);
125 loadLocalCachedPDBEntries();
126 updateProgressIndicator(null, startTime);
127 updateProgressIndicator(MessageManager.getString(
128 "status.searching_for_pdb_structures"), startTime);
129 fetchStructuresMetaData();
130 // revise filter options if no results were found
131 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
132 discoverStructureViews();
133 updateProgressIndicator(null, startTime);
134 mainFrame.setVisible(true);
138 discoverPDBStructuresThread.start();
142 * Builds a drop-down choice list of existing structure viewers to which new
143 * structures may be added. If this list is empty then it, and the 'Add'
144 * button, are hidden.
146 private void discoverStructureViews()
148 if (Desktop.getInstance() != null)
150 targetView.removeAllItems();
151 if (lastTargetedView != null && !lastTargetedView.isVisible())
153 lastTargetedView = null;
155 int linkedViewsAt = 0;
156 for (StructureViewerBase view : Desktop.getInstance()
157 .getStructureViewers(null, null))
159 StructureViewer viewHandler = (lastTargetedView != null
160 && lastTargetedView.sview == view) ? lastTargetedView
161 : StructureViewer.reconfigure(view);
163 if (view.isLinkedWith(ap))
165 targetView.insertItemAt(viewHandler, linkedViewsAt++);
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 (lastTargetedView != null)
182 targetView.setSelectedItem(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<>();
323 * note PDBs as DBRefEntry so they are not duplicated in query
325 Set<String> pdbids = new HashSet<>();
327 if (seq.getAllPDBEntries() != null
328 && queryBuilder.length() < MAX_QLENGTH)
330 for (PDBEntry entry : seq.getAllPDBEntries())
332 if (isValidSeqName(entry.getId()))
334 String id = entry.getId().toLowerCase();
335 queryBuilder.append("pdb_id:").append(id).append(" OR ");
336 isPDBRefsFound = true;
342 List<DBRefEntry> refs = seq.getDBRefs();
343 if (refs != null && refs.size() != 0)
345 for (int ib = 0, nb = refs.size(); ib < nb; ib++)
347 DBRefEntry dbRef = refs.get(ib);
348 if (isValidSeqName(getDBRefId(dbRef))
349 && queryBuilder.length() < MAX_QLENGTH)
351 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
353 queryBuilder.append("uniprot_accession:")
354 .append(getDBRefId(dbRef)).append(" OR ");
355 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
357 isUniProtRefsFound = true;
359 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
362 String id = getDBRefId(dbRef).toLowerCase();
363 if (!pdbids.contains(id))
365 queryBuilder.append("pdb_id:").append(id).append(" OR ");
366 isPDBRefsFound = true;
372 seqRefs.add(getDBRefId(dbRef));
378 if (!isPDBRefsFound && !isUniProtRefsFound)
380 String seqName = seq.getName();
381 seqName = sanitizeSeqName(seqName);
382 String[] names = seqName.toLowerCase().split("\\|");
383 for (String name : names)
385 // System.out.println("Found name : " + name);
387 if (isValidSeqName(name))
393 for (String seqRef : seqRefs)
395 queryBuilder.append("text:").append(seqRef).append(" OR ");
399 int endIndex = queryBuilder.lastIndexOf(" OR ");
400 if (queryBuilder.toString().length() < 6)
404 String query = queryBuilder.toString().substring(0, endIndex);
409 * Remove the following special characters from input string +, -, &, !, (, ),
410 * {, }, [, ], ^, ", ~, *, ?, :, \
415 static String sanitizeSeqName(String seqName)
417 Objects.requireNonNull(seqName);
418 return seqName.replaceAll("\\[\\d*\\]", "")
419 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
423 * Ensures sequence ref names are not less than 3 characters and does not
424 * contain a database name
429 static boolean isValidSeqName(String seqName)
431 // System.out.println("seqName : " + seqName);
432 String ignoreList = "pdb,uniprot,swiss-prot";
433 if (seqName.length() < 3)
437 if (seqName.contains(":"))
441 seqName = seqName.toLowerCase();
442 for (String ignoredEntry : ignoreList.split(","))
444 if (seqName.contains(ignoredEntry))
452 static String getDBRefId(DBRefEntry dbRef)
454 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
459 * Filters a given list of discovered structures based on supplied argument
461 * @param fieldToFilterBy
462 * the field to filter by
464 void filterResultSet(final String fieldToFilterBy)
466 Thread filterThread = new Thread(new Runnable()
471 long startTime = System.currentTimeMillis();
472 pdbRestClient = PDBFTSRestClient.getInstance();
473 lbl_loading.setVisible(true);
474 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
475 .getStructureSummaryFields();
476 Collection<FTSData> filteredResponse = new HashSet<>();
477 HashSet<String> errors = new HashSet<>();
479 for (SequenceI seq : selectedSequences)
481 FTSRestRequest pdbRequest = new FTSRestRequest();
482 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
484 pdbRequest.setAllowEmptySeq(false);
485 pdbRequest.setResponseSize(1);
486 pdbRequest.setFieldToSearchBy("(");
487 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
488 pdbRequest.setWantedFields(wantedFields);
489 pdbRequest.setAssociatedSequence(seq);
490 pdbRequest.setFacet(true);
491 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
492 pdbRequest.setFacetPivotMinCount(1);
496 pdbRequest.setAllowEmptySeq(false);
497 pdbRequest.setResponseSize(1);
498 pdbRequest.setFieldToSearchBy("(");
499 pdbRequest.setFieldToSortBy(fieldToFilterBy,
500 !chk_invertFilter.isSelected());
501 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
502 pdbRequest.setWantedFields(wantedFields);
503 pdbRequest.setAssociatedSequence(seq);
505 FTSRestResponse resultList;
508 resultList = pdbRestClient.executeRequest(pdbRequest);
509 } catch (Exception e)
512 errors.add(e.getMessage());
515 lastPdbRequest = pdbRequest;
516 if (resultList.getSearchSummary() != null
517 && !resultList.getSearchSummary().isEmpty())
519 filteredResponse.addAll(resultList.getSearchSummary());
523 String totalTime = (System.currentTimeMillis() - startTime)
525 if (!filteredResponse.isEmpty())
527 final int filterResponseCount = filteredResponse.size();
528 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
529 reorderedStructuresSet.addAll(filteredResponse);
530 reorderedStructuresSet.addAll(discoveredStructuresSet);
531 getResultTable().setModel(FTSRestResponse
532 .getTableModel(lastPdbRequest, reorderedStructuresSet));
534 FTSRestResponse.configureTableColumn(getResultTable(),
535 wantedFields, tempUserPrefs);
536 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
537 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
538 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
539 // Update table selection model here
540 getResultTable().addRowSelectionInterval(0,
541 filterResponseCount - 1);
542 mainFrame.setTitle(MessageManager.formatMessage(
543 "label.structure_chooser_filter_time", totalTime));
547 mainFrame.setTitle(MessageManager.formatMessage(
548 "label.structure_chooser_filter_time", totalTime));
549 if (errors.size() > 0)
551 StringBuilder errorMsg = new StringBuilder();
552 for (String error : errors)
554 errorMsg.append(error).append("\n");
556 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
557 MessageManager.getString("label.pdb_web-service_error"),
558 JvOptionPane.ERROR_MESSAGE);
562 lbl_loading.setVisible(false);
564 validateSelections();
567 filterThread.start();
571 * Handles action event for btn_pdbFromFile
574 protected void pdbFromFile_actionPerformed()
576 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
579 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
580 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
581 chooser.setFileView(new jalview.io.JalviewFileView());
582 chooser.setDialogTitle(
583 MessageManager.formatMessage("label.select_pdb_file_for",
584 selectedSequence.getDisplayId(false)));
585 chooser.setToolTipText(MessageManager.formatMessage(
586 "label.load_pdb_file_associate_with_sequence",
587 selectedSequence.getDisplayId(false)));
589 int value = chooser.showOpenDialog(null);
590 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
592 selectedPdbFileName = chooser.getSelectedFile().getPath();
593 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
594 validateSelections();
599 * Populates the filter combo-box options dynamically depending on discovered
602 protected void populateFilterComboBox(boolean haveData,
603 boolean cachedPDBExist)
606 * temporarily suspend the change listener behaviour
608 cmb_filterOption.removeItemListener(this);
610 cmb_filterOption.removeAllItems();
613 cmb_filterOption.addItem(new FilterOption(
614 MessageManager.getString("label.best_quality"),
615 "overall_quality", VIEWS_FILTER, false));
616 cmb_filterOption.addItem(new FilterOption(
617 MessageManager.getString("label.best_resolution"),
618 "resolution", VIEWS_FILTER, false));
619 cmb_filterOption.addItem(new FilterOption(
620 MessageManager.getString("label.most_protein_chain"),
621 "number_of_protein_chains", VIEWS_FILTER, false));
622 cmb_filterOption.addItem(new FilterOption(
623 MessageManager.getString("label.most_bound_molecules"),
624 "number_of_bound_molecules", VIEWS_FILTER, false));
625 cmb_filterOption.addItem(new FilterOption(
626 MessageManager.getString("label.most_polymer_residues"),
627 "number_of_polymer_residues", VIEWS_FILTER, true));
629 cmb_filterOption.addItem(
630 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
631 "-", VIEWS_ENTER_ID, false));
632 cmb_filterOption.addItem(
633 new FilterOption(MessageManager.getString("label.from_file"),
634 "-", VIEWS_FROM_FILE, false));
638 FilterOption cachedOption = new FilterOption(
639 MessageManager.getString("label.cached_structures"), "-",
640 VIEWS_LOCAL_PDB, false);
641 cmb_filterOption.addItem(cachedOption);
642 cmb_filterOption.setSelectedItem(cachedOption);
645 cmb_filterOption.addItemListener(this);
649 * Updates the displayed view based on the selected filter option
651 protected void updateCurrentView()
653 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
655 layout_switchableViews.show(pnl_switchableViews,
656 selectedFilterOpt.getView());
657 String filterTitle = mainFrame.getTitle();
658 mainFrame.setTitle(frameTitle);
659 chk_invertFilter.setVisible(false);
660 if (selectedFilterOpt.getView() == VIEWS_FILTER)
662 mainFrame.setTitle(filterTitle);
663 chk_invertFilter.setVisible(true);
664 filterResultSet(selectedFilterOpt.getValue());
666 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
667 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
669 mainFrame.setTitle(MessageManager
670 .getString("label.structure_chooser_manual_association"));
671 idInputAssSeqPanel.loadCmbAssSeq();
672 fileChooserAssSeqPanel.loadCmbAssSeq();
674 validateSelections();
678 * Validates user selection and enables the 'Add' and 'New View' buttons if
679 * all parameters are correct (the Add button will only be visible if there is
680 * at least one existing structure viewer open). This basically means at least
681 * one structure selected and no error messages.
683 * The 'Superpose Structures' option is enabled if either more than one
684 * structure is selected, or the 'Add' to existing view option is enabled, and
685 * disabled if the only option is to open a new view of a single structure.
688 protected void validateSelections()
690 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
692 btn_add.setEnabled(false);
693 String currentView = selectedFilterOpt.getView();
694 int selectedCount = 0;
695 if (currentView == VIEWS_FILTER)
697 selectedCount = getResultTable().getSelectedRows().length;
698 if (selectedCount > 0)
700 btn_add.setEnabled(true);
703 else if (currentView == VIEWS_LOCAL_PDB)
705 selectedCount = tbl_local_pdb.getSelectedRows().length;
706 if (selectedCount > 0)
708 btn_add.setEnabled(true);
711 else if (currentView == VIEWS_ENTER_ID)
713 validateAssociationEnterPdb();
715 else if (currentView == VIEWS_FROM_FILE)
717 validateAssociationFromFile();
720 btn_newView.setEnabled(btn_add.isEnabled());
723 * enable 'Superpose' option if more than one structure is selected,
724 * or there are view(s) available to add structure(s) to
727 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
731 * Validates inputs from the Manual PDB entry panel
733 protected void validateAssociationEnterPdb()
735 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
736 .getCmb_assSeq().getSelectedItem();
737 lbl_pdbManualFetchStatus.setIcon(errorImage);
738 lbl_pdbManualFetchStatus.setToolTipText("");
739 if (txt_search.getText().length() > 0)
741 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
742 MessageManager.formatMessage("info.no_pdb_entry_found_for",
743 txt_search.getText())));
746 if (errorWarning.length() > 0)
748 lbl_pdbManualFetchStatus.setIcon(warningImage);
749 lbl_pdbManualFetchStatus.setToolTipText(
750 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
753 if (selectedSequences.length == 1 || !assSeqOpt.getName()
754 .equalsIgnoreCase("-Select Associated Seq-"))
756 txt_search.setEnabled(true);
759 btn_add.setEnabled(true);
760 lbl_pdbManualFetchStatus.setToolTipText("");
761 lbl_pdbManualFetchStatus.setIcon(goodImage);
766 txt_search.setEnabled(false);
767 lbl_pdbManualFetchStatus.setIcon(errorImage);
772 * Validates inputs for the manual PDB file selection options
774 protected void validateAssociationFromFile()
776 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
777 .getCmb_assSeq().getSelectedItem();
778 lbl_fromFileStatus.setIcon(errorImage);
779 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
780 .getName().equalsIgnoreCase("-Select Associated Seq-")))
782 btn_pdbFromFile.setEnabled(true);
783 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
785 btn_add.setEnabled(true);
786 lbl_fromFileStatus.setIcon(goodImage);
791 btn_pdbFromFile.setEnabled(false);
792 lbl_fromFileStatus.setIcon(errorImage);
797 protected void cmbAssSeqStateChanged()
799 validateSelections();
803 * Handles the state change event for the 'filter' combo-box and 'invert'
807 protected void stateChanged(ItemEvent e)
809 if (e.getSource() instanceof JCheckBox)
815 if (e.getStateChange() == ItemEvent.SELECTED)
824 * select structures for viewing by their PDB IDs
827 * @return true if structures were found and marked as selected
829 public boolean selectStructure(String... pdbids)
831 boolean found = false;
833 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
835 String currentView = selectedFilterOpt.getView();
836 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
837 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
839 if (restable == null)
841 // can't select (enter PDB ID, or load file - need to also select which
842 // sequence to associate with)
846 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
847 for (int r = 0; r < restable.getRowCount(); r++)
849 for (int p = 0; p < pdbids.length; p++)
851 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
852 .equalsIgnoreCase(pdbids[p]))
854 restable.setRowSelectionInterval(r, r);
863 * Handles the 'New View' action
866 protected void newView_ActionPerformed()
868 targetView.setSelectedItem(null);
869 showStructures(false);
873 * Handles the 'Add to existing viewer' action
876 protected void add_ActionPerformed()
878 showStructures(false);
882 * structure viewer opened by this dialog, or null
884 private StructureViewer sViewer = null;
886 public void showStructures(boolean waitUntilFinished)
889 final int preferredHeight = pnl_filter.getHeight();
891 final StructureViewer theViewer = getTargetedStructureViewer();
892 boolean superimpose = chk_superpose.isSelected();
894 Runnable viewStruc = new Runnable()
899 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
901 String currentView = selectedFilterOpt.getView();
902 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
905 if (currentView == VIEWS_FILTER)
907 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
908 int refSeqColIndex = restable.getColumn("Ref Sequence")
910 int[] selectedRows = restable.getSelectedRows();
911 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
913 List<SequenceI> selectedSeqsToView = new ArrayList<>();
914 for (int row : selectedRows)
916 String pdbIdStr = restable.getValueAt(row, pdbIdColIndex)
918 SequenceI selectedSeq = (SequenceI) restable.getValueAt(row,
920 selectedSeqsToView.add(selectedSeq);
921 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
922 if (pdbEntry == null)
924 pdbEntry = getFindEntry(pdbIdStr,
925 selectedSeq.getAllPDBEntries());
928 if (pdbEntry == null)
930 pdbEntry = new PDBEntry(pdbIdStr, null, "pdb");
931 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
933 pdbEntriesToView[count++] = pdbEntry;
935 SequenceI[] selectedSeqs = selectedSeqsToView
936 .toArray(new SequenceI[selectedSeqsToView.size()]);
937 sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
938 selectedSeqs, superimpose, theViewer, progressBar);
940 else if (currentView == VIEWS_LOCAL_PDB)
942 int[] selectedRows = tbl_local_pdb.getSelectedRows();
943 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
945 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
947 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
949 List<SequenceI> selectedSeqsToView = new ArrayList<>();
950 for (int row : selectedRows)
952 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
954 pdbEntriesToView[count++] = pdbEntry;
955 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
956 .getValueAt(row, refSeqColIndex);
957 selectedSeqsToView.add(selectedSeq);
959 SequenceI[] selectedSeqs = selectedSeqsToView
960 .toArray(new SequenceI[selectedSeqsToView.size()]);
961 sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
962 selectedSeqs, superimpose, theViewer, progressBar);
964 else if (currentView == VIEWS_ENTER_ID)
966 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
967 .getCmb_assSeq().getSelectedItem()).getSequence();
968 if (userSelectedSeq != null)
970 selectedSequence = userSelectedSeq;
972 String pdbIdStr = txt_search.getText();
973 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
974 if (pdbEntry == null)
976 pdbEntry = new PDBEntry();
977 if (pdbIdStr.split(":").length > 1)
979 pdbEntry.setId(pdbIdStr.split(":")[0]);
980 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
984 pdbEntry.setId(pdbIdStr);
986 pdbEntry.setType(PDBEntry.Type.PDB);
987 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
990 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
991 sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
993 { selectedSequence }, superimpose, theViewer,
996 else if (currentView == VIEWS_FROM_FILE)
998 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
999 .getCmb_assSeq().getSelectedItem()).getSequence();
1000 if (userSelectedSeq != null)
1002 selectedSequence = userSelectedSeq;
1004 PDBEntry fileEntry = AssociatePdbFileWithSeq.associatePdbWithSeq(selectedPdbFileName,
1005 DataSourceType.FILE, selectedSequence, true);
1006 sViewer = StructureViewer.launchStructureViewer(ap, new PDBEntry[] { fileEntry },
1008 { selectedSequence }, superimpose, theViewer,
1011 SwingUtilities.invokeLater(new Runnable()
1016 closeAction(preferredHeight);
1017 mainFrame.dispose();
1022 Thread runner = new Thread(viewStruc);
1024 if (waitUntilFinished)
1026 while (sViewer == null ? runner.isAlive()
1027 : (sViewer.sview == null ? true
1028 : !sViewer.sview.hasMapping()))
1033 } catch (InterruptedException ie)
1041 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1043 Objects.requireNonNull(id);
1044 Objects.requireNonNull(pdbEntries);
1045 PDBEntry foundEntry = null;
1046 for (PDBEntry entry : pdbEntries)
1048 if (entry.getId().equalsIgnoreCase(id))
1057 * Answers a structure viewer (new or existing) configured to superimpose
1058 * added structures or not according to the user's choice
1063 StructureViewer getTargetedStructureViewer()
1065 return (StructureViewer) targetView.getSelectedItem();
1069 * Populates the combo-box used in associating manually fetched structures to
1070 * a unique sequence when more than one sequence selection is made.
1073 protected void populateCmbAssociateSeqOptions(
1074 JComboBox<AssociateSeqOptions> cmb_assSeq,
1075 JLabel lbl_associateSeq)
1077 cmb_assSeq.removeAllItems();
1079 new AssociateSeqOptions("-Select Associated Seq-", null));
1080 lbl_associateSeq.setVisible(false);
1081 if (selectedSequences.length > 1)
1083 for (SequenceI seq : selectedSequences)
1085 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1090 String seqName = selectedSequence.getDisplayId(false);
1091 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1092 lbl_associateSeq.setText(seqName);
1093 lbl_associateSeq.setVisible(true);
1094 cmb_assSeq.setVisible(false);
1098 protected boolean isStructuresDiscovered()
1100 return discoveredStructuresSet != null
1101 && !discoveredStructuresSet.isEmpty();
1104 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1106 // Doing a search for "1" or "1c" is valuable?
1107 // Those work but are enormously slow.
1110 protected void txt_search_ActionPerformed()
1112 String text = txt_search.getText().trim();
1113 if (text.length() >= PDB_ID_MIN)
1120 errorWarning.setLength(0);
1121 isValidPBDEntry = false;
1122 if (text.length() > 0)
1124 String searchTerm = text.toLowerCase();
1125 searchTerm = searchTerm.split(":")[0];
1126 // System.out.println(">>>>> search term : " + searchTerm);
1127 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1128 FTSRestRequest pdbRequest = new FTSRestRequest();
1129 pdbRequest.setAllowEmptySeq(false);
1130 pdbRequest.setResponseSize(1);
1131 pdbRequest.setFieldToSearchBy("(pdb_id:");
1132 pdbRequest.setWantedFields(wantedFields);
1133 pdbRequest.setSearchTerm(searchTerm + ")");
1134 pdbRequest.setAssociatedSequence(selectedSequence);
1135 pdbRestClient = PDBFTSRestClient.getInstance();
1136 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1137 FTSRestResponse resultList;
1140 resultList = pdbRestClient.executeRequest(pdbRequest);
1141 } catch (Exception e)
1143 errorWarning.append(e.getMessage());
1147 validateSelections();
1149 if (resultList.getSearchSummary() != null
1150 && resultList.getSearchSummary().size() > 0)
1152 isValidPBDEntry = true;
1155 validateSelections();
1161 protected void tabRefresh()
1163 if (selectedSequences != null)
1165 Thread refreshThread = new Thread(new Runnable()
1170 fetchStructuresMetaData();
1172 ((FilterOption) cmb_filterOption.getSelectedItem())
1176 refreshThread.start();
1180 public class PDBEntryTableModel extends AbstractTableModel
1182 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1185 private List<CachedPDB> pdbEntries;
1187 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1189 this.pdbEntries = new ArrayList<>(pdbEntries);
1193 public String getColumnName(int columnIndex)
1195 return columns[columnIndex];
1199 public int getRowCount()
1201 return pdbEntries.size();
1205 public int getColumnCount()
1207 return columns.length;
1211 public boolean isCellEditable(int row, int column)
1217 public Object getValueAt(int rowIndex, int columnIndex)
1219 Object value = "??";
1220 CachedPDB entry = pdbEntries.get(rowIndex);
1221 switch (columnIndex)
1224 value = entry.getSequence();
1227 value = entry.getPdbEntry();
1230 value = entry.getPdbEntry().getChainCode() == null ? "_"
1231 : entry.getPdbEntry().getChainCode();
1234 value = entry.getPdbEntry().getType();
1237 value = entry.getPdbEntry().getFile();
1244 public Class<?> getColumnClass(int columnIndex)
1246 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1249 public CachedPDB getPDBEntryAt(int row)
1251 return pdbEntries.get(row);
1256 private class CachedPDB
1258 private SequenceI sequence;
1260 private PDBEntry pdbEntry;
1262 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1264 this.sequence = sequence;
1265 this.pdbEntry = pdbEntry;
1268 public SequenceI getSequence()
1273 public PDBEntry getPdbEntry()
1280 private IProgressIndicator progressBar;
1283 public void setProgressBar(String message, long id)
1285 progressBar.setProgressBar(message, id);
1289 public void registerHandler(long id, IProgressIndicatorHandler handler)
1291 progressBar.registerHandler(id, handler);
1295 public boolean operationInProgress()
1297 return progressBar.operationInProgress();
1300 public JalviewStructureDisplayI getOpenedStructureViewer()
1302 return sViewer == null ? null : sViewer.sview;