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 java.awt.event.ItemEvent;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashSet;
28 import java.util.LinkedHashSet;
29 import java.util.List;
30 import java.util.Objects;
32 import java.util.Vector;
34 import javax.swing.JCheckBox;
35 import javax.swing.JComboBox;
36 import javax.swing.JLabel;
37 import javax.swing.JTable;
38 import javax.swing.SwingUtilities;
39 import javax.swing.table.AbstractTableModel;
41 import jalview.api.structures.JalviewStructureDisplayI;
42 import jalview.bin.Cache;
43 import jalview.bin.Jalview;
44 import jalview.datamodel.DBRefEntry;
45 import jalview.datamodel.DBRefSource;
46 import jalview.datamodel.PDBEntry;
47 import jalview.datamodel.SequenceI;
48 import jalview.fts.api.FTSData;
49 import jalview.fts.api.FTSDataColumnI;
50 import jalview.fts.api.FTSRestClientI;
51 import jalview.fts.core.FTSRestRequest;
52 import jalview.fts.core.FTSRestResponse;
53 import jalview.fts.service.pdb.PDBFTSRestClient;
54 import jalview.io.DataSourceType;
55 import jalview.jbgui.GStructureChooser;
56 import jalview.util.MessageManager;
59 * Provides the behaviors for the Structure chooser Panel
64 @SuppressWarnings("serial")
65 public class StructureChooser extends GStructureChooser
66 implements IProgressIndicator
68 static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
70 private static int MAX_QLENGTH = 7820;
72 private SequenceI selectedSequence;
74 private SequenceI[] selectedSequences;
76 private IProgressIndicator progressIndicator;
78 private Collection<FTSData> discoveredStructuresSet;
80 private FTSRestRequest lastPdbRequest;
82 private FTSRestClientI pdbRestClient;
84 private String selectedPdbFileName;
86 private boolean isValidPBDEntry;
88 private boolean cachedPDBExists;
90 static StructureViewer lastTargetedView = null;
92 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
96 this.selectedSequence = selectedSeq;
97 this.selectedSequences = selectedSeqs;
98 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
103 * Initializes parameters used by the Structure Chooser Panel
105 protected void init()
107 if (!Jalview.isHeadlessMode())
109 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
112 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
114 // ensure a filter option is in force for search
115 populateFilterComboBox(true, cachedPDBExists);
116 Thread discoverPDBStructuresThread = new Thread(new Runnable()
121 long startTime = System.currentTimeMillis();
122 updateProgressIndicator(MessageManager
123 .getString("status.loading_cached_pdb_entries"), startTime);
124 loadLocalCachedPDBEntries();
125 updateProgressIndicator(null, startTime);
126 updateProgressIndicator(MessageManager.getString(
127 "status.searching_for_pdb_structures"), startTime);
128 fetchStructuresMetaData();
129 // revise filter options if no results were found
130 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
131 discoverStructureViews();
132 updateProgressIndicator(null, startTime);
133 mainFrame.setVisible(true);
137 discoverPDBStructuresThread.start();
141 * Builds a drop-down choice list of existing structure viewers to which new
142 * structures may be added. If this list is empty then it, and the 'Add'
143 * button, are hidden.
145 private void discoverStructureViews()
147 if (Desktop.getInstance() != null)
149 targetView.removeAllItems();
150 if (lastTargetedView != null && !lastTargetedView.isVisible())
152 lastTargetedView = null;
154 int linkedViewsAt = 0;
155 for (StructureViewerBase view : Desktop.getInstance()
156 .getStructureViewers(null, null))
158 StructureViewer viewHandler = (lastTargetedView != null
159 && lastTargetedView.sview == view) ? lastTargetedView
160 : StructureViewer.reconfigure(view);
162 if (view.isLinkedWith(ap))
164 targetView.insertItemAt(viewHandler, linkedViewsAt++);
168 targetView.addItem(viewHandler);
173 * show option to Add to viewer if at least 1 viewer found
175 targetView.setVisible(false);
176 if (targetView.getItemCount() > 0)
178 targetView.setVisible(true);
179 if (lastTargetedView != null)
181 targetView.setSelectedItem(lastTargetedView);
185 targetView.setSelectedIndex(0);
188 btn_add.setVisible(targetView.isVisible());
193 * Updates the progress indicator with the specified message
196 * displayed message for the operation
198 * unique handle for this indicator
200 protected void updateProgressIndicator(String message, long id)
202 if (progressIndicator != null)
204 progressIndicator.setProgressBar(message, id);
209 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
212 void fetchStructuresMetaData()
214 long startTime = System.currentTimeMillis();
215 pdbRestClient = PDBFTSRestClient.getInstance();
216 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
217 .getStructureSummaryFields();
219 discoveredStructuresSet = new LinkedHashSet<>();
220 HashSet<String> errors = new HashSet<>();
221 for (SequenceI seq : selectedSequences)
223 FTSRestRequest pdbRequest = new FTSRestRequest();
224 pdbRequest.setAllowEmptySeq(false);
225 pdbRequest.setResponseSize(500);
226 pdbRequest.setFieldToSearchBy("(");
227 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
229 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
230 !chk_invertFilter.isSelected());
231 pdbRequest.setWantedFields(wantedFields);
232 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
233 pdbRequest.setAssociatedSequence(seq);
234 FTSRestResponse resultList;
237 resultList = pdbRestClient.executeRequest(pdbRequest);
238 } catch (Exception e)
241 errors.add(e.getMessage());
244 lastPdbRequest = pdbRequest;
245 if (resultList.getSearchSummary() != null
246 && !resultList.getSearchSummary().isEmpty())
248 discoveredStructuresSet.addAll(resultList.getSearchSummary());
252 int noOfStructuresFound = 0;
253 String totalTime = (System.currentTimeMillis() - startTime)
255 if (discoveredStructuresSet != null
256 && !discoveredStructuresSet.isEmpty())
258 getResultTable().setModel(FTSRestResponse
259 .getTableModel(lastPdbRequest, discoveredStructuresSet));
260 noOfStructuresFound = discoveredStructuresSet.size();
261 mainFrame.setTitle(MessageManager.formatMessage(
262 "label.structure_chooser_no_of_structures",
263 noOfStructuresFound, totalTime));
267 mainFrame.setTitle(MessageManager
268 .getString("label.structure_chooser_manual_association"));
269 if (errors.size() > 0)
271 StringBuilder errorMsg = new StringBuilder();
272 for (String error : errors)
274 errorMsg.append(error).append("\n");
276 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
277 MessageManager.getString("label.pdb_web-service_error"),
278 JvOptionPane.ERROR_MESSAGE);
283 protected void loadLocalCachedPDBEntries()
285 ArrayList<CachedPDB> entries = new ArrayList<>();
286 for (SequenceI seq : selectedSequences)
288 if (seq.getDatasetSequence() != null
289 && seq.getDatasetSequence().getAllPDBEntries() != null)
291 for (PDBEntry pdbEntry : seq.getDatasetSequence()
294 if (pdbEntry.getFile() != null)
296 entries.add(new CachedPDB(seq, pdbEntry));
301 cachedPDBExists = !entries.isEmpty();
302 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
303 tbl_local_pdb.setModel(tableModelx);
307 * Builds a query string for a given sequences using its DBRef entries
310 * the sequences to build a query for
311 * @return the built query string
314 static String buildQuery(SequenceI seq)
316 boolean isPDBRefsFound = false;
317 boolean isUniProtRefsFound = false;
318 StringBuilder queryBuilder = new StringBuilder();
319 Set<String> seqRefs = new LinkedHashSet<>();
322 * note PDBs as DBRefEntry so they are not duplicated in query
324 Set<String> pdbids = new HashSet<>();
326 if (seq.getAllPDBEntries() != null
327 && queryBuilder.length() < MAX_QLENGTH)
329 for (PDBEntry entry : seq.getAllPDBEntries())
331 if (isValidSeqName(entry.getId()))
333 String id = entry.getId().toLowerCase();
334 queryBuilder.append("pdb_id:").append(id).append(" OR ");
335 isPDBRefsFound = true;
341 List<DBRefEntry> refs = seq.getDBRefs();
342 if (refs != null && refs.size() != 0)
344 for (int ib = 0, nb = refs.size(); ib < nb; ib++)
346 DBRefEntry dbRef = refs.get(ib);
347 if (isValidSeqName(getDBRefId(dbRef))
348 && queryBuilder.length() < MAX_QLENGTH)
350 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
352 queryBuilder.append("uniprot_accession:")
353 .append(getDBRefId(dbRef)).append(" OR ");
354 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
356 isUniProtRefsFound = true;
358 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
361 String id = getDBRefId(dbRef).toLowerCase();
362 if (!pdbids.contains(id))
364 queryBuilder.append("pdb_id:").append(id).append(" OR ");
365 isPDBRefsFound = true;
371 seqRefs.add(getDBRefId(dbRef));
377 if (!isPDBRefsFound && !isUniProtRefsFound)
379 String seqName = seq.getName();
380 seqName = sanitizeSeqName(seqName);
381 String[] names = seqName.toLowerCase().split("\\|");
382 for (String name : names)
384 // System.out.println("Found name : " + name);
386 if (isValidSeqName(name))
392 for (String seqRef : seqRefs)
394 queryBuilder.append("text:").append(seqRef).append(" OR ");
398 int endIndex = queryBuilder.lastIndexOf(" OR ");
399 if (queryBuilder.toString().length() < 6)
403 String query = queryBuilder.toString().substring(0, endIndex);
408 * Remove the following special characters from input string +, -, &, !, (, ),
409 * {, }, [, ], ^, ", ~, *, ?, :, \
414 static String sanitizeSeqName(String seqName)
416 Objects.requireNonNull(seqName);
417 return seqName.replaceAll("\\[\\d*\\]", "")
418 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
422 * Ensures sequence ref names are not less than 3 characters and does not
423 * contain a database name
428 static boolean isValidSeqName(String seqName)
430 // System.out.println("seqName : " + seqName);
431 String ignoreList = "pdb,uniprot,swiss-prot";
432 if (seqName.length() < 3)
436 if (seqName.contains(":"))
440 seqName = seqName.toLowerCase();
441 for (String ignoredEntry : ignoreList.split(","))
443 if (seqName.contains(ignoredEntry))
451 static String getDBRefId(DBRefEntry dbRef)
453 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
458 * Filters a given list of discovered structures based on supplied argument
460 * @param fieldToFilterBy
461 * the field to filter by
463 void filterResultSet(final String fieldToFilterBy)
465 Thread filterThread = new Thread(new Runnable()
470 long startTime = System.currentTimeMillis();
471 pdbRestClient = PDBFTSRestClient.getInstance();
472 lbl_loading.setVisible(true);
473 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
474 .getStructureSummaryFields();
475 Collection<FTSData> filteredResponse = new HashSet<>();
476 HashSet<String> errors = new HashSet<>();
478 for (SequenceI seq : selectedSequences)
480 FTSRestRequest pdbRequest = new FTSRestRequest();
481 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
483 pdbRequest.setAllowEmptySeq(false);
484 pdbRequest.setResponseSize(1);
485 pdbRequest.setFieldToSearchBy("(");
486 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
487 pdbRequest.setWantedFields(wantedFields);
488 pdbRequest.setAssociatedSequence(seq);
489 pdbRequest.setFacet(true);
490 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
491 pdbRequest.setFacetPivotMinCount(1);
495 pdbRequest.setAllowEmptySeq(false);
496 pdbRequest.setResponseSize(1);
497 pdbRequest.setFieldToSearchBy("(");
498 pdbRequest.setFieldToSortBy(fieldToFilterBy,
499 !chk_invertFilter.isSelected());
500 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
501 pdbRequest.setWantedFields(wantedFields);
502 pdbRequest.setAssociatedSequence(seq);
504 FTSRestResponse resultList;
507 resultList = pdbRestClient.executeRequest(pdbRequest);
508 } catch (Exception e)
511 errors.add(e.getMessage());
514 lastPdbRequest = pdbRequest;
515 if (resultList.getSearchSummary() != null
516 && !resultList.getSearchSummary().isEmpty())
518 filteredResponse.addAll(resultList.getSearchSummary());
522 String totalTime = (System.currentTimeMillis() - startTime)
524 if (!filteredResponse.isEmpty())
526 final int filterResponseCount = filteredResponse.size();
527 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
528 reorderedStructuresSet.addAll(filteredResponse);
529 reorderedStructuresSet.addAll(discoveredStructuresSet);
530 getResultTable().setModel(FTSRestResponse
531 .getTableModel(lastPdbRequest, reorderedStructuresSet));
533 FTSRestResponse.configureTableColumn(getResultTable(),
534 wantedFields, tempUserPrefs);
535 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
536 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
537 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
538 // Update table selection model here
539 getResultTable().addRowSelectionInterval(0,
540 filterResponseCount - 1);
541 mainFrame.setTitle(MessageManager.formatMessage(
542 "label.structure_chooser_filter_time", totalTime));
546 mainFrame.setTitle(MessageManager.formatMessage(
547 "label.structure_chooser_filter_time", totalTime));
548 if (errors.size() > 0)
550 StringBuilder errorMsg = new StringBuilder();
551 for (String error : errors)
553 errorMsg.append(error).append("\n");
555 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
556 MessageManager.getString("label.pdb_web-service_error"),
557 JvOptionPane.ERROR_MESSAGE);
561 lbl_loading.setVisible(false);
563 validateSelections();
566 filterThread.start();
570 * Handles action event for btn_pdbFromFile
573 protected void pdbFromFile_actionPerformed()
575 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
578 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
579 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
580 chooser.setFileView(new jalview.io.JalviewFileView());
581 chooser.setDialogTitle(
582 MessageManager.formatMessage("label.select_pdb_file_for",
583 selectedSequence.getDisplayId(false)));
584 chooser.setToolTipText(MessageManager.formatMessage(
585 "label.load_pdb_file_associate_with_sequence",
586 selectedSequence.getDisplayId(false)));
588 int value = chooser.showOpenDialog(null);
589 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
591 selectedPdbFileName = chooser.getSelectedFile().getPath();
592 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
593 validateSelections();
598 * Populates the filter combo-box options dynamically depending on discovered
601 protected void populateFilterComboBox(boolean haveData,
602 boolean cachedPDBExist)
605 * temporarily suspend the change listener behaviour
607 cmb_filterOption.removeItemListener(this);
609 cmb_filterOption.removeAllItems();
612 cmb_filterOption.addItem(new FilterOption(
613 MessageManager.getString("label.best_quality"),
614 "overall_quality", VIEWS_FILTER, false));
615 cmb_filterOption.addItem(new FilterOption(
616 MessageManager.getString("label.best_resolution"),
617 "resolution", VIEWS_FILTER, false));
618 cmb_filterOption.addItem(new FilterOption(
619 MessageManager.getString("label.most_protein_chain"),
620 "number_of_protein_chains", VIEWS_FILTER, false));
621 cmb_filterOption.addItem(new FilterOption(
622 MessageManager.getString("label.most_bound_molecules"),
623 "number_of_bound_molecules", VIEWS_FILTER, false));
624 cmb_filterOption.addItem(new FilterOption(
625 MessageManager.getString("label.most_polymer_residues"),
626 "number_of_polymer_residues", VIEWS_FILTER, true));
628 cmb_filterOption.addItem(
629 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
630 "-", VIEWS_ENTER_ID, false));
631 cmb_filterOption.addItem(
632 new FilterOption(MessageManager.getString("label.from_file"),
633 "-", VIEWS_FROM_FILE, false));
637 FilterOption cachedOption = new FilterOption(
638 MessageManager.getString("label.cached_structures"), "-",
639 VIEWS_LOCAL_PDB, false);
640 cmb_filterOption.addItem(cachedOption);
641 cmb_filterOption.setSelectedItem(cachedOption);
644 cmb_filterOption.addItemListener(this);
648 * Updates the displayed view based on the selected filter option
650 protected void updateCurrentView()
652 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
654 layout_switchableViews.show(pnl_switchableViews,
655 selectedFilterOpt.getView());
656 String filterTitle = mainFrame.getTitle();
657 mainFrame.setTitle(frameTitle);
658 chk_invertFilter.setVisible(false);
659 if (selectedFilterOpt.getView() == VIEWS_FILTER)
661 mainFrame.setTitle(filterTitle);
662 chk_invertFilter.setVisible(true);
663 filterResultSet(selectedFilterOpt.getValue());
665 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
666 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
668 mainFrame.setTitle(MessageManager
669 .getString("label.structure_chooser_manual_association"));
670 idInputAssSeqPanel.loadCmbAssSeq();
671 fileChooserAssSeqPanel.loadCmbAssSeq();
673 validateSelections();
677 * Validates user selection and enables the 'Add' and 'New View' buttons if
678 * all parameters are correct (the Add button will only be visible if there is
679 * at least one existing structure viewer open). This basically means at least
680 * one structure selected and no error messages.
682 * The 'Superpose Structures' option is enabled if either more than one
683 * structure is selected, or the 'Add' to existing view option is enabled, and
684 * disabled if the only option is to open a new view of a single structure.
687 protected void validateSelections()
689 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
691 btn_add.setEnabled(false);
692 String currentView = selectedFilterOpt.getView();
693 int selectedCount = 0;
694 if (currentView == VIEWS_FILTER)
696 selectedCount = getResultTable().getSelectedRows().length;
697 if (selectedCount > 0)
699 btn_add.setEnabled(true);
702 else if (currentView == VIEWS_LOCAL_PDB)
704 selectedCount = tbl_local_pdb.getSelectedRows().length;
705 if (selectedCount > 0)
707 btn_add.setEnabled(true);
710 else if (currentView == VIEWS_ENTER_ID)
712 validateAssociationEnterPdb();
714 else if (currentView == VIEWS_FROM_FILE)
716 validateAssociationFromFile();
719 btn_newView.setEnabled(btn_add.isEnabled());
722 * enable 'Superpose' option if more than one structure is selected,
723 * or there are view(s) available to add structure(s) to
726 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
730 * Validates inputs from the Manual PDB entry panel
732 protected void validateAssociationEnterPdb()
734 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
735 .getCmb_assSeq().getSelectedItem();
736 lbl_pdbManualFetchStatus.setIcon(errorImage);
737 lbl_pdbManualFetchStatus.setToolTipText("");
738 if (txt_search.getText().length() > 0)
740 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
741 MessageManager.formatMessage("info.no_pdb_entry_found_for",
742 txt_search.getText())));
745 if (errorWarning.length() > 0)
747 lbl_pdbManualFetchStatus.setIcon(warningImage);
748 lbl_pdbManualFetchStatus.setToolTipText(
749 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
752 if (selectedSequences.length == 1 || !assSeqOpt.getName()
753 .equalsIgnoreCase("-Select Associated Seq-"))
755 txt_search.setEnabled(true);
758 btn_add.setEnabled(true);
759 lbl_pdbManualFetchStatus.setToolTipText("");
760 lbl_pdbManualFetchStatus.setIcon(goodImage);
765 txt_search.setEnabled(false);
766 lbl_pdbManualFetchStatus.setIcon(errorImage);
771 * Validates inputs for the manual PDB file selection options
773 protected void validateAssociationFromFile()
775 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
776 .getCmb_assSeq().getSelectedItem();
777 lbl_fromFileStatus.setIcon(errorImage);
778 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
779 .getName().equalsIgnoreCase("-Select Associated Seq-")))
781 btn_pdbFromFile.setEnabled(true);
782 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
784 btn_add.setEnabled(true);
785 lbl_fromFileStatus.setIcon(goodImage);
790 btn_pdbFromFile.setEnabled(false);
791 lbl_fromFileStatus.setIcon(errorImage);
796 protected void cmbAssSeqStateChanged()
798 validateSelections();
802 * Handles the state change event for the 'filter' combo-box and 'invert'
806 protected void stateChanged(ItemEvent e)
808 if (e.getSource() instanceof JCheckBox)
814 if (e.getStateChange() == ItemEvent.SELECTED)
823 * select structures for viewing by their PDB IDs
826 * @return true if structures were found and marked as selected
828 public boolean selectStructure(String... pdbids)
830 boolean found = false;
832 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
834 String currentView = selectedFilterOpt.getView();
835 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
836 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
838 if (restable == null)
840 // can't select (enter PDB ID, or load file - need to also select which
841 // sequence to associate with)
845 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
846 for (int r = 0; r < restable.getRowCount(); r++)
848 for (int p = 0; p < pdbids.length; p++)
850 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
851 .equalsIgnoreCase(pdbids[p]))
853 restable.setRowSelectionInterval(r, r);
862 * Handles the 'New View' action
865 protected void newView_ActionPerformed()
867 targetView.setSelectedItem(null);
868 showStructures(false);
872 * Handles the 'Add to existing viewer' action
875 protected void add_ActionPerformed()
877 showStructures(false);
881 * structure viewer opened by this dialog, or null
883 private StructureViewer sViewer = null;
885 public void showStructures(boolean waitUntilFinished)
888 final int preferredHeight = pnl_filter.getHeight();
890 final StructureViewer theViewer = getTargetedStructureViewer();
891 boolean superimpose = chk_superpose.isSelected();
893 Runnable viewStruc = new Runnable()
898 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
900 String currentView = selectedFilterOpt.getView();
901 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
904 if (currentView == VIEWS_FILTER)
906 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
907 int refSeqColIndex = restable.getColumn("Ref Sequence")
909 int[] selectedRows = restable.getSelectedRows();
910 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
912 List<SequenceI> selectedSeqsToView = new ArrayList<>();
913 for (int row : selectedRows)
915 String pdbIdStr = restable.getValueAt(row, pdbIdColIndex)
917 SequenceI selectedSeq = (SequenceI) restable.getValueAt(row,
919 selectedSeqsToView.add(selectedSeq);
920 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
921 if (pdbEntry == null)
923 pdbEntry = getFindEntry(pdbIdStr,
924 selectedSeq.getAllPDBEntries());
927 if (pdbEntry == null)
929 pdbEntry = new PDBEntry(pdbIdStr, null, "pdb");
930 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
932 pdbEntriesToView[count++] = pdbEntry;
934 SequenceI[] selectedSeqs = selectedSeqsToView
935 .toArray(new SequenceI[selectedSeqsToView.size()]);
936 sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
937 selectedSeqs, superimpose, theViewer, progressBar);
939 else if (currentView == VIEWS_LOCAL_PDB)
941 int[] selectedRows = tbl_local_pdb.getSelectedRows();
942 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
944 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
946 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
948 List<SequenceI> selectedSeqsToView = new ArrayList<>();
949 for (int row : selectedRows)
951 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
953 pdbEntriesToView[count++] = pdbEntry;
954 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
955 .getValueAt(row, refSeqColIndex);
956 selectedSeqsToView.add(selectedSeq);
958 SequenceI[] selectedSeqs = selectedSeqsToView
959 .toArray(new SequenceI[selectedSeqsToView.size()]);
960 sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
961 selectedSeqs, superimpose, theViewer, progressBar);
963 else if (currentView == VIEWS_ENTER_ID)
965 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
966 .getCmb_assSeq().getSelectedItem()).getSequence();
967 if (userSelectedSeq != null)
969 selectedSequence = userSelectedSeq;
971 String pdbIdStr = txt_search.getText();
972 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
973 if (pdbEntry == null)
975 pdbEntry = new PDBEntry();
976 if (pdbIdStr.split(":").length > 1)
978 pdbEntry.setId(pdbIdStr.split(":")[0]);
979 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
983 pdbEntry.setId(pdbIdStr);
985 pdbEntry.setType(PDBEntry.Type.PDB);
986 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
989 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
990 sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
992 { selectedSequence }, superimpose, theViewer,
995 else if (currentView == VIEWS_FROM_FILE)
997 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
998 .getCmb_assSeq().getSelectedItem()).getSequence();
999 if (userSelectedSeq != null)
1001 selectedSequence = userSelectedSeq;
1003 PDBEntry fileEntry = AssociatePdbFileWithSeq.associatePdbWithSeq(selectedPdbFileName,
1004 DataSourceType.FILE, selectedSequence, true);
1005 sViewer = StructureViewer.launchStructureViewer(ap, new PDBEntry[] { fileEntry },
1007 { selectedSequence }, superimpose, theViewer,
1010 SwingUtilities.invokeLater(new Runnable()
1015 closeAction(preferredHeight);
1016 mainFrame.dispose();
1021 Thread runner = new Thread(viewStruc);
1023 if (waitUntilFinished)
1025 while (sViewer == null ? runner.isAlive()
1026 : (sViewer.sview == null ? true
1027 : !sViewer.sview.hasMapping()))
1032 } catch (InterruptedException ie)
1040 private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1042 Objects.requireNonNull(id);
1043 Objects.requireNonNull(pdbEntries);
1044 PDBEntry foundEntry = null;
1045 for (PDBEntry entry : pdbEntries)
1047 if (entry.getId().equalsIgnoreCase(id))
1056 * Answers a structure viewer (new or existing) configured to superimpose
1057 * added structures or not according to the user's choice
1062 StructureViewer getTargetedStructureViewer()
1064 return (StructureViewer) targetView.getSelectedItem();
1068 * Populates the combo-box used in associating manually fetched structures to
1069 * a unique sequence when more than one sequence selection is made.
1072 protected void populateCmbAssociateSeqOptions(
1073 JComboBox<AssociateSeqOptions> cmb_assSeq,
1074 JLabel lbl_associateSeq)
1076 cmb_assSeq.removeAllItems();
1078 new AssociateSeqOptions("-Select Associated Seq-", null));
1079 lbl_associateSeq.setVisible(false);
1080 if (selectedSequences.length > 1)
1082 for (SequenceI seq : selectedSequences)
1084 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1089 String seqName = selectedSequence.getDisplayId(false);
1090 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1091 lbl_associateSeq.setText(seqName);
1092 lbl_associateSeq.setVisible(true);
1093 cmb_assSeq.setVisible(false);
1097 protected boolean isStructuresDiscovered()
1099 return discoveredStructuresSet != null
1100 && !discoveredStructuresSet.isEmpty();
1103 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1105 // Doing a search for "1" or "1c" is valuable?
1106 // Those work but are enormously slow.
1109 protected void txt_search_ActionPerformed()
1111 String text = txt_search.getText().trim();
1112 if (text.length() >= PDB_ID_MIN)
1119 errorWarning.setLength(0);
1120 isValidPBDEntry = false;
1121 if (text.length() > 0)
1123 String searchTerm = text.toLowerCase();
1124 searchTerm = searchTerm.split(":")[0];
1125 // System.out.println(">>>>> search term : " + searchTerm);
1126 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1127 FTSRestRequest pdbRequest = new FTSRestRequest();
1128 pdbRequest.setAllowEmptySeq(false);
1129 pdbRequest.setResponseSize(1);
1130 pdbRequest.setFieldToSearchBy("(pdb_id:");
1131 pdbRequest.setWantedFields(wantedFields);
1132 pdbRequest.setSearchTerm(searchTerm + ")");
1133 pdbRequest.setAssociatedSequence(selectedSequence);
1134 pdbRestClient = PDBFTSRestClient.getInstance();
1135 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1136 FTSRestResponse resultList;
1139 resultList = pdbRestClient.executeRequest(pdbRequest);
1140 } catch (Exception e)
1142 errorWarning.append(e.getMessage());
1146 validateSelections();
1148 if (resultList.getSearchSummary() != null
1149 && resultList.getSearchSummary().size() > 0)
1151 isValidPBDEntry = true;
1154 validateSelections();
1160 protected void tabRefresh()
1162 if (selectedSequences != null)
1164 Thread refreshThread = new Thread(new Runnable()
1169 fetchStructuresMetaData();
1171 ((FilterOption) cmb_filterOption.getSelectedItem())
1175 refreshThread.start();
1179 public class PDBEntryTableModel extends AbstractTableModel
1181 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1184 private List<CachedPDB> pdbEntries;
1186 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1188 this.pdbEntries = new ArrayList<>(pdbEntries);
1192 public String getColumnName(int columnIndex)
1194 return columns[columnIndex];
1198 public int getRowCount()
1200 return pdbEntries.size();
1204 public int getColumnCount()
1206 return columns.length;
1210 public boolean isCellEditable(int row, int column)
1216 public Object getValueAt(int rowIndex, int columnIndex)
1218 Object value = "??";
1219 CachedPDB entry = pdbEntries.get(rowIndex);
1220 switch (columnIndex)
1223 value = entry.getSequence();
1226 value = entry.getPdbEntry();
1229 value = entry.getPdbEntry().getChainCode() == null ? "_"
1230 : entry.getPdbEntry().getChainCode();
1233 value = entry.getPdbEntry().getType();
1236 value = entry.getPdbEntry().getFile();
1243 public Class<?> getColumnClass(int columnIndex)
1245 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1248 public CachedPDB getPDBEntryAt(int row)
1250 return pdbEntries.get(row);
1255 private class CachedPDB
1257 private SequenceI sequence;
1259 private PDBEntry pdbEntry;
1261 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1263 this.sequence = sequence;
1264 this.pdbEntry = pdbEntry;
1267 public SequenceI getSequence()
1272 public PDBEntry getPdbEntry()
1279 private IProgressIndicator progressBar;
1282 public void setProgressBar(String message, long id)
1284 progressBar.setProgressBar(message, id);
1288 public void removeProgressBar(long id)
1290 progressBar.removeProgressBar(id);
1294 public void registerHandler(long id, IProgressIndicatorHandler handler)
1296 progressBar.registerHandler(id, handler);
1300 public boolean operationInProgress()
1302 return progressBar.operationInProgress();
1305 public JalviewStructureDisplayI getOpenedStructureViewer()
1307 return sViewer == null ? null : sViewer.sview;