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.FTSDataColumnPreferences;
35 import jalview.fts.core.FTSRestRequest;
36 import jalview.fts.core.FTSRestResponse;
37 import jalview.fts.service.pdb.PDBFTSRestClient;
38 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
39 import jalview.gui.structurechooser.StructureChooserQuerySource;
40 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
41 import jalview.io.DataSourceType;
42 import jalview.jbgui.FilterOption;
43 import jalview.jbgui.GStructureChooser;
44 import jalview.structure.StructureMapping;
45 import jalview.structure.StructureSelectionManager;
46 import jalview.util.MessageManager;
47 import jalview.ws.DBRefFetcher;
48 import jalview.ws.sifts.SiftsSettings;
50 import java.awt.event.ItemEvent;
51 import java.util.ArrayList;
52 import java.util.Collection;
53 import java.util.HashSet;
54 import java.util.LinkedHashSet;
55 import java.util.List;
56 import java.util.Objects;
58 import java.util.Vector;
59 import java.util.concurrent.CompletableFuture;
60 import java.util.concurrent.Executor;
61 import java.util.concurrent.Executors;
63 import javax.swing.JCheckBox;
64 import javax.swing.JComboBox;
65 import javax.swing.JLabel;
66 import javax.swing.JTable;
67 import javax.swing.SwingUtilities;
68 import javax.swing.table.AbstractTableModel;
71 * Provides the behaviors for the Structure chooser Panel
76 @SuppressWarnings("serial")
77 public class StructureChooser extends GStructureChooser
78 implements IProgressIndicator
80 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
82 private SequenceI selectedSequence;
84 private SequenceI[] selectedSequences;
86 private IProgressIndicator progressIndicator;
88 private Collection<FTSData> discoveredStructuresSet;
90 private StructureChooserQuerySource data;
93 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
95 return data.getDocFieldPrefs();
98 private String selectedPdbFileName;
100 private boolean isValidPBDEntry;
102 private boolean cachedPDBExists;
104 private Collection<FTSData> lastDiscoveredStructuresSet;
106 private static StructureViewer lastTargetedView = null;
108 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
111 // which FTS engine to use
112 data = StructureChooserQuerySource
113 .getQuerySourceFor(selectedSeqs);
117 this.selectedSequence = selectedSeq;
118 this.selectedSequences = selectedSeqs;
119 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
125 * Initializes parameters used by the Structure Chooser Panel
127 protected void init()
129 if (!Jalview.isHeadlessMode())
131 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
134 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
136 // ensure a filter option is in force for search
137 populateFilterComboBox(true, cachedPDBExists);
138 // todo change to futures I guess
140 final Runnable discoverPDBStructures = new Runnable()
145 // looks for any existing structures already loaded
146 // for the sequences (the cached ones)
147 // then queries the StructureChooserQuerySource to
148 // discover more structures.
150 // Possible optimisation is to only begin querying
151 // the structure chooser if there are no cached structures.
153 long startTime = System.currentTimeMillis();
154 updateProgressIndicator(MessageManager
155 .getString("status.loading_cached_pdb_entries"), startTime);
156 loadLocalCachedPDBEntries();
157 updateProgressIndicator(null, startTime);
158 updateProgressIndicator(MessageManager.getString(
159 "status.searching_for_pdb_structures"), startTime);
160 fetchStructuresMetaData();
161 // revise filter options if no results were found
162 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
163 discoverStructureViews();
164 updateProgressIndicator(null, startTime);
165 mainFrame.setVisible(true);
169 final List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
171 final Runnable discoverCanonicalDBrefs = new Runnable()
176 long progressId = System.currentTimeMillis();
178 int y = seqsWithoutSourceDBRef.size();
179 setProgressBar(MessageManager.formatMessage(
180 "status.fetching_dbrefs_for_sequences_without_valid_refs",
182 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
183 .toArray(new SequenceI[y]);
184 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
185 dbRefFetcher.fetchDBRefs(true);
187 setProgressBar("Fetch complete.", progressId); // todo i18n
189 SwingUtilities.invokeLater(discoverPDBStructures);
193 Executors.defaultThreadFactory().newThread(new Runnable()
198 for (SequenceI seq : selectedSequences)
202 int dbRef = ThreeDBStructureChooserQuerySource
203 .checkUniprotRefs(seq.getDBRefs());
206 seqsWithoutSourceDBRef.add(seq);
210 // retrieve database refs for protein sequences
211 if (!seqsWithoutSourceDBRef.isEmpty())
213 JvOptionPane.newOptionDialog(Desktop.getDesktop())
214 .setResponseHandler(0, discoverCanonicalDBrefs)
215 .setResponseHandler(1, discoverPDBStructures)
216 .showDialog(MessageManager.formatMessage("label.fetch_references_for",seqsWithoutSourceDBRef.size()), MessageManager.getString(
217 "label.fetch_uniprot_references"),
218 JvOptionPane.YES_NO_OPTION,
219 JvOptionPane.PLAIN_MESSAGE, null, new Object[]
220 { MessageManager.getString("action.ok"),
221 MessageManager.getString("action.cancel") },
222 MessageManager.getString("action.ok"));
224 // get structures directly
225 Executors.defaultThreadFactory().newThread(discoverPDBStructures).start();
233 * Builds a drop-down choice list of existing structure viewers to which new
234 * structures may be added. If this list is empty then it, and the 'Add'
235 * button, are hidden.
237 private void discoverStructureViews()
239 if (Desktop.instance != null)
241 targetView.removeAllItems();
242 if (lastTargetedView != null && !lastTargetedView.isVisible())
244 lastTargetedView = null;
246 int linkedViewsAt = 0;
247 for (StructureViewerBase view : Desktop.instance
248 .getStructureViewers(null, null))
250 StructureViewer viewHandler = (lastTargetedView != null
251 && lastTargetedView.sview == view) ? lastTargetedView
252 : StructureViewer.reconfigure(view);
254 if (view.isLinkedWith(ap))
256 targetView.insertItemAt(viewHandler, linkedViewsAt++);
260 targetView.addItem(viewHandler);
265 * show option to Add to viewer if at least 1 viewer found
267 targetView.setVisible(false);
268 if (targetView.getItemCount() > 0)
270 targetView.setVisible(true);
271 if (lastTargetedView != null)
273 targetView.setSelectedItem(lastTargetedView);
277 targetView.setSelectedIndex(0);
280 btn_add.setVisible(targetView.isVisible());
285 * Updates the progress indicator with the specified message
288 * displayed message for the operation
290 * unique handle for this indicator
292 protected void updateProgressIndicator(String message, long id)
294 if (progressIndicator != null)
296 progressIndicator.setProgressBar(message, id);
301 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
304 void fetchStructuresMetaData()
306 long startTime = System.currentTimeMillis();
307 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
308 .getStructureSummaryFields();
310 discoveredStructuresSet = new LinkedHashSet<>();
311 HashSet<String> errors = new HashSet<>();
313 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
316 for (SequenceI seq : selectedSequences)
319 FTSRestResponse resultList;
322 resultList = data.fetchStructuresMetaData(seq, wantedFields,
323 selectedFilterOpt, !chk_invertFilter.isSelected());
324 // null response means the FTSengine didn't yield a query for this
325 // consider designing a special exception if we really wanted to be OOCrazy
326 if (resultList==null)
330 } catch (Exception e)
333 errors.add(e.getMessage());
336 if (resultList.getSearchSummary() != null
337 && !resultList.getSearchSummary().isEmpty())
339 discoveredStructuresSet.addAll(resultList.getSearchSummary());
343 int noOfStructuresFound = 0;
344 String totalTime = (System.currentTimeMillis() - startTime)
346 if (discoveredStructuresSet != null
347 && !discoveredStructuresSet.isEmpty())
350 .setModel(data.getTableModel(discoveredStructuresSet));
352 noOfStructuresFound = discoveredStructuresSet.size();
353 lastDiscoveredStructuresSet=discoveredStructuresSet;
354 mainFrame.setTitle(MessageManager.formatMessage(
355 "label.structure_chooser_no_of_structures",
356 noOfStructuresFound, totalTime));
360 mainFrame.setTitle(MessageManager
361 .getString("label.structure_chooser_manual_association"));
362 if (errors.size() > 0)
364 StringBuilder errorMsg = new StringBuilder();
365 for (String error : errors)
367 errorMsg.append(error).append("\n");
369 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
370 MessageManager.getString("label.pdb_web-service_error"),
371 JvOptionPane.ERROR_MESSAGE);
376 protected void loadLocalCachedPDBEntries()
378 ArrayList<CachedPDB> entries = new ArrayList<>();
379 for (SequenceI seq : selectedSequences)
381 if (seq.getDatasetSequence() != null
382 && seq.getDatasetSequence().getAllPDBEntries() != null)
384 for (PDBEntry pdbEntry : seq.getDatasetSequence()
387 if (pdbEntry.getFile() != null)
389 entries.add(new CachedPDB(seq, pdbEntry));
394 cachedPDBExists = !entries.isEmpty();
395 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
396 tbl_local_pdb.setModel(tableModelx);
400 * Filters a given list of discovered structures based on supplied argument
402 * @param fieldToFilterBy
403 * the field to filter by
405 void filterResultSet(final String fieldToFilterBy)
407 Thread filterThread = new Thread(new Runnable()
413 long startTime = System.currentTimeMillis();
414 lbl_loading.setVisible(true);
415 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
416 .getStructureSummaryFields();
417 Collection<FTSData> filteredResponse = new HashSet<>();
418 HashSet<String> errors = new HashSet<>();
420 for (SequenceI seq : selectedSequences)
423 FTSRestResponse resultList;
426 resultList = data.selectFirstRankedQuery(seq, discoveredStructuresSet,wantedFields,
427 fieldToFilterBy, !chk_invertFilter.isSelected());
429 } catch (Exception e)
432 errors.add(e.getMessage());
435 if (resultList.getSearchSummary() != null
436 && !resultList.getSearchSummary().isEmpty())
438 filteredResponse.addAll(resultList.getSearchSummary());
442 String totalTime = (System.currentTimeMillis() - startTime)
444 if (!filteredResponse.isEmpty())
446 final int filterResponseCount = filteredResponse.size();
447 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
448 reorderedStructuresSet.addAll(filteredResponse);
449 reorderedStructuresSet.addAll(discoveredStructuresSet);
451 .setModel(data.getTableModel(reorderedStructuresSet));
453 FTSRestResponse.configureTableColumn(getResultTable(),
454 wantedFields, tempUserPrefs);
455 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
456 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
457 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
458 // Update table selection model here
459 getResultTable().addRowSelectionInterval(0,
460 filterResponseCount - 1);
461 mainFrame.setTitle(MessageManager.formatMessage(
462 "label.structure_chooser_filter_time", totalTime));
466 mainFrame.setTitle(MessageManager.formatMessage(
467 "label.structure_chooser_filter_time", totalTime));
468 if (errors.size() > 0)
470 StringBuilder errorMsg = new StringBuilder();
471 for (String error : errors)
473 errorMsg.append(error).append("\n");
475 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
476 MessageManager.getString("label.pdb_web-service_error"),
477 JvOptionPane.ERROR_MESSAGE);
481 lbl_loading.setVisible(false);
483 validateSelections();
486 filterThread.start();
490 * Handles action event for btn_pdbFromFile
493 protected void pdbFromFile_actionPerformed()
495 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
498 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
499 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
500 chooser.setFileView(new jalview.io.JalviewFileView());
501 chooser.setDialogTitle(
502 MessageManager.formatMessage("label.select_pdb_file_for",
503 selectedSequence.getDisplayId(false)));
504 chooser.setToolTipText(MessageManager.formatMessage(
505 "label.load_pdb_file_associate_with_sequence",
506 selectedSequence.getDisplayId(false)));
508 int value = chooser.showOpenDialog(null);
509 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
511 selectedPdbFileName = chooser.getSelectedFile().getPath();
512 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
513 validateSelections();
518 * Populates the filter combo-box options dynamically depending on discovered
521 protected void populateFilterComboBox(boolean haveData,
522 boolean cachedPDBExist)
524 populateFilterComboBox(haveData, cachedPDBExist, null);
527 * Populates the filter combo-box options dynamically depending on discovered
530 protected void populateFilterComboBox(boolean haveData,
531 boolean cachedPDBExist, FilterOption lastSel)
535 * temporarily suspend the change listener behaviour
537 cmb_filterOption.removeItemListener(this);
539 cmb_filterOption.removeAllItems();
542 List<FilterOption> filters = data.getAvailableFilterOptions(VIEWS_FILTER);
543 data.updateAvailableFilterOptions(VIEWS_FILTER, filters, lastDiscoveredStructuresSet);
545 for (FilterOption filter:filters)
547 if (lastSel!=null && filter.equals(lastSel)) {
551 cmb_filterOption.addItem(filter);
554 cmb_filterOption.addItem(
555 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
556 "-", VIEWS_ENTER_ID, false,null));
557 cmb_filterOption.addItem(
558 new FilterOption(MessageManager.getString("label.from_file"),
559 "-", VIEWS_FROM_FILE, false,null));
563 FilterOption cachedOption = new FilterOption(
564 MessageManager.getString("label.cached_structures"), "-",
565 VIEWS_LOCAL_PDB, false,null);
566 cmb_filterOption.addItem(cachedOption);
568 cmb_filterOption.setSelectedItem(cachedOption);
573 cmb_filterOption.setSelectedIndex(selSet);
575 cmb_filterOption.addItemListener(this);
579 * Updates the displayed view based on the selected filter option
581 protected void updateCurrentView()
583 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
585 layout_switchableViews.show(pnl_switchableViews,
586 selectedFilterOpt.getView());
587 String filterTitle = mainFrame.getTitle();
588 mainFrame.setTitle(frameTitle);
589 chk_invertFilter.setVisible(false);
590 if (selectedFilterOpt.getView() == VIEWS_FILTER)
592 mainFrame.setTitle(filterTitle);
593 // TDB Query has no invert as yet
594 chk_invertFilter.setVisible(selectedFilterOpt.getQuerySource() instanceof PDBStructureChooserQuerySource);
596 if (data!=selectedFilterOpt.getQuerySource() || data.needsRefetch(selectedFilterOpt))
598 data = selectedFilterOpt.getQuerySource();
599 // rebuild the views completely, since prefs will also change
603 filterResultSet(selectedFilterOpt.getValue());
606 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
607 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
609 mainFrame.setTitle(MessageManager
610 .getString("label.structure_chooser_manual_association"));
611 idInputAssSeqPanel.loadCmbAssSeq();
612 fileChooserAssSeqPanel.loadCmbAssSeq();
614 validateSelections();
618 * Validates user selection and enables the 'Add' and 'New View' buttons if
619 * all parameters are correct (the Add button will only be visible if there is
620 * at least one existing structure viewer open). This basically means at least
621 * one structure selected and no error messages.
623 * The 'Superpose Structures' option is enabled if either more than one
624 * structure is selected, or the 'Add' to existing view option is enabled, and
625 * disabled if the only option is to open a new view of a single structure.
628 protected void validateSelections()
630 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
632 btn_add.setEnabled(false);
633 String currentView = selectedFilterOpt.getView();
634 int selectedCount = 0;
635 if (currentView == VIEWS_FILTER)
637 selectedCount = getResultTable().getSelectedRows().length;
638 if (selectedCount > 0)
640 btn_add.setEnabled(true);
643 else if (currentView == VIEWS_LOCAL_PDB)
645 selectedCount = tbl_local_pdb.getSelectedRows().length;
646 if (selectedCount > 0)
648 btn_add.setEnabled(true);
651 else if (currentView == VIEWS_ENTER_ID)
653 validateAssociationEnterPdb();
655 else if (currentView == VIEWS_FROM_FILE)
657 validateAssociationFromFile();
660 btn_newView.setEnabled(btn_add.isEnabled());
663 * enable 'Superpose' option if more than one structure is selected,
664 * or there are view(s) available to add structure(s) to
667 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
671 * Validates inputs from the Manual PDB entry panel
673 protected void validateAssociationEnterPdb()
675 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
676 .getCmb_assSeq().getSelectedItem();
677 lbl_pdbManualFetchStatus.setIcon(errorImage);
678 lbl_pdbManualFetchStatus.setToolTipText("");
679 if (txt_search.getText().length() > 0)
681 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
682 MessageManager.formatMessage("info.no_pdb_entry_found_for",
683 txt_search.getText())));
686 if (errorWarning.length() > 0)
688 lbl_pdbManualFetchStatus.setIcon(warningImage);
689 lbl_pdbManualFetchStatus.setToolTipText(
690 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
693 if (selectedSequences.length == 1 || !assSeqOpt.getName()
694 .equalsIgnoreCase("-Select Associated Seq-"))
696 txt_search.setEnabled(true);
699 btn_add.setEnabled(true);
700 lbl_pdbManualFetchStatus.setToolTipText("");
701 lbl_pdbManualFetchStatus.setIcon(goodImage);
706 txt_search.setEnabled(false);
707 lbl_pdbManualFetchStatus.setIcon(errorImage);
712 * Validates inputs for the manual PDB file selection options
714 protected void validateAssociationFromFile()
716 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
717 .getCmb_assSeq().getSelectedItem();
718 lbl_fromFileStatus.setIcon(errorImage);
719 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
720 .getName().equalsIgnoreCase("-Select Associated Seq-")))
722 btn_pdbFromFile.setEnabled(true);
723 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
725 btn_add.setEnabled(true);
726 lbl_fromFileStatus.setIcon(goodImage);
731 btn_pdbFromFile.setEnabled(false);
732 lbl_fromFileStatus.setIcon(errorImage);
737 protected void cmbAssSeqStateChanged()
739 validateSelections();
743 * Handles the state change event for the 'filter' combo-box and 'invert'
747 protected void stateChanged(ItemEvent e)
749 if (e.getSource() instanceof JCheckBox)
755 if (e.getStateChange() == ItemEvent.SELECTED)
764 * select structures for viewing by their PDB IDs
767 * @return true if structures were found and marked as selected
769 public boolean selectStructure(String... pdbids)
771 boolean found = false;
773 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
775 String currentView = selectedFilterOpt.getView();
776 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
777 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
779 if (restable == null)
781 // can't select (enter PDB ID, or load file - need to also select which
782 // sequence to associate with)
786 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
787 for (int r = 0; r < restable.getRowCount(); r++)
789 for (int p = 0; p < pdbids.length; p++)
791 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
792 .equalsIgnoreCase(pdbids[p]))
794 restable.setRowSelectionInterval(r, r);
803 * Handles the 'New View' action
806 protected void newView_ActionPerformed()
808 targetView.setSelectedItem(null);
809 showStructures(false);
813 * Handles the 'Add to existing viewer' action
816 protected void add_ActionPerformed()
818 showStructures(false);
822 * structure viewer opened by this dialog, or null
824 private StructureViewer sViewer = null;
826 public void showStructures(boolean waitUntilFinished)
829 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
831 final int preferredHeight = pnl_filter.getHeight();
833 Runnable viewStruc = new Runnable()
838 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
840 String currentView = selectedFilterOpt.getView();
841 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
844 if (currentView == VIEWS_FILTER)
846 int[] selectedRows = restable.getSelectedRows();
847 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
848 List<SequenceI> selectedSeqsToView = new ArrayList<>();
849 pdbEntriesToView = data.collectSelectedRows(restable,selectedRows,selectedSeqsToView);
851 SequenceI[] selectedSeqs = selectedSeqsToView
852 .toArray(new SequenceI[selectedSeqsToView.size()]);
853 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
856 else if (currentView == VIEWS_LOCAL_PDB)
858 int[] selectedRows = tbl_local_pdb.getSelectedRows();
859 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
861 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
863 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
865 List<SequenceI> selectedSeqsToView = new ArrayList<>();
866 for (int row : selectedRows)
868 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb.getModel()).getPDBEntryAt(row).getPdbEntry();
870 pdbEntriesToView[count++] = pdbEntry;
871 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
872 .getValueAt(row, refSeqColIndex);
873 selectedSeqsToView.add(selectedSeq);
875 SequenceI[] selectedSeqs = selectedSeqsToView
876 .toArray(new SequenceI[selectedSeqsToView.size()]);
877 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
880 else if (currentView == VIEWS_ENTER_ID)
882 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
883 .getCmb_assSeq().getSelectedItem()).getSequence();
884 if (userSelectedSeq != null)
886 selectedSequence = userSelectedSeq;
888 String pdbIdStr = txt_search.getText();
889 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
890 if (pdbEntry == null)
892 pdbEntry = new PDBEntry();
893 if (pdbIdStr.split(":").length > 1)
895 pdbEntry.setId(pdbIdStr.split(":")[0]);
896 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
900 pdbEntry.setId(pdbIdStr);
902 pdbEntry.setType(PDBEntry.Type.PDB);
903 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
906 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
907 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
909 { selectedSequence });
911 else if (currentView == VIEWS_FROM_FILE)
913 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
914 .getCmb_assSeq().getSelectedItem()).getSequence();
915 if (userSelectedSeq != null)
917 selectedSequence = userSelectedSeq;
919 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
920 .associatePdbWithSeq(selectedPdbFileName,
921 DataSourceType.FILE, selectedSequence, true,
924 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
926 { selectedSequence });
928 SwingUtilities.invokeLater(new Runnable()
933 closeAction(preferredHeight);
939 Thread runner = new Thread(viewStruc);
941 if (waitUntilFinished)
943 while (sViewer == null ? runner.isAlive()
944 : (sViewer.sview == null ? true
945 : !sViewer.sview.hasMapping()))
950 } catch (InterruptedException ie)
959 * Answers a structure viewer (new or existing) configured to superimpose
960 * added structures or not according to the user's choice
965 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
967 Object sv = targetView.getSelectedItem();
969 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
973 * Adds PDB structures to a new or existing structure viewer
976 * @param pdbEntriesToView
981 private StructureViewer launchStructureViewer(
982 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
983 final AlignmentPanel alignPanel, SequenceI[] sequences)
985 long progressId = sequences.hashCode();
986 setProgressBar(MessageManager
987 .getString("status.launching_3d_structure_viewer"), progressId);
988 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
989 boolean superimpose = chk_superpose.isSelected();
990 theViewer.setSuperpose(superimpose);
993 * remember user's choice of superimpose or not
995 Cache.setProperty(AUTOSUPERIMPOSE,
996 Boolean.valueOf(superimpose).toString());
998 setProgressBar(null, progressId);
999 if (SiftsSettings.isMapWithSifts())
1001 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1003 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1004 // real PDB ID. For moment, we can also safely do this if there is already
1005 // a known mapping between the PDBEntry and the sequence.
1006 for (SequenceI seq : sequences)
1008 PDBEntry pdbe = pdbEntriesToView[p++];
1009 if (pdbe != null && pdbe.getFile() != null)
1011 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1012 if (smm != null && smm.length > 0)
1014 for (StructureMapping sm : smm)
1016 if (sm.getSequence() == seq)
1023 if (seq.getPrimaryDBRefs().isEmpty())
1025 seqsWithoutSourceDBRef.add(seq);
1029 if (!seqsWithoutSourceDBRef.isEmpty())
1031 int y = seqsWithoutSourceDBRef.size();
1032 setProgressBar(MessageManager.formatMessage(
1033 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1035 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1036 .toArray(new SequenceI[y]);
1037 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1038 dbRefFetcher.fetchDBRefs(true);
1040 setProgressBar("Fetch complete.", progressId); // todo i18n
1043 if (pdbEntriesToView.length > 1)
1046 MessageManager.getString(
1047 "status.fetching_3d_structures_for_selected_entries"),
1049 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1053 setProgressBar(MessageManager.formatMessage(
1054 "status.fetching_3d_structures_for",
1055 pdbEntriesToView[0].getId()), progressId);
1056 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1058 setProgressBar(null, progressId);
1059 // remember the last viewer we used...
1060 lastTargetedView = theViewer;
1065 * Populates the combo-box used in associating manually fetched structures to
1066 * a unique sequence when more than one sequence selection is made.
1069 protected void populateCmbAssociateSeqOptions(
1070 JComboBox<AssociateSeqOptions> cmb_assSeq,
1071 JLabel lbl_associateSeq)
1073 cmb_assSeq.removeAllItems();
1075 new AssociateSeqOptions("-Select Associated Seq-", null));
1076 lbl_associateSeq.setVisible(false);
1077 if (selectedSequences.length > 1)
1079 for (SequenceI seq : selectedSequences)
1081 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1086 String seqName = selectedSequence.getDisplayId(false);
1087 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1088 lbl_associateSeq.setText(seqName);
1089 lbl_associateSeq.setVisible(true);
1090 cmb_assSeq.setVisible(false);
1094 protected boolean isStructuresDiscovered()
1096 return discoveredStructuresSet != null
1097 && !discoveredStructuresSet.isEmpty();
1100 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1102 // Doing a search for "1" or "1c" is valuable?
1103 // Those work but are enormously slow.
1106 protected void txt_search_ActionPerformed()
1108 String text = txt_search.getText().trim();
1109 if (text.length() >= PDB_ID_MIN)
1116 errorWarning.setLength(0);
1117 isValidPBDEntry = false;
1118 if (text.length() > 0)
1120 // TODO move this pdb id search into the PDB specific
1122 // for moment, it will work fine as is because it is self-contained
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 FTSRestClientI 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();
1170 //populateFilterComboBox(true, cachedPDBExists);
1173 ((FilterOption) cmb_filterOption.getSelectedItem())
1177 refreshThread.start();
1181 public class PDBEntryTableModel extends AbstractTableModel
1183 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1186 private List<CachedPDB> pdbEntries;
1188 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1190 this.pdbEntries = new ArrayList<>(pdbEntries);
1194 public String getColumnName(int columnIndex)
1196 return columns[columnIndex];
1200 public int getRowCount()
1202 return pdbEntries.size();
1206 public int getColumnCount()
1208 return columns.length;
1212 public boolean isCellEditable(int row, int column)
1218 public Object getValueAt(int rowIndex, int columnIndex)
1220 Object value = "??";
1221 CachedPDB entry = pdbEntries.get(rowIndex);
1222 switch (columnIndex)
1225 value = entry.getSequence();
1228 value = entry.getQualifiedId();
1231 value = entry.getPdbEntry().getChainCode() == null ? "_"
1232 : entry.getPdbEntry().getChainCode();
1235 value = entry.getPdbEntry().getType();
1238 value = entry.getPdbEntry().getFile();
1245 public Class<?> getColumnClass(int columnIndex)
1247 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1250 public CachedPDB getPDBEntryAt(int row)
1252 return pdbEntries.get(row);
1257 private class CachedPDB
1259 private SequenceI sequence;
1261 private PDBEntry pdbEntry;
1263 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1265 this.sequence = sequence;
1266 this.pdbEntry = pdbEntry;
1269 public String getQualifiedId()
1271 if (pdbEntry.hasProvider())
1273 return pdbEntry.getProvider()+":"+pdbEntry.getId();
1275 return pdbEntry.toString();
1278 public SequenceI getSequence()
1283 public PDBEntry getPdbEntry()
1290 private IProgressIndicator progressBar;
1293 public void setProgressBar(String message, long id)
1295 progressBar.setProgressBar(message, id);
1299 public void registerHandler(long id, IProgressIndicatorHandler handler)
1301 progressBar.registerHandler(id, handler);
1305 public boolean operationInProgress()
1307 return progressBar.operationInProgress();
1310 public JalviewStructureDisplayI getOpenedStructureViewer()
1312 return sViewer == null ? null : sViewer.sview;
1316 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1318 data.setDocFieldPrefs(newPrefs);