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 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 Desktop desktop = Desktop.getInstance();
149 targetView.removeAllItems();
150 if (desktop.lastTargetedView != null
151 && !desktop.lastTargetedView.isVisible())
153 desktop.lastTargetedView = null;
155 int linkedViewsAt = 0;
156 for (StructureViewerBase view : desktop
157 .getStructureViewers(null, null))
159 StructureViewer viewHandler = (desktop.lastTargetedView != null
160 && desktop.lastTargetedView.sview == view)
161 ? desktop.lastTargetedView
162 : StructureViewer.reconfigure(view);
164 if (view.isLinkedWith(ap))
166 targetView.insertItemAt(viewHandler,
171 targetView.addItem(viewHandler);
176 * show option to Add to viewer if at least 1 viewer found
178 targetView.setVisible(false);
179 if (targetView.getItemCount() > 0)
181 targetView.setVisible(true);
182 if (desktop.lastTargetedView != null)
184 targetView.setSelectedItem(desktop.lastTargetedView);
188 targetView.setSelectedIndex(0);
191 btn_add.setVisible(targetView.isVisible());
196 * Updates the progress indicator with the specified message
199 * displayed message for the operation
201 * unique handle for this indicator
203 protected void updateProgressIndicator(String message, long id)
205 if (progressIndicator != null)
207 progressIndicator.setProgressBar(message, id);
212 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
215 void fetchStructuresMetaData()
217 long startTime = System.currentTimeMillis();
218 pdbRestClient = PDBFTSRestClient.getInstance();
219 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
220 .getStructureSummaryFields();
222 discoveredStructuresSet = new LinkedHashSet<>();
223 HashSet<String> errors = new HashSet<>();
224 for (SequenceI seq : selectedSequences)
226 FTSRestRequest pdbRequest = new FTSRestRequest();
227 pdbRequest.setAllowEmptySeq(false);
228 pdbRequest.setResponseSize(500);
229 pdbRequest.setFieldToSearchBy("(");
230 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
232 pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
233 !chk_invertFilter.isSelected());
234 pdbRequest.setWantedFields(wantedFields);
235 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
236 pdbRequest.setAssociatedSequence(seq);
237 FTSRestResponse resultList;
240 resultList = pdbRestClient.executeRequest(pdbRequest);
241 } catch (Exception e)
244 errors.add(e.getMessage());
247 lastPdbRequest = pdbRequest;
248 if (resultList.getSearchSummary() != null
249 && !resultList.getSearchSummary().isEmpty())
251 discoveredStructuresSet.addAll(resultList.getSearchSummary());
255 int noOfStructuresFound = 0;
256 String totalTime = (System.currentTimeMillis() - startTime)
258 if (discoveredStructuresSet != null
259 && !discoveredStructuresSet.isEmpty())
261 getResultTable().setModel(FTSRestResponse
262 .getTableModel(lastPdbRequest, discoveredStructuresSet));
263 noOfStructuresFound = discoveredStructuresSet.size();
264 mainFrame.setTitle(MessageManager.formatMessage(
265 "label.structure_chooser_no_of_structures",
266 noOfStructuresFound, totalTime));
270 mainFrame.setTitle(MessageManager
271 .getString("label.structure_chooser_manual_association"));
272 if (errors.size() > 0)
274 StringBuilder errorMsg = new StringBuilder();
275 for (String error : errors)
277 errorMsg.append(error).append("\n");
279 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
280 MessageManager.getString("label.pdb_web-service_error"),
281 JvOptionPane.ERROR_MESSAGE);
286 protected void loadLocalCachedPDBEntries()
288 ArrayList<CachedPDB> entries = new ArrayList<>();
289 for (SequenceI seq : selectedSequences)
291 if (seq.getDatasetSequence() != null
292 && seq.getDatasetSequence().getAllPDBEntries() != null)
294 for (PDBEntry pdbEntry : seq.getDatasetSequence()
297 if (pdbEntry.getFile() != null)
299 entries.add(new CachedPDB(seq, pdbEntry));
304 cachedPDBExists = !entries.isEmpty();
305 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
306 tbl_local_pdb.setModel(tableModelx);
310 * Builds a query string for a given sequences using its DBRef entries
313 * the sequences to build a query for
314 * @return the built query string
317 static String buildQuery(SequenceI seq)
319 boolean isPDBRefsFound = false;
320 boolean isUniProtRefsFound = false;
321 StringBuilder queryBuilder = new StringBuilder();
322 Set<String> seqRefs = new LinkedHashSet<>();
324 if (seq.getAllPDBEntries() != null
325 && queryBuilder.length() < MAX_QLENGTH)
327 for (PDBEntry entry : seq.getAllPDBEntries())
329 if (isValidSeqName(entry.getId()))
331 queryBuilder.append("pdb_id:").append(entry.getId().toLowerCase())
333 isPDBRefsFound = true;
338 List<DBRefEntry> refs = seq.getDBRefs();
339 if (refs != null && refs.size() != 0)
341 for (int ib = 0, nb = refs.size(); ib < nb; ib++)
343 DBRefEntry dbRef = refs.get(ib);
344 if (isValidSeqName(getDBRefId(dbRef))
345 && queryBuilder.length() < MAX_QLENGTH)
347 if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
349 queryBuilder.append("uniprot_accession:")
350 .append(getDBRefId(dbRef)).append(" OR ");
351 queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
353 isUniProtRefsFound = true;
355 else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
358 queryBuilder.append("pdb_id:")
359 .append(getDBRefId(dbRef).toLowerCase()).append(" OR ");
360 isPDBRefsFound = true;
364 seqRefs.add(getDBRefId(dbRef));
370 if (!isPDBRefsFound && !isUniProtRefsFound)
372 String seqName = seq.getName();
373 seqName = sanitizeSeqName(seqName);
374 String[] names = seqName.toLowerCase().split("\\|");
375 for (String name : names)
377 // System.out.println("Found name : " + name);
379 if (isValidSeqName(name))
385 for (String seqRef : seqRefs)
387 queryBuilder.append("text:").append(seqRef).append(" OR ");
391 int endIndex = queryBuilder.lastIndexOf(" OR ");
392 if (queryBuilder.toString().length() < 6)
396 String query = queryBuilder.toString().substring(0, endIndex);
401 * Remove the following special characters from input string +, -, &, !, (, ),
402 * {, }, [, ], ^, ", ~, *, ?, :, \
407 static String sanitizeSeqName(String seqName)
409 Objects.requireNonNull(seqName);
410 return seqName.replaceAll("\\[\\d*\\]", "")
411 .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
415 * Ensures sequence ref names are not less than 3 characters and does not
416 * contain a database name
421 static boolean isValidSeqName(String seqName)
423 // System.out.println("seqName : " + seqName);
424 String ignoreList = "pdb,uniprot,swiss-prot";
425 if (seqName.length() < 3)
429 if (seqName.contains(":"))
433 seqName = seqName.toLowerCase();
434 for (String ignoredEntry : ignoreList.split(","))
436 if (seqName.contains(ignoredEntry))
444 static String getDBRefId(DBRefEntry dbRef)
446 String ref = dbRef.getAccessionId().replaceAll("GO:", "");
451 * Filters a given list of discovered structures based on supplied argument
453 * @param fieldToFilterBy
454 * the field to filter by
456 void filterResultSet(final String fieldToFilterBy)
458 Thread filterThread = new Thread(new Runnable()
463 long startTime = System.currentTimeMillis();
464 pdbRestClient = PDBFTSRestClient.getInstance();
465 lbl_loading.setVisible(true);
466 Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
467 .getStructureSummaryFields();
468 Collection<FTSData> filteredResponse = new HashSet<>();
469 HashSet<String> errors = new HashSet<>();
471 for (SequenceI seq : selectedSequences)
473 FTSRestRequest pdbRequest = new FTSRestRequest();
474 if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
476 pdbRequest.setAllowEmptySeq(false);
477 pdbRequest.setResponseSize(1);
478 pdbRequest.setFieldToSearchBy("(");
479 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
480 pdbRequest.setWantedFields(wantedFields);
481 pdbRequest.setAssociatedSequence(seq);
482 pdbRequest.setFacet(true);
483 pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
484 pdbRequest.setFacetPivotMinCount(1);
488 pdbRequest.setAllowEmptySeq(false);
489 pdbRequest.setResponseSize(1);
490 pdbRequest.setFieldToSearchBy("(");
491 pdbRequest.setFieldToSortBy(fieldToFilterBy,
492 !chk_invertFilter.isSelected());
493 pdbRequest.setSearchTerm(buildQuery(seq) + ")");
494 pdbRequest.setWantedFields(wantedFields);
495 pdbRequest.setAssociatedSequence(seq);
497 FTSRestResponse resultList;
500 resultList = pdbRestClient.executeRequest(pdbRequest);
501 } catch (Exception e)
504 errors.add(e.getMessage());
507 lastPdbRequest = pdbRequest;
508 if (resultList.getSearchSummary() != null
509 && !resultList.getSearchSummary().isEmpty())
511 filteredResponse.addAll(resultList.getSearchSummary());
515 String totalTime = (System.currentTimeMillis() - startTime)
517 if (!filteredResponse.isEmpty())
519 final int filterResponseCount = filteredResponse.size();
520 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
521 reorderedStructuresSet.addAll(filteredResponse);
522 reorderedStructuresSet.addAll(discoveredStructuresSet);
523 getResultTable().setModel(FTSRestResponse
524 .getTableModel(lastPdbRequest, reorderedStructuresSet));
526 FTSRestResponse.configureTableColumn(getResultTable(),
527 wantedFields, tempUserPrefs);
528 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
529 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
530 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
531 // Update table selection model here
532 getResultTable().addRowSelectionInterval(0,
533 filterResponseCount - 1);
534 mainFrame.setTitle(MessageManager.formatMessage(
535 "label.structure_chooser_filter_time", totalTime));
539 mainFrame.setTitle(MessageManager.formatMessage(
540 "label.structure_chooser_filter_time", totalTime));
541 if (errors.size() > 0)
543 StringBuilder errorMsg = new StringBuilder();
544 for (String error : errors)
546 errorMsg.append(error).append("\n");
548 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
549 MessageManager.getString("label.pdb_web-service_error"),
550 JvOptionPane.ERROR_MESSAGE);
554 lbl_loading.setVisible(false);
556 validateSelections();
559 filterThread.start();
563 * Handles action event for btn_pdbFromFile
566 protected void pdbFromFile_actionPerformed()
568 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and StructureChooser
570 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
571 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
572 chooser.setFileView(new jalview.io.JalviewFileView());
573 chooser.setDialogTitle(
574 MessageManager.formatMessage("label.select_pdb_file_for",
575 selectedSequence.getDisplayId(false)));
576 chooser.setToolTipText(MessageManager.formatMessage(
577 "label.load_pdb_file_associate_with_sequence",
578 selectedSequence.getDisplayId(false)));
580 int value = chooser.showOpenDialog(null);
581 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
583 selectedPdbFileName = chooser.getSelectedFile().getPath();
584 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
585 validateSelections();
590 * Populates the filter combo-box options dynamically depending on discovered
593 protected void populateFilterComboBox(boolean haveData,
594 boolean cachedPDBExist)
597 * temporarily suspend the change listener behaviour
599 cmb_filterOption.removeItemListener(this);
601 cmb_filterOption.removeAllItems();
604 cmb_filterOption.addItem(new FilterOption(
605 MessageManager.getString("label.best_quality"),
606 "overall_quality", VIEWS_FILTER, false));
607 cmb_filterOption.addItem(new FilterOption(
608 MessageManager.getString("label.best_resolution"),
609 "resolution", VIEWS_FILTER, false));
610 cmb_filterOption.addItem(new FilterOption(
611 MessageManager.getString("label.most_protein_chain"),
612 "number_of_protein_chains", VIEWS_FILTER, false));
613 cmb_filterOption.addItem(new FilterOption(
614 MessageManager.getString("label.most_bound_molecules"),
615 "number_of_bound_molecules", VIEWS_FILTER, false));
616 cmb_filterOption.addItem(new FilterOption(
617 MessageManager.getString("label.most_polymer_residues"),
618 "number_of_polymer_residues", VIEWS_FILTER, true));
620 cmb_filterOption.addItem(
621 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
622 "-", VIEWS_ENTER_ID, false));
623 cmb_filterOption.addItem(
624 new FilterOption(MessageManager.getString("label.from_file"),
625 "-", VIEWS_FROM_FILE, false));
629 FilterOption cachedOption = new FilterOption(
630 MessageManager.getString("label.cached_structures"),
631 "-", VIEWS_LOCAL_PDB, false);
632 cmb_filterOption.addItem(cachedOption);
633 cmb_filterOption.setSelectedItem(cachedOption);
636 cmb_filterOption.addItemListener(this);
640 * Updates the displayed view based on the selected filter option
642 protected void updateCurrentView()
644 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
646 layout_switchableViews.show(pnl_switchableViews,
647 selectedFilterOpt.getView());
648 String filterTitle = mainFrame.getTitle();
649 mainFrame.setTitle(frameTitle);
650 chk_invertFilter.setVisible(false);
651 if (selectedFilterOpt.getView() == VIEWS_FILTER)
653 mainFrame.setTitle(filterTitle);
654 chk_invertFilter.setVisible(true);
655 filterResultSet(selectedFilterOpt.getValue());
657 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
658 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
660 mainFrame.setTitle(MessageManager
661 .getString("label.structure_chooser_manual_association"));
662 idInputAssSeqPanel.loadCmbAssSeq();
663 fileChooserAssSeqPanel.loadCmbAssSeq();
665 validateSelections();
669 * Validates user selection and enables the 'Add' and 'New View' buttons if
670 * all parameters are correct (the Add button will only be visible if there is
671 * at least one existing structure viewer open). This basically means at least
672 * one structure selected and no error messages.
674 * The 'Superpose Structures' option is enabled if either more than one
675 * structure is selected, or the 'Add' to existing view option is enabled, and
676 * disabled if the only option is to open a new view of a single structure.
679 protected void validateSelections()
681 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
683 btn_add.setEnabled(false);
684 String currentView = selectedFilterOpt.getView();
685 int selectedCount = 0;
686 if (currentView == VIEWS_FILTER)
688 selectedCount = getResultTable().getSelectedRows().length;
689 if (selectedCount > 0)
691 btn_add.setEnabled(true);
694 else if (currentView == VIEWS_LOCAL_PDB)
696 selectedCount = tbl_local_pdb.getSelectedRows().length;
697 if (selectedCount > 0)
699 btn_add.setEnabled(true);
702 else if (currentView == VIEWS_ENTER_ID)
704 validateAssociationEnterPdb();
706 else if (currentView == VIEWS_FROM_FILE)
708 validateAssociationFromFile();
711 btn_newView.setEnabled(btn_add.isEnabled());
714 * enable 'Superpose' option if more than one structure is selected,
715 * or there are view(s) available to add structure(s) to
718 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
722 * Validates inputs from the Manual PDB entry panel
724 protected void validateAssociationEnterPdb()
726 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
727 .getCmb_assSeq().getSelectedItem();
728 lbl_pdbManualFetchStatus.setIcon(errorImage);
729 lbl_pdbManualFetchStatus.setToolTipText("");
730 if (txt_search.getText().length() > 0)
732 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
733 MessageManager.formatMessage("info.no_pdb_entry_found_for",
734 txt_search.getText())));
737 if (errorWarning.length() > 0)
739 lbl_pdbManualFetchStatus.setIcon(warningImage);
740 lbl_pdbManualFetchStatus.setToolTipText(
741 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
744 if (selectedSequences.length == 1 || !assSeqOpt.getName()
745 .equalsIgnoreCase("-Select Associated Seq-"))
747 txt_search.setEnabled(true);
750 btn_add.setEnabled(true);
751 lbl_pdbManualFetchStatus.setToolTipText("");
752 lbl_pdbManualFetchStatus.setIcon(goodImage);
757 txt_search.setEnabled(false);
758 lbl_pdbManualFetchStatus.setIcon(errorImage);
763 * Validates inputs for the manual PDB file selection options
765 protected void validateAssociationFromFile()
767 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
768 .getCmb_assSeq().getSelectedItem();
769 lbl_fromFileStatus.setIcon(errorImage);
770 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
771 .getName().equalsIgnoreCase("-Select Associated Seq-")))
773 btn_pdbFromFile.setEnabled(true);
774 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
776 btn_add.setEnabled(true);
777 lbl_fromFileStatus.setIcon(goodImage);
782 btn_pdbFromFile.setEnabled(false);
783 lbl_fromFileStatus.setIcon(errorImage);
788 protected void cmbAssSeqStateChanged()
790 validateSelections();
794 * Handles the state change event for the 'filter' combo-box and 'invert'
798 protected void stateChanged(ItemEvent e)
800 if (e.getSource() instanceof JCheckBox)
806 if (e.getStateChange() == ItemEvent.SELECTED)
815 * select structures for viewing by their PDB IDs
818 * @return true if structures were found and marked as selected
820 public boolean selectStructure(String... pdbids)
822 boolean found = false;
824 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
826 String currentView = selectedFilterOpt.getView();
827 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
828 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
830 if (restable == null)
832 // can't select (enter PDB ID, or load file - need to also select which
833 // sequence to associate with)
837 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
838 for (int r = 0; r < restable.getRowCount(); r++)
840 for (int p = 0; p < pdbids.length; p++)
842 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
843 .equalsIgnoreCase(pdbids[p]))
845 restable.setRowSelectionInterval(r, r);
854 * Handles the 'New View' action
857 protected void newView_ActionPerformed()
859 targetView.setSelectedItem(null);
860 showStructures(false);
864 * Handles the 'Add to existing viewer' action
867 protected void add_ActionPerformed()
869 showStructures(false);
873 * structure viewer opened by this dialog, or null
875 protected StructureViewer sViewer = null;
877 public void showStructures(boolean waitUntilFinished)
880 final int preferredHeight = pnl_filter.getHeight();
882 Runnable viewStruc = new Runnable()
887 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
889 String currentView = selectedFilterOpt.getView();
890 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
893 if (currentView == VIEWS_FILTER)
895 int pdbIdColIndex = restable.getColumn("PDB Id")
897 int refSeqColIndex = restable.getColumn("Ref Sequence")
899 int[] selectedRows = restable.getSelectedRows();
900 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
902 List<SequenceI> selectedSeqsToView = new ArrayList<>();
903 for (int row : selectedRows)
905 String pdbIdStr = restable
906 .getValueAt(row, pdbIdColIndex).toString();
907 SequenceI selectedSeq = (SequenceI) restable
908 .getValueAt(row, refSeqColIndex);
909 selectedSeqsToView.add(selectedSeq);
910 PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
911 if (pdbEntry == null)
913 pdbEntry = getFindEntry(pdbIdStr,
914 selectedSeq.getAllPDBEntries());
917 if (pdbEntry == null)
919 pdbEntry = new PDBEntry();
920 pdbEntry.setId(pdbIdStr);
921 pdbEntry.setType(PDBEntry.Type.PDB);
922 selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
924 pdbEntriesToView[count++] = pdbEntry;
926 SequenceI[] selectedSeqs = selectedSeqsToView
927 .toArray(new SequenceI[selectedSeqsToView.size()]);
928 sViewer = launchStructureViewer(ap, pdbEntriesToView,
931 else if (currentView == VIEWS_LOCAL_PDB)
933 int[] selectedRows = tbl_local_pdb.getSelectedRows();
934 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
936 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
938 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
940 List<SequenceI> selectedSeqsToView = new ArrayList<>();
941 for (int row : selectedRows)
943 PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
945 pdbEntriesToView[count++] = pdbEntry;
946 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
947 .getValueAt(row, refSeqColIndex);
948 selectedSeqsToView.add(selectedSeq);
950 SequenceI[] selectedSeqs = selectedSeqsToView
951 .toArray(new SequenceI[selectedSeqsToView.size()]);
952 sViewer = launchStructureViewer(ap, pdbEntriesToView,
955 else if (currentView == VIEWS_ENTER_ID)
957 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
958 .getCmb_assSeq().getSelectedItem()).getSequence();
959 if (userSelectedSeq != null)
961 selectedSequence = userSelectedSeq;
963 String pdbIdStr = txt_search.getText();
964 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
965 if (pdbEntry == null)
967 pdbEntry = new PDBEntry();
968 if (pdbIdStr.split(":").length > 1)
970 pdbEntry.setId(pdbIdStr.split(":")[0]);
971 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
975 pdbEntry.setId(pdbIdStr);
977 pdbEntry.setType(PDBEntry.Type.PDB);
978 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
981 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
982 sViewer = launchStructureViewer(ap, pdbEntriesToView,
984 { selectedSequence });
986 else if (currentView == VIEWS_FROM_FILE)
988 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
989 .getCmb_assSeq().getSelectedItem()).getSequence();
990 if (userSelectedSeq != null)
992 selectedSequence = userSelectedSeq;
994 PDBEntry fileEntry = AssociatePdbFileWithSeq
995 .associatePdbWithSeq(selectedPdbFileName,
996 DataSourceType.FILE, selectedSequence, true);
998 sViewer = launchStructureViewer(
1002 { selectedSequence });
1004 SwingUtilities.invokeLater(new Runnable()
1009 closeAction(preferredHeight);
1010 mainFrame.dispose();
1015 Thread runner = new Thread(viewStruc);
1017 if (waitUntilFinished)
1019 while (sViewer == null ? runner.isAlive()
1020 : (sViewer.sview == null ? true
1021 : !sViewer.sview.hasMapping()))
1026 } catch (InterruptedException ie)
1034 protected PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
1036 Objects.requireNonNull(id);
1037 Objects.requireNonNull(pdbEntries);
1038 PDBEntry foundEntry = null;
1039 for (PDBEntry entry : pdbEntries)
1041 if (entry.getId().equalsIgnoreCase(id))
1050 * Answers a structure viewer (new or existing) configured to superimpose
1051 * added structures or not according to the user's choice
1055 StructureViewer getTargetedStructureViewer()
1057 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1058 Object sv = (targetView == null ? null : targetView.getSelectedItem());
1060 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1064 * Adds PDB structures to a new or existing structure viewer
1067 * @param pdbEntriesToView
1069 * @param superimpose
1072 protected StructureViewer launchStructureViewer(
1073 AlignmentPanel ap, PDBEntry[] pdbEntriesToView,
1074 SequenceI[] selectedSeqs)
1076 boolean superimpose = chk_superpose.isSelected();
1078 * remember user's choice of superimpose or not
1080 Cache.setProperty(AUTOSUPERIMPOSE,
1081 Boolean.valueOf(superimpose).toString());
1082 return StructureViewer.launchStructureViewer(ap, pdbEntriesToView, selectedSeqs,
1083 superimpose, getTargetedStructureViewer(), progressBar);
1087 * Populates the combo-box used in associating manually fetched structures to
1088 * a unique sequence when more than one sequence selection is made.
1091 protected void populateCmbAssociateSeqOptions(
1092 JComboBox<AssociateSeqOptions> cmb_assSeq,
1093 JLabel lbl_associateSeq)
1095 cmb_assSeq.removeAllItems();
1097 new AssociateSeqOptions("-Select Associated Seq-", null));
1098 lbl_associateSeq.setVisible(false);
1099 if (selectedSequences.length > 1)
1101 for (SequenceI seq : selectedSequences)
1103 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1108 String seqName = selectedSequence.getDisplayId(false);
1109 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1110 lbl_associateSeq.setText(seqName);
1111 lbl_associateSeq.setVisible(true);
1112 cmb_assSeq.setVisible(false);
1116 protected boolean isStructuresDiscovered()
1118 return discoveredStructuresSet != null
1119 && !discoveredStructuresSet.isEmpty();
1122 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes this.
1123 // Doing a search for "1" or "1c" is valuable?
1124 // Those work but are enormously slow.
1127 protected void txt_search_ActionPerformed()
1129 String text = txt_search.getText().trim();
1130 if (text.length() >= PDB_ID_MIN)
1138 errorWarning.setLength(0);
1139 isValidPBDEntry = false;
1140 if (text.length() > 0)
1142 String searchTerm = text.toLowerCase();
1143 searchTerm = searchTerm.split(":")[0];
1144 // System.out.println(">>>>> search term : " + searchTerm);
1145 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1146 FTSRestRequest pdbRequest = new FTSRestRequest();
1147 pdbRequest.setAllowEmptySeq(false);
1148 pdbRequest.setResponseSize(1);
1149 pdbRequest.setFieldToSearchBy("(pdb_id:");
1150 pdbRequest.setWantedFields(wantedFields);
1151 pdbRequest.setSearchTerm(searchTerm + ")");
1152 pdbRequest.setAssociatedSequence(selectedSequence);
1153 pdbRestClient = PDBFTSRestClient.getInstance();
1154 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1155 FTSRestResponse resultList;
1158 resultList = pdbRestClient.executeRequest(pdbRequest);
1159 } catch (Exception e)
1161 errorWarning.append(e.getMessage());
1165 validateSelections();
1167 if (resultList.getSearchSummary() != null
1168 && resultList.getSearchSummary().size() > 0)
1170 isValidPBDEntry = true;
1173 validateSelections();
1180 protected void tabRefresh()
1182 if (selectedSequences != null)
1184 Thread refreshThread = new Thread(new Runnable()
1189 fetchStructuresMetaData();
1191 ((FilterOption) cmb_filterOption.getSelectedItem())
1195 refreshThread.start();
1199 public class PDBEntryTableModel extends AbstractTableModel
1201 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1204 private List<CachedPDB> pdbEntries;
1206 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1208 this.pdbEntries = new ArrayList<>(pdbEntries);
1212 public String getColumnName(int columnIndex)
1214 return columns[columnIndex];
1218 public int getRowCount()
1220 return pdbEntries.size();
1224 public int getColumnCount()
1226 return columns.length;
1230 public boolean isCellEditable(int row, int column)
1236 public Object getValueAt(int rowIndex, int columnIndex)
1238 Object value = "??";
1239 CachedPDB entry = pdbEntries.get(rowIndex);
1240 switch (columnIndex)
1243 value = entry.getSequence();
1246 value = entry.getPdbEntry();
1249 value = entry.getPdbEntry().getChainCode() == null ? "_"
1250 : entry.getPdbEntry().getChainCode();
1253 value = entry.getPdbEntry().getType();
1256 value = entry.getPdbEntry().getFile();
1263 public Class<?> getColumnClass(int columnIndex)
1265 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1268 public CachedPDB getPDBEntryAt(int row)
1270 return pdbEntries.get(row);
1275 private class CachedPDB
1277 private SequenceI sequence;
1279 private PDBEntry pdbEntry;
1281 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1283 this.sequence = sequence;
1284 this.pdbEntry = pdbEntry;
1287 public SequenceI getSequence()
1292 public PDBEntry getPdbEntry()
1299 private IProgressIndicator progressBar;
1302 public void setProgressBar(String message, long id)
1304 if (progressBar != null)
1306 progressBar.setProgressBar(message, id);
1311 public void registerHandler(long id, IProgressIndicatorHandler handler)
1313 progressBar.registerHandler(id, handler);
1317 public boolean operationInProgress()
1319 return progressBar.operationInProgress();
1322 public JalviewStructureDisplayI getOpenedStructureViewer()
1324 return sViewer == null ? null : sViewer.sview;