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.concurrent.Executors;
32 import javax.swing.JCheckBox;
33 import javax.swing.JComboBox;
34 import javax.swing.JLabel;
35 import javax.swing.JTable;
36 import javax.swing.SwingUtilities;
37 import javax.swing.table.AbstractTableModel;
39 import jalview.api.structures.JalviewStructureDisplayI;
40 import jalview.bin.Cache;
41 import jalview.bin.Jalview;
42 import jalview.datamodel.PDBEntry;
43 import jalview.datamodel.SequenceI;
44 import jalview.fts.api.FTSData;
45 import jalview.fts.api.FTSDataColumnI;
46 import jalview.fts.api.FTSRestClientI;
47 import jalview.fts.core.FTSDataColumnPreferences;
48 import jalview.fts.core.FTSRestRequest;
49 import jalview.fts.core.FTSRestResponse;
50 import jalview.fts.service.pdb.PDBFTSRestClient;
51 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
52 import jalview.gui.structurechooser.StructureChooserQuerySource;
53 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
54 import jalview.io.DataSourceType;
55 import jalview.jbgui.FilterOption;
56 import jalview.jbgui.GStructureChooser;
57 import jalview.structure.StructureMapping;
58 import jalview.structure.StructureSelectionManager;
59 import jalview.util.MessageManager;
60 import jalview.ws.DBRefFetcher;
61 import jalview.ws.seqfetcher.DbSourceProxy;
62 import jalview.ws.sifts.SiftsSettings;
65 * Provides the behaviors for the Structure chooser Panel
70 @SuppressWarnings("serial")
71 public class StructureChooser extends GStructureChooser
72 implements IProgressIndicator
74 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
77 * transient combo box choice for initiating 3db fetch
79 private static final String VIEWS_QUERYING_TDB = "QUERY_3DB";
81 private SequenceI selectedSequence;
83 private SequenceI[] selectedSequences;
85 private IProgressIndicator progressIndicator;
87 private Collection<FTSData> discoveredStructuresSet;
89 private StructureChooserQuerySource data;
92 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
94 return data.getDocFieldPrefs();
97 private String selectedPdbFileName;
99 private boolean isValidPBDEntry;
101 private boolean cachedPDBExists;
103 private Collection<FTSData> lastDiscoveredStructuresSet;
105 private boolean canQueryTDB = false;
107 private boolean notQueriedTDBYet = true;
109 List<SequenceI> seqsWithoutSourceDBRef = null;
111 private static StructureViewer lastTargetedView = null;
113 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
116 // which FTS engine to use
117 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
121 this.selectedSequence = selectedSeq;
122 this.selectedSequences = selectedSeqs;
123 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
129 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
130 * least one structure are discovered.
132 private void populateSeqsWithoutSourceDBRef()
134 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
135 boolean needCanonical = false;
136 for (SequenceI seq : selectedSequences)
140 int dbRef = ThreeDBStructureChooserQuerySource
141 .checkUniprotRefs(seq.getDBRefs());
146 // need to retrieve canonicals
147 needCanonical = true;
148 seqsWithoutSourceDBRef.add(seq);
152 // could be a sequence with pdb ref
153 if (seq.getAllPDBEntries() == null
154 || seq.getAllPDBEntries().size() == 0)
156 seqsWithoutSourceDBRef.add(seq);
162 // retrieve database refs for protein sequences
163 if (!seqsWithoutSourceDBRef.isEmpty())
168 notQueriedTDBYet = false;
174 * Initializes parameters used by the Structure Chooser Panel
176 protected void init()
178 if (!Jalview.isHeadlessMode())
180 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
183 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
185 Executors.defaultThreadFactory().newThread(new Runnable()
189 populateSeqsWithoutSourceDBRef();
190 initialStructureDiscovery();
198 private void initialStructureDiscovery()
200 // check which FTS engine to use
201 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
203 // ensure a filter option is in force for search
204 populateFilterComboBox(true, cachedPDBExists);
206 // looks for any existing structures already loaded
207 // for the sequences (the cached ones)
208 // then queries the StructureChooserQuerySource to
209 // discover more structures.
211 // Possible optimisation is to only begin querying
212 // the structure chooser if there are no cached structures.
214 long startTime = System.currentTimeMillis();
215 updateProgressIndicator(
216 MessageManager.getString("status.loading_cached_pdb_entries"),
218 loadLocalCachedPDBEntries();
219 updateProgressIndicator(null, startTime);
220 updateProgressIndicator(
221 MessageManager.getString("status.searching_for_pdb_structures"),
223 fetchStructuresMetaData();
224 // revise filter options if no results were found
225 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
226 discoverStructureViews();
227 updateProgressIndicator(null, startTime);
228 mainFrame.setVisible(true);
232 private void promptForTDBFetch()
234 final long progressId = System.currentTimeMillis();
236 // final action after prompting and discovering db refs
237 final Runnable strucDiscovery = new Runnable()
242 // TODO: warn if no accessions discovered
243 populateSeqsWithoutSourceDBRef();
244 // redo initial discovery - this time with 3d beacons
246 previousWantedFields=null;
248 initialStructureDiscovery();
252 // fetch db refs if OK pressed
253 final Runnable discoverCanonicalDBrefs = new Runnable()
258 populateSeqsWithoutSourceDBRef();
260 final int y = seqsWithoutSourceDBRef.size();
263 SwingUtilities.invokeLater(new Runnable() {
267 updateProgressIndicator(MessageManager.formatMessage(
268 "status.fetching_dbrefs_for_sequences_without_valid_refs",
274 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
275 .toArray(new SequenceI[y]);
276 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
277 progressBar, new DbSourceProxy[]
278 { new jalview.ws.dbsources.Uniprot() }, null, false);
280 // ideally this would also gracefully run with callbacks
281 dbRefFetcher.fetchDBRefs(true);
283 SwingUtilities.invokeLater(new Runnable() {
288 updateProgressIndicator("Fetch complete.", progressId); // todo i18n
290 // filter has been selected, so we set flag to remove ourselves
291 notQueriedTDBYet = false;
293 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
300 final Runnable revertview = new Runnable() {
302 if (lastSelected!=null) {
303 cmb_filterOption.setSelectedItem(lastSelected);
307 // need cancel and no to result in the discoverPDB action - mocked is
309 JvOptionPane.newOptionDialog(this)
310 .setResponseHandler(JvOptionPane.OK_OPTION,
311 discoverCanonicalDBrefs)
312 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
313 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
315 MessageManager.formatMessage(
316 "label.fetch_references_for_3dbeacons",
317 seqsWithoutSourceDBRef.size()),
319 .getString("label.3dbeacons"),
320 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
322 { MessageManager.getString("action.ok"),
323 MessageManager.getString("action.cancel") },
324 MessageManager.getString("action.ok"));
328 * Builds a drop-down choice list of existing structure viewers to which new
329 * structures may be added. If this list is empty then it, and the 'Add'
330 * button, are hidden.
332 private void discoverStructureViews()
334 if (Desktop.instance != null)
336 targetView.removeAllItems();
337 if (lastTargetedView != null && !lastTargetedView.isVisible())
339 lastTargetedView = null;
341 int linkedViewsAt = 0;
342 for (StructureViewerBase view : Desktop.instance
343 .getStructureViewers(null, null))
345 StructureViewer viewHandler = (lastTargetedView != null
346 && lastTargetedView.sview == view) ? lastTargetedView
347 : StructureViewer.reconfigure(view);
349 if (view.isLinkedWith(ap))
351 targetView.insertItemAt(viewHandler, linkedViewsAt++);
355 targetView.addItem(viewHandler);
360 * show option to Add to viewer if at least 1 viewer found
362 targetView.setVisible(false);
363 if (targetView.getItemCount() > 0)
365 targetView.setVisible(true);
366 if (lastTargetedView != null)
368 targetView.setSelectedItem(lastTargetedView);
372 targetView.setSelectedIndex(0);
375 btn_add.setVisible(targetView.isVisible());
380 * Updates the progress indicator with the specified message
383 * displayed message for the operation
385 * unique handle for this indicator
387 protected void updateProgressIndicator(String message, long id)
389 if (progressIndicator != null)
391 progressIndicator.setProgressBar(message, id);
396 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
399 void fetchStructuresMetaData()
401 long startTime = System.currentTimeMillis();
402 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
403 .getStructureSummaryFields();
405 discoveredStructuresSet = new LinkedHashSet<>();
406 HashSet<String> errors = new HashSet<>();
408 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
411 for (SequenceI seq : selectedSequences)
414 FTSRestResponse resultList;
417 resultList = data.fetchStructuresMetaData(seq, wantedFields,
418 selectedFilterOpt, !chk_invertFilter.isSelected());
419 // null response means the FTSengine didn't yield a query for this
420 // consider designing a special exception if we really wanted to be
422 if (resultList == null)
426 } catch (Exception e)
429 errors.add(e.getMessage());
432 if (resultList.getSearchSummary() != null
433 && !resultList.getSearchSummary().isEmpty())
435 discoveredStructuresSet.addAll(resultList.getSearchSummary());
439 int noOfStructuresFound = 0;
440 String totalTime = (System.currentTimeMillis() - startTime)
442 if (discoveredStructuresSet != null
443 && !discoveredStructuresSet.isEmpty())
446 .setModel(data.getTableModel(discoveredStructuresSet));
448 noOfStructuresFound = discoveredStructuresSet.size();
449 lastDiscoveredStructuresSet = discoveredStructuresSet;
450 mainFrame.setTitle(MessageManager.formatMessage(
451 "label.structure_chooser_no_of_structures",
452 noOfStructuresFound, totalTime));
456 mainFrame.setTitle(MessageManager
457 .getString("label.structure_chooser_manual_association"));
458 if (errors.size() > 0)
460 StringBuilder errorMsg = new StringBuilder();
461 for (String error : errors)
463 errorMsg.append(error).append("\n");
465 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
466 MessageManager.getString("label.pdb_web-service_error"),
467 JvOptionPane.ERROR_MESSAGE);
472 protected void loadLocalCachedPDBEntries()
474 ArrayList<CachedPDB> entries = new ArrayList<>();
475 for (SequenceI seq : selectedSequences)
477 if (seq.getDatasetSequence() != null
478 && seq.getDatasetSequence().getAllPDBEntries() != null)
480 for (PDBEntry pdbEntry : seq.getDatasetSequence()
483 if (pdbEntry.getFile() != null)
485 entries.add(new CachedPDB(seq, pdbEntry));
490 cachedPDBExists = !entries.isEmpty();
491 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
492 tbl_local_pdb.setModel(tableModelx);
496 * Filters a given list of discovered structures based on supplied argument
498 * @param fieldToFilterBy
499 * the field to filter by
501 void filterResultSet(final String fieldToFilterBy)
503 Thread filterThread = new Thread(new Runnable()
509 long startTime = System.currentTimeMillis();
510 lbl_loading.setVisible(true);
511 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
512 .getStructureSummaryFields();
513 Collection<FTSData> filteredResponse = new HashSet<>();
514 HashSet<String> errors = new HashSet<>();
516 for (SequenceI seq : selectedSequences)
519 FTSRestResponse resultList;
522 resultList = data.selectFirstRankedQuery(seq,
523 discoveredStructuresSet, wantedFields, fieldToFilterBy,
524 !chk_invertFilter.isSelected());
526 } catch (Exception e)
529 errors.add(e.getMessage());
532 if (resultList.getSearchSummary() != null
533 && !resultList.getSearchSummary().isEmpty())
535 filteredResponse.addAll(resultList.getSearchSummary());
539 String totalTime = (System.currentTimeMillis() - startTime)
541 if (!filteredResponse.isEmpty())
543 final int filterResponseCount = filteredResponse.size();
544 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
545 reorderedStructuresSet.addAll(filteredResponse);
546 reorderedStructuresSet.addAll(discoveredStructuresSet);
548 .setModel(data.getTableModel(reorderedStructuresSet));
550 FTSRestResponse.configureTableColumn(getResultTable(),
551 wantedFields, tempUserPrefs);
552 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
553 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
554 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
555 // Update table selection model here
556 getResultTable().addRowSelectionInterval(0,
557 filterResponseCount - 1);
558 mainFrame.setTitle(MessageManager.formatMessage(
559 "label.structure_chooser_filter_time", totalTime));
563 mainFrame.setTitle(MessageManager.formatMessage(
564 "label.structure_chooser_filter_time", totalTime));
565 if (errors.size() > 0)
567 StringBuilder errorMsg = new StringBuilder();
568 for (String error : errors)
570 errorMsg.append(error).append("\n");
572 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
573 MessageManager.getString("label.pdb_web-service_error"),
574 JvOptionPane.ERROR_MESSAGE);
578 lbl_loading.setVisible(false);
580 validateSelections();
583 filterThread.start();
587 * Handles action event for btn_pdbFromFile
590 protected void pdbFromFile_actionPerformed()
592 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
595 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
596 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
597 chooser.setFileView(new jalview.io.JalviewFileView());
598 chooser.setDialogTitle(
599 MessageManager.formatMessage("label.select_pdb_file_for",
600 selectedSequence.getDisplayId(false)));
601 chooser.setToolTipText(MessageManager.formatMessage(
602 "label.load_pdb_file_associate_with_sequence",
603 selectedSequence.getDisplayId(false)));
605 int value = chooser.showOpenDialog(null);
606 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
608 selectedPdbFileName = chooser.getSelectedFile().getPath();
609 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
610 validateSelections();
615 * Populates the filter combo-box options dynamically depending on discovered
618 protected void populateFilterComboBox(boolean haveData,
619 boolean cachedPDBExist)
621 populateFilterComboBox(haveData, cachedPDBExist, null);
625 * Populates the filter combo-box options dynamically depending on discovered
628 protected void populateFilterComboBox(boolean haveData,
629 boolean cachedPDBExist, FilterOption lastSel)
633 * temporarily suspend the change listener behaviour
635 cmb_filterOption.removeItemListener(this);
637 cmb_filterOption.removeAllItems();
640 List<FilterOption> filters = data
641 .getAvailableFilterOptions(VIEWS_FILTER);
642 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
643 lastDiscoveredStructuresSet);
645 for (FilterOption filter : filters)
647 if (lastSel != null && filter.equals(lastSel))
652 cmb_filterOption.addItem(filter);
656 cmb_filterOption.addItem(
657 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
658 "-", VIEWS_ENTER_ID, false, null));
659 cmb_filterOption.addItem(
660 new FilterOption(MessageManager.getString("label.from_file"),
661 "-", VIEWS_FROM_FILE, false, null));
662 if (canQueryTDB && notQueriedTDBYet)
664 FilterOption queryTDBOption = new FilterOption(
665 MessageManager.getString("label.search_3dbeacons"), "-",
666 VIEWS_QUERYING_TDB, false, null);
667 cmb_filterOption.addItem(queryTDBOption);
672 FilterOption cachedOption = new FilterOption(
673 MessageManager.getString("label.cached_structures"), "-",
674 VIEWS_LOCAL_PDB, false, null);
675 cmb_filterOption.addItem(cachedOption);
678 cmb_filterOption.setSelectedItem(cachedOption);
683 cmb_filterOption.setSelectedIndex(selSet);
685 cmb_filterOption.addItemListener(this);
689 * Updates the displayed view based on the selected filter option
691 protected void updateCurrentView()
693 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
696 // first check if we need to rebuild dialog
697 if (selectedFilterOpt.getView() == VIEWS_QUERYING_TDB)
702 if (lastSelected == selectedFilterOpt)
704 // don't need to do anything, probably
707 // otherwise, record selection
708 // and update the layout and dialog accordingly
709 lastSelected = selectedFilterOpt;
711 layout_switchableViews.show(pnl_switchableViews,
712 selectedFilterOpt.getView());
713 String filterTitle = mainFrame.getTitle();
714 mainFrame.setTitle(frameTitle);
715 chk_invertFilter.setVisible(false);
717 if (selectedFilterOpt.getView() == VIEWS_FILTER)
719 mainFrame.setTitle(filterTitle);
720 // TDB Query has no invert as yet
721 chk_invertFilter.setVisible(selectedFilterOpt
722 .getQuerySource() instanceof PDBStructureChooserQuerySource);
724 if (data != selectedFilterOpt.getQuerySource()
725 || data.needsRefetch(selectedFilterOpt))
727 data = selectedFilterOpt.getQuerySource();
728 // rebuild the views completely, since prefs will also change
734 filterResultSet(selectedFilterOpt.getValue());
737 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
738 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
740 mainFrame.setTitle(MessageManager
741 .getString("label.structure_chooser_manual_association"));
742 idInputAssSeqPanel.loadCmbAssSeq();
743 fileChooserAssSeqPanel.loadCmbAssSeq();
745 validateSelections();
749 * Validates user selection and enables the 'Add' and 'New View' buttons if
750 * all parameters are correct (the Add button will only be visible if there is
751 * at least one existing structure viewer open). This basically means at least
752 * one structure selected and no error messages.
754 * The 'Superpose Structures' option is enabled if either more than one
755 * structure is selected, or the 'Add' to existing view option is enabled, and
756 * disabled if the only option is to open a new view of a single structure.
759 protected void validateSelections()
761 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
763 btn_add.setEnabled(false);
764 String currentView = selectedFilterOpt.getView();
765 int selectedCount = 0;
766 if (currentView == VIEWS_FILTER)
768 selectedCount = getResultTable().getSelectedRows().length;
769 if (selectedCount > 0)
771 btn_add.setEnabled(true);
774 else if (currentView == VIEWS_LOCAL_PDB)
776 selectedCount = tbl_local_pdb.getSelectedRows().length;
777 if (selectedCount > 0)
779 btn_add.setEnabled(true);
782 else if (currentView == VIEWS_ENTER_ID)
784 validateAssociationEnterPdb();
786 else if (currentView == VIEWS_FROM_FILE)
788 validateAssociationFromFile();
791 btn_newView.setEnabled(btn_add.isEnabled());
794 * enable 'Superpose' option if more than one structure is selected,
795 * or there are view(s) available to add structure(s) to
798 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
802 * Validates inputs from the Manual PDB entry panel
804 protected void validateAssociationEnterPdb()
806 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
807 .getCmb_assSeq().getSelectedItem();
808 lbl_pdbManualFetchStatus.setIcon(errorImage);
809 lbl_pdbManualFetchStatus.setToolTipText("");
810 if (txt_search.getText().length() > 0)
812 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
813 MessageManager.formatMessage("info.no_pdb_entry_found_for",
814 txt_search.getText())));
817 if (errorWarning.length() > 0)
819 lbl_pdbManualFetchStatus.setIcon(warningImage);
820 lbl_pdbManualFetchStatus.setToolTipText(
821 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
824 if (selectedSequences.length == 1 || !assSeqOpt.getName()
825 .equalsIgnoreCase("-Select Associated Seq-"))
827 txt_search.setEnabled(true);
830 btn_add.setEnabled(true);
831 lbl_pdbManualFetchStatus.setToolTipText("");
832 lbl_pdbManualFetchStatus.setIcon(goodImage);
837 txt_search.setEnabled(false);
838 lbl_pdbManualFetchStatus.setIcon(errorImage);
843 * Validates inputs for the manual PDB file selection options
845 protected void validateAssociationFromFile()
847 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
848 .getCmb_assSeq().getSelectedItem();
849 lbl_fromFileStatus.setIcon(errorImage);
850 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
851 .getName().equalsIgnoreCase("-Select Associated Seq-")))
853 btn_pdbFromFile.setEnabled(true);
854 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
856 btn_add.setEnabled(true);
857 lbl_fromFileStatus.setIcon(goodImage);
862 btn_pdbFromFile.setEnabled(false);
863 lbl_fromFileStatus.setIcon(errorImage);
868 protected void cmbAssSeqStateChanged()
870 validateSelections();
872 private FilterOption lastSelected=null;
874 * Handles the state change event for the 'filter' combo-box and 'invert'
878 protected void stateChanged(ItemEvent e)
880 if (e.getSource() instanceof JCheckBox)
886 if (e.getStateChange() == ItemEvent.SELECTED)
895 * select structures for viewing by their PDB IDs
898 * @return true if structures were found and marked as selected
900 public boolean selectStructure(String... pdbids)
902 boolean found = false;
904 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
906 String currentView = selectedFilterOpt.getView();
907 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
908 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
910 if (restable == null)
912 // can't select (enter PDB ID, or load file - need to also select which
913 // sequence to associate with)
917 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
918 for (int r = 0; r < restable.getRowCount(); r++)
920 for (int p = 0; p < pdbids.length; p++)
922 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
923 .equalsIgnoreCase(pdbids[p]))
925 restable.setRowSelectionInterval(r, r);
934 * Handles the 'New View' action
937 protected void newView_ActionPerformed()
939 targetView.setSelectedItem(null);
940 showStructures(false);
944 * Handles the 'Add to existing viewer' action
947 protected void add_ActionPerformed()
949 showStructures(false);
953 * structure viewer opened by this dialog, or null
955 private StructureViewer sViewer = null;
957 public void showStructures(boolean waitUntilFinished)
960 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
962 final int preferredHeight = pnl_filter.getHeight();
964 Runnable viewStruc = new Runnable()
969 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
971 String currentView = selectedFilterOpt.getView();
972 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
975 if (currentView == VIEWS_FILTER)
977 int[] selectedRows = restable.getSelectedRows();
978 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
979 List<SequenceI> selectedSeqsToView = new ArrayList<>();
980 pdbEntriesToView = data.collectSelectedRows(restable,
981 selectedRows, selectedSeqsToView);
983 SequenceI[] selectedSeqs = selectedSeqsToView
984 .toArray(new SequenceI[selectedSeqsToView.size()]);
985 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
988 else if (currentView == VIEWS_LOCAL_PDB)
990 int[] selectedRows = tbl_local_pdb.getSelectedRows();
991 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
993 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
995 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
997 List<SequenceI> selectedSeqsToView = new ArrayList<>();
998 for (int row : selectedRows)
1000 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1001 .getModel()).getPDBEntryAt(row).getPdbEntry();
1003 pdbEntriesToView[count++] = pdbEntry;
1004 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1005 .getValueAt(row, refSeqColIndex);
1006 selectedSeqsToView.add(selectedSeq);
1008 SequenceI[] selectedSeqs = selectedSeqsToView
1009 .toArray(new SequenceI[selectedSeqsToView.size()]);
1010 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1013 else if (currentView == VIEWS_ENTER_ID)
1015 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1016 .getCmb_assSeq().getSelectedItem()).getSequence();
1017 if (userSelectedSeq != null)
1019 selectedSequence = userSelectedSeq;
1021 String pdbIdStr = txt_search.getText();
1022 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1023 if (pdbEntry == null)
1025 pdbEntry = new PDBEntry();
1026 if (pdbIdStr.split(":").length > 1)
1028 pdbEntry.setId(pdbIdStr.split(":")[0]);
1029 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
1033 pdbEntry.setId(pdbIdStr);
1035 pdbEntry.setType(PDBEntry.Type.PDB);
1036 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1039 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1040 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1042 { selectedSequence });
1044 else if (currentView == VIEWS_FROM_FILE)
1046 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1047 .getCmb_assSeq().getSelectedItem()).getSequence();
1048 if (userSelectedSeq != null)
1050 selectedSequence = userSelectedSeq;
1052 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1053 .associatePdbWithSeq(selectedPdbFileName,
1054 DataSourceType.FILE, selectedSequence, true,
1057 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1059 { selectedSequence });
1061 SwingUtilities.invokeLater(new Runnable()
1066 closeAction(preferredHeight);
1067 mainFrame.dispose();
1072 Thread runner = new Thread(viewStruc);
1074 if (waitUntilFinished)
1076 while (sViewer == null ? runner.isAlive()
1077 : (sViewer.sview == null ? true
1078 : !sViewer.sview.hasMapping()))
1083 } catch (InterruptedException ie)
1092 * Answers a structure viewer (new or existing) configured to superimpose
1093 * added structures or not according to the user's choice
1098 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1100 Object sv = targetView.getSelectedItem();
1102 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1106 * Adds PDB structures to a new or existing structure viewer
1109 * @param pdbEntriesToView
1114 private StructureViewer launchStructureViewer(
1115 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1116 final AlignmentPanel alignPanel, SequenceI[] sequences)
1118 long progressId = sequences.hashCode();
1119 setProgressBar(MessageManager
1120 .getString("status.launching_3d_structure_viewer"), progressId);
1121 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1122 boolean superimpose = chk_superpose.isSelected();
1123 theViewer.setSuperpose(superimpose);
1126 * remember user's choice of superimpose or not
1128 Cache.setProperty(AUTOSUPERIMPOSE,
1129 Boolean.valueOf(superimpose).toString());
1131 setProgressBar(null, progressId);
1132 if (SiftsSettings.isMapWithSifts())
1134 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1136 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1137 // real PDB ID. For moment, we can also safely do this if there is already
1138 // a known mapping between the PDBEntry and the sequence.
1139 for (SequenceI seq : sequences)
1141 PDBEntry pdbe = pdbEntriesToView[p++];
1142 if (pdbe != null && pdbe.getFile() != null)
1144 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1145 if (smm != null && smm.length > 0)
1147 for (StructureMapping sm : smm)
1149 if (sm.getSequence() == seq)
1156 if (seq.getPrimaryDBRefs().isEmpty())
1158 seqsWithoutSourceDBRef.add(seq);
1162 if (!seqsWithoutSourceDBRef.isEmpty())
1164 int y = seqsWithoutSourceDBRef.size();
1165 setProgressBar(MessageManager.formatMessage(
1166 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1168 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1169 .toArray(new SequenceI[y]);
1170 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1171 dbRefFetcher.fetchDBRefs(true);
1173 setProgressBar("Fetch complete.", progressId); // todo i18n
1176 if (pdbEntriesToView.length > 1)
1179 MessageManager.getString(
1180 "status.fetching_3d_structures_for_selected_entries"),
1182 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1186 setProgressBar(MessageManager.formatMessage(
1187 "status.fetching_3d_structures_for",
1188 pdbEntriesToView[0].getId()), progressId);
1189 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1191 setProgressBar(null, progressId);
1192 // remember the last viewer we used...
1193 lastTargetedView = theViewer;
1198 * Populates the combo-box used in associating manually fetched structures to
1199 * a unique sequence when more than one sequence selection is made.
1202 protected void populateCmbAssociateSeqOptions(
1203 JComboBox<AssociateSeqOptions> cmb_assSeq,
1204 JLabel lbl_associateSeq)
1206 cmb_assSeq.removeAllItems();
1208 new AssociateSeqOptions("-Select Associated Seq-", null));
1209 lbl_associateSeq.setVisible(false);
1210 if (selectedSequences.length > 1)
1212 for (SequenceI seq : selectedSequences)
1214 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1219 String seqName = selectedSequence.getDisplayId(false);
1220 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1221 lbl_associateSeq.setText(seqName);
1222 lbl_associateSeq.setVisible(true);
1223 cmb_assSeq.setVisible(false);
1227 protected boolean isStructuresDiscovered()
1229 return discoveredStructuresSet != null
1230 && !discoveredStructuresSet.isEmpty();
1233 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1235 // Doing a search for "1" or "1c" is valuable?
1236 // Those work but are enormously slow.
1239 protected void txt_search_ActionPerformed()
1241 String text = txt_search.getText().trim();
1242 if (text.length() >= PDB_ID_MIN)
1249 errorWarning.setLength(0);
1250 isValidPBDEntry = false;
1251 if (text.length() > 0)
1253 // TODO move this pdb id search into the PDB specific
1255 // for moment, it will work fine as is because it is self-contained
1256 String searchTerm = text.toLowerCase();
1257 searchTerm = searchTerm.split(":")[0];
1258 // System.out.println(">>>>> search term : " + searchTerm);
1259 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1260 FTSRestRequest pdbRequest = new FTSRestRequest();
1261 pdbRequest.setAllowEmptySeq(false);
1262 pdbRequest.setResponseSize(1);
1263 pdbRequest.setFieldToSearchBy("(pdb_id:");
1264 pdbRequest.setWantedFields(wantedFields);
1265 pdbRequest.setSearchTerm(searchTerm + ")");
1266 pdbRequest.setAssociatedSequence(selectedSequence);
1267 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1268 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1269 FTSRestResponse resultList;
1272 resultList = pdbRestClient.executeRequest(pdbRequest);
1273 } catch (Exception e)
1275 errorWarning.append(e.getMessage());
1279 validateSelections();
1281 if (resultList.getSearchSummary() != null
1282 && resultList.getSearchSummary().size() > 0)
1284 isValidPBDEntry = true;
1287 validateSelections();
1293 protected void tabRefresh()
1295 if (selectedSequences != null)
1297 Thread refreshThread = new Thread(new Runnable()
1302 fetchStructuresMetaData();
1303 // populateFilterComboBox(true, cachedPDBExists);
1306 ((FilterOption) cmb_filterOption.getSelectedItem())
1310 refreshThread.start();
1314 public class PDBEntryTableModel extends AbstractTableModel
1316 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1319 private List<CachedPDB> pdbEntries;
1321 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1323 this.pdbEntries = new ArrayList<>(pdbEntries);
1327 public String getColumnName(int columnIndex)
1329 return columns[columnIndex];
1333 public int getRowCount()
1335 return pdbEntries.size();
1339 public int getColumnCount()
1341 return columns.length;
1345 public boolean isCellEditable(int row, int column)
1351 public Object getValueAt(int rowIndex, int columnIndex)
1353 Object value = "??";
1354 CachedPDB entry = pdbEntries.get(rowIndex);
1355 switch (columnIndex)
1358 value = entry.getSequence();
1361 value = entry.getQualifiedId();
1364 value = entry.getPdbEntry().getChainCode() == null ? "_"
1365 : entry.getPdbEntry().getChainCode();
1368 value = entry.getPdbEntry().getType();
1371 value = entry.getPdbEntry().getFile();
1378 public Class<?> getColumnClass(int columnIndex)
1380 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1383 public CachedPDB getPDBEntryAt(int row)
1385 return pdbEntries.get(row);
1390 private class CachedPDB
1392 private SequenceI sequence;
1394 private PDBEntry pdbEntry;
1396 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1398 this.sequence = sequence;
1399 this.pdbEntry = pdbEntry;
1402 public String getQualifiedId()
1404 if (pdbEntry.hasProvider())
1406 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1408 return pdbEntry.toString();
1411 public SequenceI getSequence()
1416 public PDBEntry getPdbEntry()
1423 private IProgressIndicator progressBar;
1426 public void setProgressBar(String message, long id)
1428 progressBar.setProgressBar(message, id);
1432 public void registerHandler(long id, IProgressIndicatorHandler handler)
1434 progressBar.registerHandler(id, handler);
1438 public boolean operationInProgress()
1440 return progressBar.operationInProgress();
1443 public JalviewStructureDisplayI getOpenedStructureViewer()
1445 return sViewer == null ? null : sViewer.sview;
1449 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1451 data.setDocFieldPrefs(newPrefs);
1457 * @return true when all initialisation threads have finished and dialog is
1460 public boolean isDialogVisible()
1462 return mainFrame != null && data != null && cmb_filterOption != null
1463 && mainFrame.isVisible()
1464 && cmb_filterOption.getSelectedItem() != null;