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";
76 private SequenceI selectedSequence;
78 private SequenceI[] selectedSequences;
80 private IProgressIndicator progressIndicator;
82 private Collection<FTSData> discoveredStructuresSet;
84 private StructureChooserQuerySource data;
87 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
89 return data.getDocFieldPrefs();
92 private String selectedPdbFileName;
94 private boolean isValidPBDEntry;
96 private boolean cachedPDBExists;
98 private Collection<FTSData> lastDiscoveredStructuresSet;
100 private static StructureViewer lastTargetedView = null;
102 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
105 // which FTS engine to use
106 data = StructureChooserQuerySource
107 .getQuerySourceFor(selectedSeqs);
111 this.selectedSequence = selectedSeq;
112 this.selectedSequences = selectedSeqs;
113 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
119 * Initializes parameters used by the Structure Chooser Panel
121 protected void init()
123 if (!Jalview.isHeadlessMode())
125 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
128 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
130 final Runnable discoverPDBStructures = new Runnable()
135 // check which FTS engine to use
136 data = StructureChooserQuerySource
137 .getQuerySourceFor(selectedSequences);
139 // ensure a filter option is in force for search
140 populateFilterComboBox(true, cachedPDBExists);
142 // looks for any existing structures already loaded
143 // for the sequences (the cached ones)
144 // then queries the StructureChooserQuerySource to
145 // discover more structures.
147 // Possible optimisation is to only begin querying
148 // the structure chooser if there are no cached structures.
150 long startTime = System.currentTimeMillis();
151 updateProgressIndicator(MessageManager
152 .getString("status.loading_cached_pdb_entries"), startTime);
153 loadLocalCachedPDBEntries();
154 updateProgressIndicator(null, startTime);
155 updateProgressIndicator(MessageManager.getString(
156 "status.searching_for_pdb_structures"), startTime);
157 fetchStructuresMetaData();
158 // revise filter options if no results were found
159 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
160 discoverStructureViews();
161 updateProgressIndicator(null, startTime);
162 mainFrame.setVisible(true);
166 final List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
168 final Runnable discoverCanonicalDBrefs = new Runnable()
173 long progressId = System.currentTimeMillis();
175 int y = seqsWithoutSourceDBRef.size();
177 setProgressBar(MessageManager.formatMessage(
178 "status.fetching_dbrefs_for_sequences_without_valid_refs",
180 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
181 .toArray(new SequenceI[y]);
183 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
184 progressBar, new DbSourceProxy[]
185 { new jalview.ws.dbsources.Uniprot() },
188 dbRefFetcher.fetchDBRefs(true);
190 setProgressBar("Fetch complete.", progressId); // todo i18n
192 Executors.defaultThreadFactory().newThread(discoverPDBStructures).start();
196 Executors.defaultThreadFactory().newThread(new Runnable()
201 for (SequenceI seq : selectedSequences)
205 int dbRef = ThreeDBStructureChooserQuerySource
206 .checkUniprotRefs(seq.getDBRefs());
209 if (seq.getAllPDBEntries()==null && seq.getAllPDBEntries().size()==0)
211 seqsWithoutSourceDBRef.add(seq);
216 // retrieve database refs for protein sequences
217 if (!seqsWithoutSourceDBRef.isEmpty())
219 // need cancel and no to result in the discoverPDB action - mocked is 'cancel'
220 JvOptionPane.newOptionDialog(Desktop.getDesktop())
221 .setResponseHandler(JvOptionPane.OK_OPTION, discoverCanonicalDBrefs)
222 .setResponseHandler(JvOptionPane.CANCEL_OPTION, discoverPDBStructures)
223 .setResponseHandler(JvOptionPane.NO_OPTION, discoverPDBStructures)
224 .showDialog(MessageManager.formatMessage("label.fetch_references_for",
225 seqsWithoutSourceDBRef.size()), MessageManager.getString(
226 "label.fetch_uniprot_references"),
227 JvOptionPane.YES_NO_OPTION,
228 JvOptionPane.PLAIN_MESSAGE, null, new Object[]
229 { MessageManager.getString("action.ok"),
230 MessageManager.getString("action.cancel") },
231 MessageManager.getString("action.ok"));
233 // get structures directly
234 Executors.defaultThreadFactory().newThread(discoverPDBStructures).start();
242 * Builds a drop-down choice list of existing structure viewers to which new
243 * structures may be added. If this list is empty then it, and the 'Add'
244 * button, are hidden.
246 private void discoverStructureViews()
248 if (Desktop.instance != null)
250 targetView.removeAllItems();
251 if (lastTargetedView != null && !lastTargetedView.isVisible())
253 lastTargetedView = null;
255 int linkedViewsAt = 0;
256 for (StructureViewerBase view : Desktop.instance
257 .getStructureViewers(null, null))
259 StructureViewer viewHandler = (lastTargetedView != null
260 && lastTargetedView.sview == view) ? lastTargetedView
261 : StructureViewer.reconfigure(view);
263 if (view.isLinkedWith(ap))
265 targetView.insertItemAt(viewHandler, linkedViewsAt++);
269 targetView.addItem(viewHandler);
274 * show option to Add to viewer if at least 1 viewer found
276 targetView.setVisible(false);
277 if (targetView.getItemCount() > 0)
279 targetView.setVisible(true);
280 if (lastTargetedView != null)
282 targetView.setSelectedItem(lastTargetedView);
286 targetView.setSelectedIndex(0);
289 btn_add.setVisible(targetView.isVisible());
294 * Updates the progress indicator with the specified message
297 * displayed message for the operation
299 * unique handle for this indicator
301 protected void updateProgressIndicator(String message, long id)
303 if (progressIndicator != null)
305 progressIndicator.setProgressBar(message, id);
310 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
313 void fetchStructuresMetaData()
315 long startTime = System.currentTimeMillis();
316 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
317 .getStructureSummaryFields();
319 discoveredStructuresSet = new LinkedHashSet<>();
320 HashSet<String> errors = new HashSet<>();
322 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
325 for (SequenceI seq : selectedSequences)
328 FTSRestResponse resultList;
331 resultList = data.fetchStructuresMetaData(seq, wantedFields,
332 selectedFilterOpt, !chk_invertFilter.isSelected());
333 // null response means the FTSengine didn't yield a query for this
334 // consider designing a special exception if we really wanted to be OOCrazy
335 if (resultList==null)
339 } catch (Exception e)
342 errors.add(e.getMessage());
345 if (resultList.getSearchSummary() != null
346 && !resultList.getSearchSummary().isEmpty())
348 discoveredStructuresSet.addAll(resultList.getSearchSummary());
352 int noOfStructuresFound = 0;
353 String totalTime = (System.currentTimeMillis() - startTime)
355 if (discoveredStructuresSet != null
356 && !discoveredStructuresSet.isEmpty())
359 .setModel(data.getTableModel(discoveredStructuresSet));
361 noOfStructuresFound = discoveredStructuresSet.size();
362 lastDiscoveredStructuresSet=discoveredStructuresSet;
363 mainFrame.setTitle(MessageManager.formatMessage(
364 "label.structure_chooser_no_of_structures",
365 noOfStructuresFound, totalTime));
369 mainFrame.setTitle(MessageManager
370 .getString("label.structure_chooser_manual_association"));
371 if (errors.size() > 0)
373 StringBuilder errorMsg = new StringBuilder();
374 for (String error : errors)
376 errorMsg.append(error).append("\n");
378 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
379 MessageManager.getString("label.pdb_web-service_error"),
380 JvOptionPane.ERROR_MESSAGE);
385 protected void loadLocalCachedPDBEntries()
387 ArrayList<CachedPDB> entries = new ArrayList<>();
388 for (SequenceI seq : selectedSequences)
390 if (seq.getDatasetSequence() != null
391 && seq.getDatasetSequence().getAllPDBEntries() != null)
393 for (PDBEntry pdbEntry : seq.getDatasetSequence()
396 if (pdbEntry.getFile() != null)
398 entries.add(new CachedPDB(seq, pdbEntry));
403 cachedPDBExists = !entries.isEmpty();
404 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
405 tbl_local_pdb.setModel(tableModelx);
409 * Filters a given list of discovered structures based on supplied argument
411 * @param fieldToFilterBy
412 * the field to filter by
414 void filterResultSet(final String fieldToFilterBy)
416 Thread filterThread = new Thread(new Runnable()
422 long startTime = System.currentTimeMillis();
423 lbl_loading.setVisible(true);
424 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
425 .getStructureSummaryFields();
426 Collection<FTSData> filteredResponse = new HashSet<>();
427 HashSet<String> errors = new HashSet<>();
429 for (SequenceI seq : selectedSequences)
432 FTSRestResponse resultList;
435 resultList = data.selectFirstRankedQuery(seq, discoveredStructuresSet,wantedFields,
436 fieldToFilterBy, !chk_invertFilter.isSelected());
438 } catch (Exception e)
441 errors.add(e.getMessage());
444 if (resultList.getSearchSummary() != null
445 && !resultList.getSearchSummary().isEmpty())
447 filteredResponse.addAll(resultList.getSearchSummary());
451 String totalTime = (System.currentTimeMillis() - startTime)
453 if (!filteredResponse.isEmpty())
455 final int filterResponseCount = filteredResponse.size();
456 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
457 reorderedStructuresSet.addAll(filteredResponse);
458 reorderedStructuresSet.addAll(discoveredStructuresSet);
460 .setModel(data.getTableModel(reorderedStructuresSet));
462 FTSRestResponse.configureTableColumn(getResultTable(),
463 wantedFields, tempUserPrefs);
464 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
465 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
466 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
467 // Update table selection model here
468 getResultTable().addRowSelectionInterval(0,
469 filterResponseCount - 1);
470 mainFrame.setTitle(MessageManager.formatMessage(
471 "label.structure_chooser_filter_time", totalTime));
475 mainFrame.setTitle(MessageManager.formatMessage(
476 "label.structure_chooser_filter_time", totalTime));
477 if (errors.size() > 0)
479 StringBuilder errorMsg = new StringBuilder();
480 for (String error : errors)
482 errorMsg.append(error).append("\n");
484 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
485 MessageManager.getString("label.pdb_web-service_error"),
486 JvOptionPane.ERROR_MESSAGE);
490 lbl_loading.setVisible(false);
492 validateSelections();
495 filterThread.start();
499 * Handles action event for btn_pdbFromFile
502 protected void pdbFromFile_actionPerformed()
504 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
507 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
508 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
509 chooser.setFileView(new jalview.io.JalviewFileView());
510 chooser.setDialogTitle(
511 MessageManager.formatMessage("label.select_pdb_file_for",
512 selectedSequence.getDisplayId(false)));
513 chooser.setToolTipText(MessageManager.formatMessage(
514 "label.load_pdb_file_associate_with_sequence",
515 selectedSequence.getDisplayId(false)));
517 int value = chooser.showOpenDialog(null);
518 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
520 selectedPdbFileName = chooser.getSelectedFile().getPath();
521 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
522 validateSelections();
527 * Populates the filter combo-box options dynamically depending on discovered
530 protected void populateFilterComboBox(boolean haveData,
531 boolean cachedPDBExist)
533 populateFilterComboBox(haveData, cachedPDBExist, null);
536 * Populates the filter combo-box options dynamically depending on discovered
539 protected void populateFilterComboBox(boolean haveData,
540 boolean cachedPDBExist, FilterOption lastSel)
544 * temporarily suspend the change listener behaviour
546 cmb_filterOption.removeItemListener(this);
548 cmb_filterOption.removeAllItems();
551 List<FilterOption> filters = data.getAvailableFilterOptions(VIEWS_FILTER);
552 data.updateAvailableFilterOptions(VIEWS_FILTER, filters, lastDiscoveredStructuresSet);
554 for (FilterOption filter:filters)
556 if (lastSel!=null && filter.equals(lastSel)) {
560 cmb_filterOption.addItem(filter);
563 cmb_filterOption.addItem(
564 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
565 "-", VIEWS_ENTER_ID, false,null));
566 cmb_filterOption.addItem(
567 new FilterOption(MessageManager.getString("label.from_file"),
568 "-", VIEWS_FROM_FILE, false,null));
572 FilterOption cachedOption = new FilterOption(
573 MessageManager.getString("label.cached_structures"), "-",
574 VIEWS_LOCAL_PDB, false,null);
575 cmb_filterOption.addItem(cachedOption);
577 cmb_filterOption.setSelectedItem(cachedOption);
582 cmb_filterOption.setSelectedIndex(selSet);
584 cmb_filterOption.addItemListener(this);
588 * Updates the displayed view based on the selected filter option
590 protected void updateCurrentView()
592 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
594 layout_switchableViews.show(pnl_switchableViews,
595 selectedFilterOpt.getView());
596 String filterTitle = mainFrame.getTitle();
597 mainFrame.setTitle(frameTitle);
598 chk_invertFilter.setVisible(false);
599 if (selectedFilterOpt.getView() == VIEWS_FILTER)
601 mainFrame.setTitle(filterTitle);
602 // TDB Query has no invert as yet
603 chk_invertFilter.setVisible(selectedFilterOpt.getQuerySource() instanceof PDBStructureChooserQuerySource);
605 if (data!=selectedFilterOpt.getQuerySource() || data.needsRefetch(selectedFilterOpt))
607 data = selectedFilterOpt.getQuerySource();
608 // rebuild the views completely, since prefs will also change
612 filterResultSet(selectedFilterOpt.getValue());
615 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
616 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
618 mainFrame.setTitle(MessageManager
619 .getString("label.structure_chooser_manual_association"));
620 idInputAssSeqPanel.loadCmbAssSeq();
621 fileChooserAssSeqPanel.loadCmbAssSeq();
623 validateSelections();
627 * Validates user selection and enables the 'Add' and 'New View' buttons if
628 * all parameters are correct (the Add button will only be visible if there is
629 * at least one existing structure viewer open). This basically means at least
630 * one structure selected and no error messages.
632 * The 'Superpose Structures' option is enabled if either more than one
633 * structure is selected, or the 'Add' to existing view option is enabled, and
634 * disabled if the only option is to open a new view of a single structure.
637 protected void validateSelections()
639 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
641 btn_add.setEnabled(false);
642 String currentView = selectedFilterOpt.getView();
643 int selectedCount = 0;
644 if (currentView == VIEWS_FILTER)
646 selectedCount = getResultTable().getSelectedRows().length;
647 if (selectedCount > 0)
649 btn_add.setEnabled(true);
652 else if (currentView == VIEWS_LOCAL_PDB)
654 selectedCount = tbl_local_pdb.getSelectedRows().length;
655 if (selectedCount > 0)
657 btn_add.setEnabled(true);
660 else if (currentView == VIEWS_ENTER_ID)
662 validateAssociationEnterPdb();
664 else if (currentView == VIEWS_FROM_FILE)
666 validateAssociationFromFile();
669 btn_newView.setEnabled(btn_add.isEnabled());
672 * enable 'Superpose' option if more than one structure is selected,
673 * or there are view(s) available to add structure(s) to
676 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
680 * Validates inputs from the Manual PDB entry panel
682 protected void validateAssociationEnterPdb()
684 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
685 .getCmb_assSeq().getSelectedItem();
686 lbl_pdbManualFetchStatus.setIcon(errorImage);
687 lbl_pdbManualFetchStatus.setToolTipText("");
688 if (txt_search.getText().length() > 0)
690 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
691 MessageManager.formatMessage("info.no_pdb_entry_found_for",
692 txt_search.getText())));
695 if (errorWarning.length() > 0)
697 lbl_pdbManualFetchStatus.setIcon(warningImage);
698 lbl_pdbManualFetchStatus.setToolTipText(
699 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
702 if (selectedSequences.length == 1 || !assSeqOpt.getName()
703 .equalsIgnoreCase("-Select Associated Seq-"))
705 txt_search.setEnabled(true);
708 btn_add.setEnabled(true);
709 lbl_pdbManualFetchStatus.setToolTipText("");
710 lbl_pdbManualFetchStatus.setIcon(goodImage);
715 txt_search.setEnabled(false);
716 lbl_pdbManualFetchStatus.setIcon(errorImage);
721 * Validates inputs for the manual PDB file selection options
723 protected void validateAssociationFromFile()
725 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
726 .getCmb_assSeq().getSelectedItem();
727 lbl_fromFileStatus.setIcon(errorImage);
728 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
729 .getName().equalsIgnoreCase("-Select Associated Seq-")))
731 btn_pdbFromFile.setEnabled(true);
732 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
734 btn_add.setEnabled(true);
735 lbl_fromFileStatus.setIcon(goodImage);
740 btn_pdbFromFile.setEnabled(false);
741 lbl_fromFileStatus.setIcon(errorImage);
746 protected void cmbAssSeqStateChanged()
748 validateSelections();
752 * Handles the state change event for the 'filter' combo-box and 'invert'
756 protected void stateChanged(ItemEvent e)
758 if (e.getSource() instanceof JCheckBox)
764 if (e.getStateChange() == ItemEvent.SELECTED)
773 * select structures for viewing by their PDB IDs
776 * @return true if structures were found and marked as selected
778 public boolean selectStructure(String... pdbids)
780 boolean found = false;
782 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
784 String currentView = selectedFilterOpt.getView();
785 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
786 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
788 if (restable == null)
790 // can't select (enter PDB ID, or load file - need to also select which
791 // sequence to associate with)
795 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
796 for (int r = 0; r < restable.getRowCount(); r++)
798 for (int p = 0; p < pdbids.length; p++)
800 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
801 .equalsIgnoreCase(pdbids[p]))
803 restable.setRowSelectionInterval(r, r);
812 * Handles the 'New View' action
815 protected void newView_ActionPerformed()
817 targetView.setSelectedItem(null);
818 showStructures(false);
822 * Handles the 'Add to existing viewer' action
825 protected void add_ActionPerformed()
827 showStructures(false);
831 * structure viewer opened by this dialog, or null
833 private StructureViewer sViewer = null;
835 public void showStructures(boolean waitUntilFinished)
838 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
840 final int preferredHeight = pnl_filter.getHeight();
842 Runnable viewStruc = new Runnable()
847 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
849 String currentView = selectedFilterOpt.getView();
850 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
853 if (currentView == VIEWS_FILTER)
855 int[] selectedRows = restable.getSelectedRows();
856 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
857 List<SequenceI> selectedSeqsToView = new ArrayList<>();
858 pdbEntriesToView = data.collectSelectedRows(restable,selectedRows,selectedSeqsToView);
860 SequenceI[] selectedSeqs = selectedSeqsToView
861 .toArray(new SequenceI[selectedSeqsToView.size()]);
862 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
865 else if (currentView == VIEWS_LOCAL_PDB)
867 int[] selectedRows = tbl_local_pdb.getSelectedRows();
868 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
870 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
872 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
874 List<SequenceI> selectedSeqsToView = new ArrayList<>();
875 for (int row : selectedRows)
877 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb.getModel()).getPDBEntryAt(row).getPdbEntry();
879 pdbEntriesToView[count++] = pdbEntry;
880 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
881 .getValueAt(row, refSeqColIndex);
882 selectedSeqsToView.add(selectedSeq);
884 SequenceI[] selectedSeqs = selectedSeqsToView
885 .toArray(new SequenceI[selectedSeqsToView.size()]);
886 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
889 else if (currentView == VIEWS_ENTER_ID)
891 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
892 .getCmb_assSeq().getSelectedItem()).getSequence();
893 if (userSelectedSeq != null)
895 selectedSequence = userSelectedSeq;
897 String pdbIdStr = txt_search.getText();
898 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
899 if (pdbEntry == null)
901 pdbEntry = new PDBEntry();
902 if (pdbIdStr.split(":").length > 1)
904 pdbEntry.setId(pdbIdStr.split(":")[0]);
905 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
909 pdbEntry.setId(pdbIdStr);
911 pdbEntry.setType(PDBEntry.Type.PDB);
912 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
915 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
916 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
918 { selectedSequence });
920 else if (currentView == VIEWS_FROM_FILE)
922 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
923 .getCmb_assSeq().getSelectedItem()).getSequence();
924 if (userSelectedSeq != null)
926 selectedSequence = userSelectedSeq;
928 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
929 .associatePdbWithSeq(selectedPdbFileName,
930 DataSourceType.FILE, selectedSequence, true,
933 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
935 { selectedSequence });
937 SwingUtilities.invokeLater(new Runnable()
942 closeAction(preferredHeight);
948 Thread runner = new Thread(viewStruc);
950 if (waitUntilFinished)
952 while (sViewer == null ? runner.isAlive()
953 : (sViewer.sview == null ? true
954 : !sViewer.sview.hasMapping()))
959 } catch (InterruptedException ie)
968 * Answers a structure viewer (new or existing) configured to superimpose
969 * added structures or not according to the user's choice
974 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
976 Object sv = targetView.getSelectedItem();
978 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
982 * Adds PDB structures to a new or existing structure viewer
985 * @param pdbEntriesToView
990 private StructureViewer launchStructureViewer(
991 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
992 final AlignmentPanel alignPanel, SequenceI[] sequences)
994 long progressId = sequences.hashCode();
995 setProgressBar(MessageManager
996 .getString("status.launching_3d_structure_viewer"), progressId);
997 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
998 boolean superimpose = chk_superpose.isSelected();
999 theViewer.setSuperpose(superimpose);
1002 * remember user's choice of superimpose or not
1004 Cache.setProperty(AUTOSUPERIMPOSE,
1005 Boolean.valueOf(superimpose).toString());
1007 setProgressBar(null, progressId);
1008 if (SiftsSettings.isMapWithSifts())
1010 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1012 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1013 // real PDB ID. For moment, we can also safely do this if there is already
1014 // a known mapping between the PDBEntry and the sequence.
1015 for (SequenceI seq : sequences)
1017 PDBEntry pdbe = pdbEntriesToView[p++];
1018 if (pdbe != null && pdbe.getFile() != null)
1020 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1021 if (smm != null && smm.length > 0)
1023 for (StructureMapping sm : smm)
1025 if (sm.getSequence() == seq)
1032 if (seq.getPrimaryDBRefs().isEmpty())
1034 seqsWithoutSourceDBRef.add(seq);
1038 if (!seqsWithoutSourceDBRef.isEmpty())
1040 int y = seqsWithoutSourceDBRef.size();
1041 setProgressBar(MessageManager.formatMessage(
1042 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1044 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1045 .toArray(new SequenceI[y]);
1046 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1047 dbRefFetcher.fetchDBRefs(true);
1049 setProgressBar("Fetch complete.", progressId); // todo i18n
1052 if (pdbEntriesToView.length > 1)
1055 MessageManager.getString(
1056 "status.fetching_3d_structures_for_selected_entries"),
1058 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1062 setProgressBar(MessageManager.formatMessage(
1063 "status.fetching_3d_structures_for",
1064 pdbEntriesToView[0].getId()), progressId);
1065 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1067 setProgressBar(null, progressId);
1068 // remember the last viewer we used...
1069 lastTargetedView = theViewer;
1074 * Populates the combo-box used in associating manually fetched structures to
1075 * a unique sequence when more than one sequence selection is made.
1078 protected void populateCmbAssociateSeqOptions(
1079 JComboBox<AssociateSeqOptions> cmb_assSeq,
1080 JLabel lbl_associateSeq)
1082 cmb_assSeq.removeAllItems();
1084 new AssociateSeqOptions("-Select Associated Seq-", null));
1085 lbl_associateSeq.setVisible(false);
1086 if (selectedSequences.length > 1)
1088 for (SequenceI seq : selectedSequences)
1090 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1095 String seqName = selectedSequence.getDisplayId(false);
1096 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1097 lbl_associateSeq.setText(seqName);
1098 lbl_associateSeq.setVisible(true);
1099 cmb_assSeq.setVisible(false);
1103 protected boolean isStructuresDiscovered()
1105 return discoveredStructuresSet != null
1106 && !discoveredStructuresSet.isEmpty();
1109 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1111 // Doing a search for "1" or "1c" is valuable?
1112 // Those work but are enormously slow.
1115 protected void txt_search_ActionPerformed()
1117 String text = txt_search.getText().trim();
1118 if (text.length() >= PDB_ID_MIN)
1125 errorWarning.setLength(0);
1126 isValidPBDEntry = false;
1127 if (text.length() > 0)
1129 // TODO move this pdb id search into the PDB specific
1131 // for moment, it will work fine as is because it is self-contained
1132 String searchTerm = text.toLowerCase();
1133 searchTerm = searchTerm.split(":")[0];
1134 // System.out.println(">>>>> search term : " + searchTerm);
1135 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1136 FTSRestRequest pdbRequest = new FTSRestRequest();
1137 pdbRequest.setAllowEmptySeq(false);
1138 pdbRequest.setResponseSize(1);
1139 pdbRequest.setFieldToSearchBy("(pdb_id:");
1140 pdbRequest.setWantedFields(wantedFields);
1141 pdbRequest.setSearchTerm(searchTerm + ")");
1142 pdbRequest.setAssociatedSequence(selectedSequence);
1143 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1144 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1145 FTSRestResponse resultList;
1148 resultList = pdbRestClient.executeRequest(pdbRequest);
1149 } catch (Exception e)
1151 errorWarning.append(e.getMessage());
1155 validateSelections();
1157 if (resultList.getSearchSummary() != null
1158 && resultList.getSearchSummary().size() > 0)
1160 isValidPBDEntry = true;
1163 validateSelections();
1169 protected void tabRefresh()
1171 if (selectedSequences != null)
1173 Thread refreshThread = new Thread(new Runnable()
1178 fetchStructuresMetaData();
1179 //populateFilterComboBox(true, cachedPDBExists);
1182 ((FilterOption) cmb_filterOption.getSelectedItem())
1186 refreshThread.start();
1190 public class PDBEntryTableModel extends AbstractTableModel
1192 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1195 private List<CachedPDB> pdbEntries;
1197 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1199 this.pdbEntries = new ArrayList<>(pdbEntries);
1203 public String getColumnName(int columnIndex)
1205 return columns[columnIndex];
1209 public int getRowCount()
1211 return pdbEntries.size();
1215 public int getColumnCount()
1217 return columns.length;
1221 public boolean isCellEditable(int row, int column)
1227 public Object getValueAt(int rowIndex, int columnIndex)
1229 Object value = "??";
1230 CachedPDB entry = pdbEntries.get(rowIndex);
1231 switch (columnIndex)
1234 value = entry.getSequence();
1237 value = entry.getQualifiedId();
1240 value = entry.getPdbEntry().getChainCode() == null ? "_"
1241 : entry.getPdbEntry().getChainCode();
1244 value = entry.getPdbEntry().getType();
1247 value = entry.getPdbEntry().getFile();
1254 public Class<?> getColumnClass(int columnIndex)
1256 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1259 public CachedPDB getPDBEntryAt(int row)
1261 return pdbEntries.get(row);
1266 private class CachedPDB
1268 private SequenceI sequence;
1270 private PDBEntry pdbEntry;
1272 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1274 this.sequence = sequence;
1275 this.pdbEntry = pdbEntry;
1278 public String getQualifiedId()
1280 if (pdbEntry.hasProvider())
1282 return pdbEntry.getProvider()+":"+pdbEntry.getId();
1284 return pdbEntry.toString();
1287 public SequenceI getSequence()
1292 public PDBEntry getPdbEntry()
1299 private IProgressIndicator progressBar;
1302 public void setProgressBar(String message, long id)
1304 progressBar.setProgressBar(message, id);
1308 public void registerHandler(long id, IProgressIndicatorHandler handler)
1310 progressBar.registerHandler(id, handler);
1314 public boolean operationInProgress()
1316 return progressBar.operationInProgress();
1319 public JalviewStructureDisplayI getOpenedStructureViewer()
1321 return sViewer == null ? null : sViewer.sview;
1325 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1327 data.setDocFieldPrefs(newPrefs);
1333 * @return true when all initialisation threads have finished and dialog is visible
1335 public boolean isDialogVisible()
1337 return mainFrame != null && data != null && cmb_filterOption != null
1338 && mainFrame.isVisible()
1339 && cmb_filterOption.getSelectedItem() != null;