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.ActionEvent;
25 import java.awt.event.ActionListener;
26 import java.awt.event.ItemEvent;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashSet;
31 import java.util.LinkedHashSet;
32 import java.util.List;
33 import java.util.Locale;
34 import java.util.concurrent.Executors;
36 import javax.swing.JCheckBox;
37 import javax.swing.JComboBox;
38 import javax.swing.JLabel;
39 import javax.swing.JMenuItem;
40 import javax.swing.JPopupMenu;
41 import javax.swing.JTable;
42 import javax.swing.SwingUtilities;
43 import javax.swing.table.AbstractTableModel;
45 import jalview.api.structures.JalviewStructureDisplayI;
46 import jalview.bin.Cache;
47 import jalview.bin.Console;
48 import jalview.bin.Jalview;
49 import jalview.datamodel.PDBEntry;
50 import jalview.datamodel.SequenceI;
51 import jalview.fts.api.FTSData;
52 import jalview.fts.api.FTSDataColumnI;
53 import jalview.fts.api.FTSRestClientI;
54 import jalview.fts.core.FTSDataColumnPreferences;
55 import jalview.fts.core.FTSRestRequest;
56 import jalview.fts.core.FTSRestResponse;
57 import jalview.fts.service.pdb.PDBFTSRestClient;
58 import jalview.fts.service.threedbeacons.TDB_FTSData;
59 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
60 import jalview.gui.structurechooser.StructureChooserQuerySource;
61 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
62 import jalview.io.DataSourceType;
63 import jalview.jbgui.FilterOption;
64 import jalview.jbgui.GStructureChooser;
65 import jalview.structure.StructureMapping;
66 import jalview.structure.StructureSelectionManager;
67 import jalview.util.MessageManager;
68 import jalview.ws.DBRefFetcher;
69 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
70 import jalview.ws.seqfetcher.DbSourceProxy;
71 import jalview.ws.sifts.SiftsSettings;
74 * Provides the behaviors for the Structure chooser Panel
79 @SuppressWarnings("serial")
80 public class StructureChooser extends GStructureChooser
81 implements IProgressIndicator
83 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
86 * warn user if need to fetch more than this many uniprot records at once
88 private static final int THRESHOLD_WARN_UNIPROT_FETCH_NEEDED = 20;
90 private SequenceI selectedSequence;
92 private SequenceI[] selectedSequences;
94 private IProgressIndicator progressIndicator;
96 private Collection<FTSData> discoveredStructuresSet;
98 private StructureChooserQuerySource data;
101 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
103 return data.getDocFieldPrefs();
106 private String selectedPdbFileName;
108 private boolean isValidPBDEntry;
110 private boolean cachedPDBExists;
112 private Collection<FTSData> lastDiscoveredStructuresSet;
114 private boolean canQueryTDB = false;
116 private boolean notQueriedTDBYet = true;
118 List<SequenceI> seqsWithoutSourceDBRef = null;
120 private boolean noChooserGUI = false;
122 private static StructureViewer lastTargetedView = null;
124 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
127 this(selectedSeqs, selectedSeq, ap, false);
130 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
131 AlignmentPanel ap, boolean noChooserGUI)
133 // which FTS engine to use
134 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
138 this.selectedSequence = selectedSeq;
139 this.selectedSequences = selectedSeqs;
140 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
141 this.noChooserGUI = noChooserGUI;
147 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
148 * least one structure are discovered.
150 private void populateSeqsWithoutSourceDBRef()
152 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
153 boolean needCanonical = false;
154 for (SequenceI seq : selectedSequences)
158 int dbRef = ThreeDBStructureChooserQuerySource
159 .checkUniprotRefs(seq.getDBRefs());
164 // need to retrieve canonicals
165 needCanonical = true;
166 seqsWithoutSourceDBRef.add(seq);
170 // could be a sequence with pdb ref
171 if (seq.getAllPDBEntries() == null
172 || seq.getAllPDBEntries().size() == 0)
174 seqsWithoutSourceDBRef.add(seq);
180 // retrieve database refs for protein sequences
181 if (!seqsWithoutSourceDBRef.isEmpty())
186 // triggers display of the 'Query TDB' button
187 notQueriedTDBYet = true;
193 * Initializes parameters used by the Structure Chooser Panel
195 protected void init()
197 if (!Jalview.isHeadlessMode())
199 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
202 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
203 btn_queryTDB.addActionListener(new ActionListener()
207 public void actionPerformed(ActionEvent e)
209 promptForTDBFetch(false);
213 Executors.defaultThreadFactory().newThread(new Runnable()
218 populateSeqsWithoutSourceDBRef();
219 initialStructureDiscovery();
227 private void initialStructureDiscovery()
229 // check which FTS engine to use
230 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
232 // ensure a filter option is in force for search
233 populateFilterComboBox(true, cachedPDBExists);
235 // looks for any existing structures already loaded
236 // for the sequences (the cached ones)
237 // then queries the StructureChooserQuerySource to
238 // discover more structures.
240 // Possible optimisation is to only begin querying
241 // the structure chooser if there are no cached structures.
243 long startTime = System.currentTimeMillis();
244 updateProgressIndicator(
245 MessageManager.getString("status.loading_cached_pdb_entries"),
247 loadLocalCachedPDBEntries();
248 updateProgressIndicator(null, startTime);
249 updateProgressIndicator(
250 MessageManager.getString("status.searching_for_pdb_structures"),
252 fetchStructuresMetaData();
253 // revise filter options if no results were found
254 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
255 discoverStructureViews();
256 updateProgressIndicator(null, startTime);
257 mainFrame.setVisible(noChooserGUI);
262 * raises dialog for Uniprot fetch followed by 3D beacons search
265 * - when true, don't ask, just fetch
267 public void promptForTDBFetch(boolean ignoreGui)
269 final long progressId = System.currentTimeMillis();
271 // final action after prompting and discovering db refs
272 final Runnable strucDiscovery = new Runnable()
277 mainFrame.setEnabled(false);
278 cmb_filterOption.setEnabled(false);
279 progressBar.setProgressBar(
280 MessageManager.getString("status.searching_3d_beacons"),
282 btn_queryTDB.setEnabled(false);
283 // TODO: warn if no accessions discovered
284 populateSeqsWithoutSourceDBRef();
285 // redo initial discovery - this time with 3d beacons
287 previousWantedFields = null;
288 lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
289 cmb_filterOption.setSelectedItem(null);
290 cachedPDBExists = false; // reset to initial
291 initialStructureDiscovery();
292 if (!isStructuresDiscovered())
294 progressBar.setProgressBar(MessageManager.getString(
295 "status.no_structures_discovered_from_3d_beacons"),
297 btn_queryTDB.setToolTipText(MessageManager.getString(
298 "status.no_structures_discovered_from_3d_beacons"));
299 btn_queryTDB.setEnabled(false);
300 pnl_queryTDB.setVisible(false);
304 cmb_filterOption.setSelectedIndex(0); // select 'best'
305 btn_queryTDB.setVisible(false);
306 pnl_queryTDB.setVisible(false);
307 progressBar.setProgressBar(null, progressId);
309 mainFrame.setEnabled(true);
310 cmb_filterOption.setEnabled(true);
314 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
318 public void finished()
320 // filter has been selected, so we set flag to remove ourselves
321 notQueriedTDBYet = false;
322 // new thread to discover structures - via 3d beacons
323 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
328 // fetch db refs if OK pressed
329 final Runnable discoverCanonicalDBrefs = new Runnable()
334 btn_queryTDB.setEnabled(false);
335 populateSeqsWithoutSourceDBRef();
337 final int y = seqsWithoutSourceDBRef.size();
340 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
341 .toArray(new SequenceI[y]);
342 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
343 progressBar, new DbSourceProxy[]
344 { new jalview.ws.dbsources.Uniprot() }, null, false);
345 dbRefFetcher.addListener(afterDbRefFetch);
346 // ideally this would also gracefully run with callbacks
348 dbRefFetcher.fetchDBRefs(true);
352 // call finished action directly
353 afterDbRefFetch.finished();
358 final Runnable revertview = new Runnable()
363 if (lastSelected != null)
365 cmb_filterOption.setSelectedItem(lastSelected);
369 int threshold = Cache.getDefault("UNIPROT_AUTOFETCH_THRESHOLD",
370 THRESHOLD_WARN_UNIPROT_FETCH_NEEDED);
371 Console.debug("Using Uniprot fetch threshold of " + threshold);
372 if (ignoreGui || seqsWithoutSourceDBRef.size() < threshold)
374 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs)
378 // need cancel and no to result in the discoverPDB action - mocked is
379 // 'cancel' TODO: mock should be OK
381 StructureChooser thisSC = this;
382 JvOptionPane.newOptionDialog(thisSC.getFrame())
383 .setResponseHandler(JvOptionPane.OK_OPTION,
384 discoverCanonicalDBrefs)
385 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
386 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
388 MessageManager.formatMessage(
389 "label.fetch_references_for_3dbeacons",
390 seqsWithoutSourceDBRef.size()),
391 MessageManager.getString("label.3dbeacons"),
392 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
394 { MessageManager.getString("action.ok"),
395 MessageManager.getString("action.cancel") },
396 MessageManager.getString("action.ok"), false);
400 * Builds a drop-down choice list of existing structure viewers to which new
401 * structures may be added. If this list is empty then it, and the 'Add'
402 * button, are hidden.
404 private void discoverStructureViews()
406 if (Desktop.instance != null)
408 targetView.removeAllItems();
409 if (lastTargetedView != null && !lastTargetedView.isVisible())
411 lastTargetedView = null;
413 int linkedViewsAt = 0;
414 for (StructureViewerBase view : Desktop.instance
415 .getStructureViewers(null, null))
417 StructureViewer viewHandler = (lastTargetedView != null
418 && lastTargetedView.sview == view) ? lastTargetedView
419 : StructureViewer.reconfigure(view);
421 if (view.isLinkedWith(ap))
423 targetView.insertItemAt(viewHandler, linkedViewsAt++);
427 targetView.addItem(viewHandler);
432 * show option to Add to viewer if at least 1 viewer found
434 targetView.setVisible(false);
435 if (targetView.getItemCount() > 0)
437 targetView.setVisible(true);
438 if (lastTargetedView != null)
440 targetView.setSelectedItem(lastTargetedView);
444 targetView.setSelectedIndex(0);
447 btn_add.setVisible(targetView.isVisible());
452 * Updates the progress indicator with the specified message
455 * displayed message for the operation
457 * unique handle for this indicator
459 protected void updateProgressIndicator(String message, long id)
461 if (progressIndicator != null)
463 progressIndicator.setProgressBar(message, id);
468 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
471 void fetchStructuresMetaData()
473 long startTime = System.currentTimeMillis();
474 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
475 .getStructureSummaryFields();
477 discoveredStructuresSet = new LinkedHashSet<>();
478 HashSet<String> errors = new HashSet<>();
480 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
483 for (SequenceI seq : selectedSequences)
486 FTSRestResponse resultList;
489 resultList = data.fetchStructuresMetaData(seq, wantedFields,
490 selectedFilterOpt, !chk_invertFilter.isSelected());
491 // null response means the FTSengine didn't yield a query for this
492 // consider designing a special exception if we really wanted to be
494 if (resultList == null)
498 } catch (Exception e)
501 errors.add(e.getMessage());
504 if (resultList.getSearchSummary() != null
505 && !resultList.getSearchSummary().isEmpty())
507 discoveredStructuresSet.addAll(resultList.getSearchSummary());
511 int noOfStructuresFound = 0;
512 String totalTime = (System.currentTimeMillis() - startTime)
514 if (discoveredStructuresSet != null
515 && !discoveredStructuresSet.isEmpty())
518 .setModel(data.getTableModel(discoveredStructuresSet));
520 noOfStructuresFound = discoveredStructuresSet.size();
521 lastDiscoveredStructuresSet = discoveredStructuresSet;
522 mainFrame.setTitle(MessageManager.formatMessage(
523 "label.structure_chooser_no_of_structures",
524 noOfStructuresFound, totalTime));
528 mainFrame.setTitle(MessageManager
529 .getString("label.structure_chooser_manual_association"));
530 if (errors.size() > 0)
532 StringBuilder errorMsg = new StringBuilder();
533 for (String error : errors)
535 errorMsg.append(error).append("\n");
537 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
538 MessageManager.getString("label.pdb_web-service_error"),
539 JvOptionPane.ERROR_MESSAGE);
544 protected void loadLocalCachedPDBEntries()
546 ArrayList<CachedPDB> entries = new ArrayList<>();
547 for (SequenceI seq : selectedSequences)
549 if (seq.getDatasetSequence() != null
550 && seq.getDatasetSequence().getAllPDBEntries() != null)
552 for (PDBEntry pdbEntry : seq.getDatasetSequence()
555 if (pdbEntry.getFile() != null)
557 entries.add(new CachedPDB(seq, pdbEntry));
562 cachedPDBExists = !entries.isEmpty();
563 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
564 tbl_local_pdb.setModel(tableModelx);
568 * Filters a given list of discovered structures based on supplied argument
570 * @param fieldToFilterBy
571 * the field to filter by
573 void filterResultSet(final String fieldToFilterBy)
575 Thread filterThread = new Thread(new Runnable()
581 long startTime = System.currentTimeMillis();
582 lbl_loading.setVisible(true);
583 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
584 .getStructureSummaryFields();
585 Collection<FTSData> filteredResponse = new HashSet<>();
586 HashSet<String> errors = new HashSet<>();
588 for (SequenceI seq : selectedSequences)
591 FTSRestResponse resultList;
594 resultList = data.selectFirstRankedQuery(seq,
595 discoveredStructuresSet, wantedFields, fieldToFilterBy,
596 !chk_invertFilter.isSelected());
598 } catch (Exception e)
601 errors.add(e.getMessage());
604 if (resultList.getSearchSummary() != null
605 && !resultList.getSearchSummary().isEmpty())
607 filteredResponse.addAll(resultList.getSearchSummary());
611 String totalTime = (System.currentTimeMillis() - startTime)
613 if (!filteredResponse.isEmpty())
615 final int filterResponseCount = filteredResponse.size();
616 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
617 reorderedStructuresSet.addAll(filteredResponse);
618 reorderedStructuresSet.addAll(discoveredStructuresSet);
620 .setModel(data.getTableModel(reorderedStructuresSet));
622 FTSRestResponse.configureTableColumn(getResultTable(),
623 wantedFields, tempUserPrefs);
624 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
625 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
626 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
627 // Update table selection model here
628 getResultTable().addRowSelectionInterval(0,
629 filterResponseCount - 1);
630 mainFrame.setTitle(MessageManager.formatMessage(
631 "label.structure_chooser_filter_time", totalTime));
635 mainFrame.setTitle(MessageManager.formatMessage(
636 "label.structure_chooser_filter_time", totalTime));
637 if (errors.size() > 0)
639 StringBuilder errorMsg = new StringBuilder();
640 for (String error : errors)
642 errorMsg.append(error).append("\n");
644 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
645 MessageManager.getString("label.pdb_web-service_error"),
646 JvOptionPane.ERROR_MESSAGE);
650 lbl_loading.setVisible(false);
652 validateSelections();
655 filterThread.start();
659 * Handles action event for btn_pdbFromFile
662 protected void pdbFromFile_actionPerformed()
664 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
667 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
668 Cache.getProperty("LAST_DIRECTORY"));
669 chooser.setFileView(new jalview.io.JalviewFileView());
670 chooser.setDialogTitle(
671 MessageManager.formatMessage("label.select_pdb_file_for",
672 selectedSequence.getDisplayId(false)));
673 chooser.setToolTipText(MessageManager.formatMessage(
674 "label.load_pdb_file_associate_with_sequence",
675 selectedSequence.getDisplayId(false)));
677 int value = chooser.showOpenDialog(null);
678 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
680 selectedPdbFileName = chooser.getSelectedFile().getPath();
681 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
682 validateSelections();
687 * Populates the filter combo-box options dynamically depending on discovered
690 protected void populateFilterComboBox(boolean haveData,
691 boolean cachedPDBExist)
693 populateFilterComboBox(haveData, cachedPDBExist, null);
697 * Populates the filter combo-box options dynamically depending on discovered
700 protected void populateFilterComboBox(boolean haveData,
701 boolean cachedPDBExist, FilterOption lastSel)
705 * temporarily suspend the change listener behaviour
707 cmb_filterOption.removeItemListener(this);
709 cmb_filterOption.removeAllItems();
712 List<FilterOption> filters = data
713 .getAvailableFilterOptions(VIEWS_FILTER);
714 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
715 lastDiscoveredStructuresSet);
717 for (FilterOption filter : filters)
719 if (lastSel != null && filter.equals(lastSel))
724 cmb_filterOption.addItem(filter);
728 cmb_filterOption.addItem(
729 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
730 "-", VIEWS_ENTER_ID, false, null));
731 cmb_filterOption.addItem(
732 new FilterOption(MessageManager.getString("label.from_file"),
733 "-", VIEWS_FROM_FILE, false, null));
734 if (canQueryTDB && notQueriedTDBYet)
736 btn_queryTDB.setVisible(true);
737 pnl_queryTDB.setVisible(true);
742 FilterOption cachedOption = new FilterOption(
743 MessageManager.getString("label.cached_structures"), "-",
744 VIEWS_LOCAL_PDB, false, null);
745 cmb_filterOption.addItem(cachedOption);
748 cmb_filterOption.setSelectedItem(cachedOption);
753 cmb_filterOption.setSelectedIndex(selSet);
755 cmb_filterOption.addItemListener(this);
759 * Updates the displayed view based on the selected filter option
761 protected void updateCurrentView()
763 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
766 if (lastSelected == selectedFilterOpt)
768 // don't need to do anything, probably
771 // otherwise, record selection
772 // and update the layout and dialog accordingly
773 lastSelected = selectedFilterOpt;
775 layout_switchableViews.show(pnl_switchableViews,
776 selectedFilterOpt.getView());
777 String filterTitle = mainFrame.getTitle();
778 mainFrame.setTitle(frameTitle);
779 chk_invertFilter.setVisible(false);
781 if (selectedFilterOpt.getView() == VIEWS_FILTER)
783 mainFrame.setTitle(filterTitle);
784 // TDB Query has no invert as yet
785 chk_invertFilter.setVisible(selectedFilterOpt
786 .getQuerySource() instanceof PDBStructureChooserQuerySource);
788 if (data != selectedFilterOpt.getQuerySource()
789 || data.needsRefetch(selectedFilterOpt))
791 data = selectedFilterOpt.getQuerySource();
792 // rebuild the views completely, since prefs will also change
798 filterResultSet(selectedFilterOpt.getValue());
801 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
802 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
804 mainFrame.setTitle(MessageManager
805 .getString("label.structure_chooser_manual_association"));
806 idInputAssSeqPanel.loadCmbAssSeq();
807 fileChooserAssSeqPanel.loadCmbAssSeq();
809 validateSelections();
813 * Validates user selection and enables the 'Add' and 'New View' buttons if
814 * all parameters are correct (the Add button will only be visible if there is
815 * at least one existing structure viewer open). This basically means at least
816 * one structure selected and no error messages.
818 * The 'Superpose Structures' option is enabled if either more than one
819 * structure is selected, or the 'Add' to existing view option is enabled, and
820 * disabled if the only option is to open a new view of a single structure.
823 protected void validateSelections()
825 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
827 btn_add.setEnabled(false);
828 String currentView = selectedFilterOpt.getView();
829 int selectedCount = 0;
830 if (currentView == VIEWS_FILTER)
832 selectedCount = getResultTable().getSelectedRows().length;
833 if (selectedCount > 0)
835 btn_add.setEnabled(true);
838 else if (currentView == VIEWS_LOCAL_PDB)
840 selectedCount = tbl_local_pdb.getSelectedRows().length;
841 if (selectedCount > 0)
843 btn_add.setEnabled(true);
846 else if (currentView == VIEWS_ENTER_ID)
848 validateAssociationEnterPdb();
850 else if (currentView == VIEWS_FROM_FILE)
852 validateAssociationFromFile();
855 btn_newView.setEnabled(btn_add.isEnabled());
858 * enable 'Superpose' option if more than one structure is selected,
859 * or there are view(s) available to add structure(s) to
862 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
866 protected boolean showPopupFor(int selectedRow, int x, int y)
868 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
870 String currentView = selectedFilterOpt.getView();
872 if (currentView == VIEWS_FILTER
873 && data instanceof ThreeDBStructureChooserQuerySource)
876 TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
877 .getFTSDataFor(getResultTable(), selectedRow,
878 discoveredStructuresSet);
879 String pageUrl = row.getModelViewUrl();
880 JPopupMenu popup = new JPopupMenu("3D Beacons");
881 JMenuItem viewUrl = new JMenuItem("View model web page");
882 viewUrl.addActionListener(new ActionListener()
885 public void actionPerformed(ActionEvent e)
887 Desktop.showUrl(pageUrl);
891 SwingUtilities.invokeLater(new Runnable()
896 popup.show(getResultTable(), x, y);
901 // event not handled by us
906 * Validates inputs from the Manual PDB entry panel
908 protected void validateAssociationEnterPdb()
910 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
911 .getCmb_assSeq().getSelectedItem();
912 lbl_pdbManualFetchStatus.setIcon(errorImage);
913 lbl_pdbManualFetchStatus.setToolTipText("");
914 if (txt_search.getText().length() > 0)
916 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
917 MessageManager.formatMessage("info.no_pdb_entry_found_for",
918 txt_search.getText())));
921 if (errorWarning.length() > 0)
923 lbl_pdbManualFetchStatus.setIcon(warningImage);
924 lbl_pdbManualFetchStatus.setToolTipText(
925 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
928 if (selectedSequences.length == 1 || !assSeqOpt.getName()
929 .equalsIgnoreCase("-Select Associated Seq-"))
931 txt_search.setEnabled(true);
934 btn_add.setEnabled(true);
935 lbl_pdbManualFetchStatus.setToolTipText("");
936 lbl_pdbManualFetchStatus.setIcon(goodImage);
941 txt_search.setEnabled(false);
942 lbl_pdbManualFetchStatus.setIcon(errorImage);
947 * Validates inputs for the manual PDB file selection options
949 protected void validateAssociationFromFile()
951 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
952 .getCmb_assSeq().getSelectedItem();
953 lbl_fromFileStatus.setIcon(errorImage);
954 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
955 .getName().equalsIgnoreCase("-Select Associated Seq-")))
957 btn_pdbFromFile.setEnabled(true);
958 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
960 btn_add.setEnabled(true);
961 lbl_fromFileStatus.setIcon(goodImage);
966 btn_pdbFromFile.setEnabled(false);
967 lbl_fromFileStatus.setIcon(errorImage);
972 protected void cmbAssSeqStateChanged()
974 validateSelections();
977 private FilterOption lastSelected = null;
980 * Handles the state change event for the 'filter' combo-box and 'invert'
984 protected void stateChanged(ItemEvent e)
986 if (e.getSource() instanceof JCheckBox)
992 if (e.getStateChange() == ItemEvent.SELECTED)
1001 * select structures for viewing by their PDB IDs
1004 * @return true if structures were found and marked as selected
1006 public boolean selectStructure(String... pdbids)
1008 boolean found = false;
1010 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1011 .getSelectedItem());
1012 String currentView = selectedFilterOpt.getView();
1013 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1014 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
1016 if (restable == null)
1018 // can't select (enter PDB ID, or load file - need to also select which
1019 // sequence to associate with)
1023 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
1024 for (int r = 0; r < restable.getRowCount(); r++)
1026 for (int p = 0; p < pdbids.length; p++)
1028 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1029 .equalsIgnoreCase(pdbids[p]))
1031 restable.setRowSelectionInterval(r, r);
1040 * Handles the 'New View' action
1043 protected void newView_ActionPerformed()
1045 targetView.setSelectedItem(null);
1046 showStructures(false);
1050 * Handles the 'Add to existing viewer' action
1053 protected void add_ActionPerformed()
1055 showStructures(false);
1059 * structure viewer opened by this dialog, or null
1061 private StructureViewer sViewer = null;
1063 public void showStructures(boolean waitUntilFinished)
1066 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1068 final int preferredHeight = pnl_filter.getHeight();
1070 Runnable viewStruc = new Runnable()
1075 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1076 .getSelectedItem());
1077 String currentView = selectedFilterOpt.getView();
1078 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1081 if (currentView == VIEWS_FILTER)
1083 int[] selectedRows = restable.getSelectedRows();
1084 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1085 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1086 pdbEntriesToView = data.collectSelectedRows(restable,
1087 selectedRows, selectedSeqsToView);
1089 SequenceI[] selectedSeqs = selectedSeqsToView
1090 .toArray(new SequenceI[selectedSeqsToView.size()]);
1091 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1094 else if (currentView == VIEWS_LOCAL_PDB)
1096 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1097 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1099 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1101 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1103 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1104 for (int row : selectedRows)
1106 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1107 .getModel()).getPDBEntryAt(row).getPdbEntry();
1109 pdbEntriesToView[count++] = pdbEntry;
1110 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1111 .getValueAt(row, refSeqColIndex);
1112 selectedSeqsToView.add(selectedSeq);
1114 SequenceI[] selectedSeqs = selectedSeqsToView
1115 .toArray(new SequenceI[selectedSeqsToView.size()]);
1116 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1119 else if (currentView == VIEWS_ENTER_ID)
1121 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1122 .getCmb_assSeq().getSelectedItem()).getSequence();
1123 if (userSelectedSeq != null)
1125 selectedSequence = userSelectedSeq;
1127 String pdbIdStr = txt_search.getText();
1128 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1129 if (pdbEntry == null)
1131 pdbEntry = new PDBEntry();
1132 if (pdbIdStr.split(":").length > 1)
1134 pdbEntry.setId(pdbIdStr.split(":")[0]);
1135 pdbEntry.setChainCode(
1136 pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1140 pdbEntry.setId(pdbIdStr);
1142 pdbEntry.setType(PDBEntry.Type.PDB);
1143 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1146 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1147 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1149 { selectedSequence });
1151 else if (currentView == VIEWS_FROM_FILE)
1153 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1154 .getCmb_assSeq().getSelectedItem()).getSequence();
1155 if (userSelectedSeq != null)
1157 selectedSequence = userSelectedSeq;
1159 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1160 .associatePdbWithSeq(selectedPdbFileName,
1161 DataSourceType.FILE, selectedSequence, true,
1164 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1166 { selectedSequence });
1168 SwingUtilities.invokeLater(new Runnable()
1173 closeAction(preferredHeight);
1174 mainFrame.dispose();
1179 Thread runner = new Thread(viewStruc);
1181 if (waitUntilFinished)
1183 while (sViewer == null ? runner.isAlive()
1184 : (sViewer.sview == null ? true
1185 : !sViewer.sview.hasMapping()))
1190 } catch (InterruptedException ie)
1199 * Answers a structure viewer (new or existing) configured to superimpose
1200 * added structures or not according to the user's choice
1205 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1207 Object sv = targetView.getSelectedItem();
1209 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1213 * Adds PDB structures to a new or existing structure viewer
1216 * @param pdbEntriesToView
1221 private StructureViewer launchStructureViewer(
1222 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1223 final AlignmentPanel alignPanel, SequenceI[] sequences)
1225 long progressId = sequences.hashCode();
1226 setProgressBar(MessageManager
1227 .getString("status.launching_3d_structure_viewer"), progressId);
1228 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1229 boolean superimpose = chk_superpose.isSelected();
1230 theViewer.setSuperpose(superimpose);
1233 * remember user's choice of superimpose or not
1235 Cache.setProperty(AUTOSUPERIMPOSE,
1236 Boolean.valueOf(superimpose).toString());
1238 setProgressBar(null, progressId);
1239 if (SiftsSettings.isMapWithSifts())
1241 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1243 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1244 // real PDB ID. For moment, we can also safely do this if there is already
1245 // a known mapping between the PDBEntry and the sequence.
1246 for (SequenceI seq : sequences)
1248 PDBEntry pdbe = pdbEntriesToView[p++];
1249 if (pdbe != null && pdbe.getFile() != null)
1251 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1252 if (smm != null && smm.length > 0)
1254 for (StructureMapping sm : smm)
1256 if (sm.getSequence() == seq)
1263 if (seq.getPrimaryDBRefs().isEmpty())
1265 seqsWithoutSourceDBRef.add(seq);
1269 if (!seqsWithoutSourceDBRef.isEmpty())
1271 int y = seqsWithoutSourceDBRef.size();
1272 setProgressBar(MessageManager.formatMessage(
1273 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1275 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1276 .toArray(new SequenceI[y]);
1277 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1278 dbRefFetcher.fetchDBRefs(true);
1280 setProgressBar("Fetch complete.", progressId); // todo i18n
1283 if (pdbEntriesToView.length > 1)
1286 MessageManager.getString(
1287 "status.fetching_3d_structures_for_selected_entries"),
1289 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1293 setProgressBar(MessageManager.formatMessage(
1294 "status.fetching_3d_structures_for",
1295 pdbEntriesToView[0].getId()), progressId);
1296 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1298 setProgressBar(null, progressId);
1299 // remember the last viewer we used...
1300 lastTargetedView = theViewer;
1305 * Populates the combo-box used in associating manually fetched structures to
1306 * a unique sequence when more than one sequence selection is made.
1309 protected void populateCmbAssociateSeqOptions(
1310 JComboBox<AssociateSeqOptions> cmb_assSeq,
1311 JLabel lbl_associateSeq)
1313 cmb_assSeq.removeAllItems();
1315 new AssociateSeqOptions("-Select Associated Seq-", null));
1316 lbl_associateSeq.setVisible(false);
1317 if (selectedSequences.length > 1)
1319 for (SequenceI seq : selectedSequences)
1321 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1326 String seqName = selectedSequence.getDisplayId(false);
1327 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1328 lbl_associateSeq.setText(seqName);
1329 lbl_associateSeq.setVisible(true);
1330 cmb_assSeq.setVisible(false);
1334 protected boolean isStructuresDiscovered()
1336 return discoveredStructuresSet != null
1337 && !discoveredStructuresSet.isEmpty();
1340 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1342 // Doing a search for "1" or "1c" is valuable?
1343 // Those work but are enormously slow.
1346 protected void txt_search_ActionPerformed()
1348 String text = txt_search.getText().trim();
1349 if (text.length() >= PDB_ID_MIN)
1356 errorWarning.setLength(0);
1357 isValidPBDEntry = false;
1358 if (text.length() > 0)
1360 // TODO move this pdb id search into the PDB specific
1362 // for moment, it will work fine as is because it is self-contained
1363 String searchTerm = text.toLowerCase(Locale.ROOT);
1364 searchTerm = searchTerm.split(":")[0];
1365 // System.out.println(">>>>> search term : " + searchTerm);
1366 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1367 FTSRestRequest pdbRequest = new FTSRestRequest();
1368 pdbRequest.setAllowEmptySeq(false);
1369 pdbRequest.setResponseSize(1);
1370 pdbRequest.setFieldToSearchBy("(pdb_id:");
1371 pdbRequest.setWantedFields(wantedFields);
1372 pdbRequest.setSearchTerm(searchTerm + ")");
1373 pdbRequest.setAssociatedSequence(selectedSequence);
1374 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1375 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1376 FTSRestResponse resultList;
1379 resultList = pdbRestClient.executeRequest(pdbRequest);
1380 } catch (Exception e)
1382 errorWarning.append(e.getMessage());
1386 validateSelections();
1388 if (resultList.getSearchSummary() != null
1389 && resultList.getSearchSummary().size() > 0)
1391 isValidPBDEntry = true;
1394 validateSelections();
1400 protected void tabRefresh()
1402 if (selectedSequences != null)
1404 lbl_loading.setVisible(true);
1405 Thread refreshThread = new Thread(new Runnable()
1410 fetchStructuresMetaData();
1411 // populateFilterComboBox(true, cachedPDBExists);
1414 ((FilterOption) cmb_filterOption.getSelectedItem())
1416 lbl_loading.setVisible(false);
1419 refreshThread.start();
1423 public class PDBEntryTableModel extends AbstractTableModel
1425 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1428 private List<CachedPDB> pdbEntries;
1430 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1432 this.pdbEntries = new ArrayList<>(pdbEntries);
1436 public String getColumnName(int columnIndex)
1438 return columns[columnIndex];
1442 public int getRowCount()
1444 return pdbEntries.size();
1448 public int getColumnCount()
1450 return columns.length;
1454 public boolean isCellEditable(int row, int column)
1460 public Object getValueAt(int rowIndex, int columnIndex)
1462 Object value = "??";
1463 CachedPDB entry = pdbEntries.get(rowIndex);
1464 switch (columnIndex)
1467 value = entry.getSequence();
1470 value = entry.getQualifiedId();
1473 value = entry.getPdbEntry().getChainCode() == null ? "_"
1474 : entry.getPdbEntry().getChainCode();
1477 value = entry.getPdbEntry().getType();
1480 value = entry.getPdbEntry().getFile();
1487 public Class<?> getColumnClass(int columnIndex)
1489 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1492 public CachedPDB getPDBEntryAt(int row)
1494 return pdbEntries.get(row);
1499 private class CachedPDB
1501 private SequenceI sequence;
1503 private PDBEntry pdbEntry;
1505 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1507 this.sequence = sequence;
1508 this.pdbEntry = pdbEntry;
1511 public String getQualifiedId()
1513 if (pdbEntry.hasProvider())
1515 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1517 return pdbEntry.toString();
1520 public SequenceI getSequence()
1525 public PDBEntry getPdbEntry()
1532 private IProgressIndicator progressBar;
1535 public void setProgressBar(String message, long id)
1537 progressBar.setProgressBar(message, id);
1541 public void registerHandler(long id, IProgressIndicatorHandler handler)
1543 progressBar.registerHandler(id, handler);
1547 public boolean operationInProgress()
1549 return progressBar.operationInProgress();
1552 public JalviewStructureDisplayI getOpenedStructureViewer()
1554 return sViewer == null ? null : sViewer.sview;
1558 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1560 data.setDocFieldPrefs(newPrefs);
1566 * @return true when all initialisation threads have finished and dialog is
1569 public boolean isDialogVisible()
1571 return mainFrame != null && data != null && cmb_filterOption != null
1572 && mainFrame.isVisible()
1573 && cmb_filterOption.getSelectedItem() != null;
1578 * @return true if the 3D-Beacons query button will/has been displayed
1580 public boolean isCanQueryTDB()
1585 public boolean isNotQueriedTDBYet()
1587 return notQueriedTDBYet;
1591 * Open a single structure file for a given sequence
1593 public static void openStructureFileForSequence(AlignmentPanel ap,
1594 SequenceI seq, File sFile)
1596 StructureChooser sc = new StructureChooser(new SequenceI[] { seq }, seq,
1598 StructureSelectionManager ssm = ap.getStructureSelectionManager();
1599 PDBEntry fileEntry = null;
1602 fileEntry = new AssociatePdbFileWithSeq().associatePdbWithSeq(
1603 sFile.getAbsolutePath(), DataSourceType.FILE, seq, true,
1605 } catch (Exception e)
1607 Console.error("Could not open structure file '"
1608 + sFile.getAbsolutePath() + "'");
1612 StructureViewer sViewer = sc.launchStructureViewer(ssm,
1614 { fileEntry }, ap, new SequenceI[] { seq });
1616 sc.mainFrame.dispose();
1617 sc.noChooserGUI = false;