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;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.HashSet;
30 import java.util.LinkedHashSet;
31 import java.util.List;
32 import java.util.Locale;
33 import java.util.concurrent.Executors;
35 import javax.swing.JCheckBox;
36 import javax.swing.JComboBox;
37 import javax.swing.JLabel;
38 import javax.swing.JMenuItem;
39 import javax.swing.JPopupMenu;
40 import javax.swing.JTable;
41 import javax.swing.SwingUtilities;
42 import javax.swing.table.AbstractTableModel;
44 import jalview.api.structures.JalviewStructureDisplayI;
45 import jalview.bin.Cache;
46 import jalview.bin.Console;
47 import jalview.bin.Jalview;
48 import jalview.datamodel.PDBEntry;
49 import jalview.datamodel.SequenceI;
50 import jalview.fts.api.FTSData;
51 import jalview.fts.api.FTSDataColumnI;
52 import jalview.fts.api.FTSRestClientI;
53 import jalview.fts.core.FTSDataColumnPreferences;
54 import jalview.fts.core.FTSRestRequest;
55 import jalview.fts.core.FTSRestResponse;
56 import jalview.fts.service.pdb.PDBFTSRestClient;
57 import jalview.fts.service.threedbeacons.TDB_FTSData;
58 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
59 import jalview.gui.structurechooser.StructureChooserQuerySource;
60 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
61 import jalview.io.DataSourceType;
62 import jalview.jbgui.FilterOption;
63 import jalview.jbgui.GStructureChooser;
64 import jalview.structure.StructureMapping;
65 import jalview.structure.StructureSelectionManager;
66 import jalview.util.MessageManager;
67 import jalview.ws.DBRefFetcher;
68 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
69 import jalview.ws.seqfetcher.DbSourceProxy;
70 import jalview.ws.sifts.SiftsSettings;
73 * Provides the behaviors for the Structure chooser Panel
78 @SuppressWarnings("serial")
79 public class StructureChooser extends GStructureChooser
80 implements IProgressIndicator
82 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
85 * warn user if need to fetch more than this many uniprot records at once
87 private static final int THRESHOLD_WARN_UNIPROT_FETCH_NEEDED = 20;
89 private SequenceI selectedSequence;
91 private SequenceI[] selectedSequences;
93 private IProgressIndicator progressIndicator;
95 private Collection<FTSData> discoveredStructuresSet;
97 private StructureChooserQuerySource data;
100 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
102 return data.getDocFieldPrefs();
105 private String selectedPdbFileName;
107 private boolean isValidPBDEntry;
109 private boolean cachedPDBExists;
111 private Collection<FTSData> lastDiscoveredStructuresSet;
113 private boolean canQueryTDB = false;
115 private boolean notQueriedTDBYet = true;
117 List<SequenceI> seqsWithoutSourceDBRef = null;
119 private static StructureViewer lastTargetedView = null;
121 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
124 // which FTS engine to use
125 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
129 this.selectedSequence = selectedSeq;
130 this.selectedSequences = selectedSeqs;
131 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
137 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
138 * least one structure are discovered.
140 private void populateSeqsWithoutSourceDBRef()
142 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
143 boolean needCanonical = false;
144 for (SequenceI seq : selectedSequences)
148 int dbRef = ThreeDBStructureChooserQuerySource
149 .checkUniprotRefs(seq.getDBRefs());
154 // need to retrieve canonicals
155 needCanonical = true;
156 seqsWithoutSourceDBRef.add(seq);
160 // could be a sequence with pdb ref
161 if (seq.getAllPDBEntries() == null
162 || seq.getAllPDBEntries().size() == 0)
164 seqsWithoutSourceDBRef.add(seq);
170 // retrieve database refs for protein sequences
171 if (!seqsWithoutSourceDBRef.isEmpty())
176 // triggers display of the 'Query TDB' button
177 notQueriedTDBYet = true;
183 * Initializes parameters used by the Structure Chooser Panel
185 protected void init()
187 if (!Jalview.isHeadlessMode())
189 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
192 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
193 btn_queryTDB.addActionListener(new ActionListener()
197 public void actionPerformed(ActionEvent e)
199 promptForTDBFetch(false);
203 Executors.defaultThreadFactory().newThread(new Runnable()
208 populateSeqsWithoutSourceDBRef();
209 initialStructureDiscovery();
217 private void initialStructureDiscovery()
219 // check which FTS engine to use
220 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
222 // ensure a filter option is in force for search
223 populateFilterComboBox(true, cachedPDBExists);
225 // looks for any existing structures already loaded
226 // for the sequences (the cached ones)
227 // then queries the StructureChooserQuerySource to
228 // discover more structures.
230 // Possible optimisation is to only begin querying
231 // the structure chooser if there are no cached structures.
233 long startTime = System.currentTimeMillis();
234 updateProgressIndicator(
235 MessageManager.getString("status.loading_cached_pdb_entries"),
237 loadLocalCachedPDBEntries();
238 updateProgressIndicator(null, startTime);
239 updateProgressIndicator(
240 MessageManager.getString("status.searching_for_pdb_structures"),
242 fetchStructuresMetaData();
243 // revise filter options if no results were found
244 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
245 discoverStructureViews();
246 updateProgressIndicator(null, startTime);
247 mainFrame.setVisible(true);
252 * raises dialog for Uniprot fetch followed by 3D beacons search
255 * - when true, don't ask, just fetch
257 public void promptForTDBFetch(boolean ignoreGui)
259 final long progressId = System.currentTimeMillis();
261 // final action after prompting and discovering db refs
262 final Runnable strucDiscovery = new Runnable()
267 mainFrame.setEnabled(false);
268 cmb_filterOption.setEnabled(false);
269 progressBar.setProgressBar(
270 MessageManager.getString("status.searching_3d_beacons"),
272 btn_queryTDB.setEnabled(false);
273 // TODO: warn if no accessions discovered
274 populateSeqsWithoutSourceDBRef();
275 // redo initial discovery - this time with 3d beacons
277 previousWantedFields = null;
278 lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
279 cmb_filterOption.setSelectedItem(null);
280 cachedPDBExists = false; // reset to initial
281 initialStructureDiscovery();
282 if (!isStructuresDiscovered())
284 progressBar.setProgressBar(MessageManager.getString(
285 "status.no_structures_discovered_from_3d_beacons"),
287 btn_queryTDB.setToolTipText(MessageManager.getString(
288 "status.no_structures_discovered_from_3d_beacons"));
289 btn_queryTDB.setEnabled(false);
290 pnl_queryTDB.setVisible(false);
294 cmb_filterOption.setSelectedIndex(0); // select 'best'
295 btn_queryTDB.setVisible(false);
296 pnl_queryTDB.setVisible(false);
297 progressBar.setProgressBar(null, progressId);
299 mainFrame.setEnabled(true);
300 cmb_filterOption.setEnabled(true);
304 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
308 public void finished()
310 // filter has been selected, so we set flag to remove ourselves
311 notQueriedTDBYet = false;
312 // new thread to discover structures - via 3d beacons
313 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
318 // fetch db refs if OK pressed
319 final Runnable discoverCanonicalDBrefs = new Runnable()
324 btn_queryTDB.setEnabled(false);
325 populateSeqsWithoutSourceDBRef();
327 final int y = seqsWithoutSourceDBRef.size();
330 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
331 .toArray(new SequenceI[y]);
332 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
333 progressBar, new DbSourceProxy[]
334 { new jalview.ws.dbsources.Uniprot() }, null, false);
335 dbRefFetcher.addListener(afterDbRefFetch);
336 // ideally this would also gracefully run with callbacks
338 dbRefFetcher.fetchDBRefs(true);
342 // call finished action directly
343 afterDbRefFetch.finished();
348 final Runnable revertview = new Runnable()
353 if (lastSelected != null)
355 cmb_filterOption.setSelectedItem(lastSelected);
359 int threshold = Cache.getDefault("UNIPROT_AUTOFETCH_THRESHOLD",
360 THRESHOLD_WARN_UNIPROT_FETCH_NEEDED);
361 Console.debug("Using Uniprot fetch threshold of " + threshold);
362 if (ignoreGui || seqsWithoutSourceDBRef.size() < threshold)
364 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs)
368 // need cancel and no to result in the discoverPDB action - mocked is
369 // 'cancel' TODO: mock should be OK
371 StructureChooser thisSC = this;
372 JvOptionPane.newOptionDialog(thisSC.getFrame())
373 .setResponseHandler(JvOptionPane.OK_OPTION,
374 discoverCanonicalDBrefs)
375 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
376 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
378 MessageManager.formatMessage(
379 "label.fetch_references_for_3dbeacons",
380 seqsWithoutSourceDBRef.size()),
381 MessageManager.getString("label.3dbeacons"),
382 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
384 { MessageManager.getString("action.ok"),
385 MessageManager.getString("action.cancel") },
386 MessageManager.getString("action.ok"), false);
390 * Builds a drop-down choice list of existing structure viewers to which new
391 * structures may be added. If this list is empty then it, and the 'Add'
392 * button, are hidden.
394 private void discoverStructureViews()
396 if (Desktop.instance != null)
398 targetView.removeAllItems();
399 if (lastTargetedView != null && !lastTargetedView.isVisible())
401 lastTargetedView = null;
403 int linkedViewsAt = 0;
404 for (StructureViewerBase view : Desktop.instance
405 .getStructureViewers(null, null))
407 StructureViewer viewHandler = (lastTargetedView != null
408 && lastTargetedView.sview == view) ? lastTargetedView
409 : StructureViewer.reconfigure(view);
411 if (view.isLinkedWith(ap))
413 targetView.insertItemAt(viewHandler, linkedViewsAt++);
417 targetView.addItem(viewHandler);
422 * show option to Add to viewer if at least 1 viewer found
424 targetView.setVisible(false);
425 if (targetView.getItemCount() > 0)
427 targetView.setVisible(true);
428 if (lastTargetedView != null)
430 targetView.setSelectedItem(lastTargetedView);
434 targetView.setSelectedIndex(0);
437 btn_add.setVisible(targetView.isVisible());
442 * Updates the progress indicator with the specified message
445 * displayed message for the operation
447 * unique handle for this indicator
449 protected void updateProgressIndicator(String message, long id)
451 if (progressIndicator != null)
453 progressIndicator.setProgressBar(message, id);
458 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
461 void fetchStructuresMetaData()
463 long startTime = System.currentTimeMillis();
464 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
465 .getStructureSummaryFields();
467 discoveredStructuresSet = new LinkedHashSet<>();
468 HashSet<String> errors = new HashSet<>();
470 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
473 for (SequenceI seq : selectedSequences)
476 FTSRestResponse resultList;
479 resultList = data.fetchStructuresMetaData(seq, wantedFields,
480 selectedFilterOpt, !chk_invertFilter.isSelected());
481 // null response means the FTSengine didn't yield a query for this
482 // consider designing a special exception if we really wanted to be
484 if (resultList == null)
488 } catch (Exception e)
491 errors.add(e.getMessage());
494 if (resultList.getSearchSummary() != null
495 && !resultList.getSearchSummary().isEmpty())
497 discoveredStructuresSet.addAll(resultList.getSearchSummary());
501 int noOfStructuresFound = 0;
502 String totalTime = (System.currentTimeMillis() - startTime)
504 if (discoveredStructuresSet != null
505 && !discoveredStructuresSet.isEmpty())
508 .setModel(data.getTableModel(discoveredStructuresSet));
510 noOfStructuresFound = discoveredStructuresSet.size();
511 lastDiscoveredStructuresSet = discoveredStructuresSet;
512 mainFrame.setTitle(MessageManager.formatMessage(
513 "label.structure_chooser_no_of_structures",
514 noOfStructuresFound, totalTime));
518 mainFrame.setTitle(MessageManager
519 .getString("label.structure_chooser_manual_association"));
520 if (errors.size() > 0)
522 StringBuilder errorMsg = new StringBuilder();
523 for (String error : errors)
525 errorMsg.append(error).append("\n");
527 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
528 MessageManager.getString("label.pdb_web-service_error"),
529 JvOptionPane.ERROR_MESSAGE);
534 protected void loadLocalCachedPDBEntries()
536 ArrayList<CachedPDB> entries = new ArrayList<>();
537 for (SequenceI seq : selectedSequences)
539 if (seq.getDatasetSequence() != null
540 && seq.getDatasetSequence().getAllPDBEntries() != null)
542 for (PDBEntry pdbEntry : seq.getDatasetSequence()
545 if (pdbEntry.getFile() != null)
547 entries.add(new CachedPDB(seq, pdbEntry));
552 cachedPDBExists = !entries.isEmpty();
553 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
554 tbl_local_pdb.setModel(tableModelx);
558 * Filters a given list of discovered structures based on supplied argument
560 * @param fieldToFilterBy
561 * the field to filter by
563 void filterResultSet(final String fieldToFilterBy)
565 Thread filterThread = new Thread(new Runnable()
571 long startTime = System.currentTimeMillis();
572 lbl_loading.setVisible(true);
573 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
574 .getStructureSummaryFields();
575 Collection<FTSData> filteredResponse = new HashSet<>();
576 HashSet<String> errors = new HashSet<>();
578 for (SequenceI seq : selectedSequences)
581 FTSRestResponse resultList;
584 resultList = data.selectFirstRankedQuery(seq,
585 discoveredStructuresSet, wantedFields, fieldToFilterBy,
586 !chk_invertFilter.isSelected());
588 } catch (Exception e)
591 errors.add(e.getMessage());
594 if (resultList.getSearchSummary() != null
595 && !resultList.getSearchSummary().isEmpty())
597 filteredResponse.addAll(resultList.getSearchSummary());
601 String totalTime = (System.currentTimeMillis() - startTime)
603 if (!filteredResponse.isEmpty())
605 final int filterResponseCount = filteredResponse.size();
606 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
607 reorderedStructuresSet.addAll(filteredResponse);
608 reorderedStructuresSet.addAll(discoveredStructuresSet);
610 .setModel(data.getTableModel(reorderedStructuresSet));
612 FTSRestResponse.configureTableColumn(getResultTable(),
613 wantedFields, tempUserPrefs);
614 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
615 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
616 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
617 // Update table selection model here
618 getResultTable().addRowSelectionInterval(0,
619 filterResponseCount - 1);
620 mainFrame.setTitle(MessageManager.formatMessage(
621 "label.structure_chooser_filter_time", totalTime));
625 mainFrame.setTitle(MessageManager.formatMessage(
626 "label.structure_chooser_filter_time", totalTime));
627 if (errors.size() > 0)
629 StringBuilder errorMsg = new StringBuilder();
630 for (String error : errors)
632 errorMsg.append(error).append("\n");
634 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
635 MessageManager.getString("label.pdb_web-service_error"),
636 JvOptionPane.ERROR_MESSAGE);
640 lbl_loading.setVisible(false);
642 validateSelections();
645 filterThread.start();
649 * Handles action event for btn_pdbFromFile
652 protected void pdbFromFile_actionPerformed()
654 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
657 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
658 Cache.getProperty("LAST_DIRECTORY"));
659 chooser.setFileView(new jalview.io.JalviewFileView());
660 chooser.setDialogTitle(
661 MessageManager.formatMessage("label.select_pdb_file_for",
662 selectedSequence.getDisplayId(false)));
663 chooser.setToolTipText(MessageManager.formatMessage(
664 "label.load_pdb_file_associate_with_sequence",
665 selectedSequence.getDisplayId(false)));
667 int value = chooser.showOpenDialog(null);
668 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
670 selectedPdbFileName = chooser.getSelectedFile().getPath();
671 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
672 validateSelections();
677 * Populates the filter combo-box options dynamically depending on discovered
680 protected void populateFilterComboBox(boolean haveData,
681 boolean cachedPDBExist)
683 populateFilterComboBox(haveData, cachedPDBExist, null);
687 * Populates the filter combo-box options dynamically depending on discovered
690 protected void populateFilterComboBox(boolean haveData,
691 boolean cachedPDBExist, FilterOption lastSel)
695 * temporarily suspend the change listener behaviour
697 cmb_filterOption.removeItemListener(this);
699 cmb_filterOption.removeAllItems();
702 List<FilterOption> filters = data
703 .getAvailableFilterOptions(VIEWS_FILTER);
704 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
705 lastDiscoveredStructuresSet);
707 for (FilterOption filter : filters)
709 if (lastSel != null && filter.equals(lastSel))
714 cmb_filterOption.addItem(filter);
718 cmb_filterOption.addItem(
719 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
720 "-", VIEWS_ENTER_ID, false, null));
721 cmb_filterOption.addItem(
722 new FilterOption(MessageManager.getString("label.from_file"),
723 "-", VIEWS_FROM_FILE, false, null));
724 if (canQueryTDB && notQueriedTDBYet)
726 btn_queryTDB.setVisible(true);
727 pnl_queryTDB.setVisible(true);
732 FilterOption cachedOption = new FilterOption(
733 MessageManager.getString("label.cached_structures"), "-",
734 VIEWS_LOCAL_PDB, false, null);
735 cmb_filterOption.addItem(cachedOption);
738 cmb_filterOption.setSelectedItem(cachedOption);
743 cmb_filterOption.setSelectedIndex(selSet);
745 cmb_filterOption.addItemListener(this);
749 * Updates the displayed view based on the selected filter option
751 protected void updateCurrentView()
753 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
756 if (lastSelected == selectedFilterOpt)
758 // don't need to do anything, probably
761 // otherwise, record selection
762 // and update the layout and dialog accordingly
763 lastSelected = selectedFilterOpt;
765 layout_switchableViews.show(pnl_switchableViews,
766 selectedFilterOpt.getView());
767 String filterTitle = mainFrame.getTitle();
768 mainFrame.setTitle(frameTitle);
769 chk_invertFilter.setVisible(false);
771 if (selectedFilterOpt.getView() == VIEWS_FILTER)
773 mainFrame.setTitle(filterTitle);
774 // TDB Query has no invert as yet
775 chk_invertFilter.setVisible(selectedFilterOpt
776 .getQuerySource() instanceof PDBStructureChooserQuerySource);
778 if (data != selectedFilterOpt.getQuerySource()
779 || data.needsRefetch(selectedFilterOpt))
781 data = selectedFilterOpt.getQuerySource();
782 // rebuild the views completely, since prefs will also change
788 filterResultSet(selectedFilterOpt.getValue());
791 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
792 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
794 mainFrame.setTitle(MessageManager
795 .getString("label.structure_chooser_manual_association"));
796 idInputAssSeqPanel.loadCmbAssSeq();
797 fileChooserAssSeqPanel.loadCmbAssSeq();
799 validateSelections();
803 * Validates user selection and enables the 'Add' and 'New View' buttons if
804 * all parameters are correct (the Add button will only be visible if there is
805 * at least one existing structure viewer open). This basically means at least
806 * one structure selected and no error messages.
808 * The 'Superpose Structures' option is enabled if either more than one
809 * structure is selected, or the 'Add' to existing view option is enabled, and
810 * disabled if the only option is to open a new view of a single structure.
813 protected void validateSelections()
815 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
817 btn_add.setEnabled(false);
818 String currentView = selectedFilterOpt.getView();
819 int selectedCount = 0;
820 if (currentView == VIEWS_FILTER)
822 selectedCount = getResultTable().getSelectedRows().length;
823 if (selectedCount > 0)
825 btn_add.setEnabled(true);
828 else if (currentView == VIEWS_LOCAL_PDB)
830 selectedCount = tbl_local_pdb.getSelectedRows().length;
831 if (selectedCount > 0)
833 btn_add.setEnabled(true);
836 else if (currentView == VIEWS_ENTER_ID)
838 validateAssociationEnterPdb();
840 else if (currentView == VIEWS_FROM_FILE)
842 validateAssociationFromFile();
845 btn_newView.setEnabled(btn_add.isEnabled());
848 * enable 'Superpose' option if more than one structure is selected,
849 * or there are view(s) available to add structure(s) to
852 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
856 protected boolean showPopupFor(int selectedRow, int x, int y)
858 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
860 String currentView = selectedFilterOpt.getView();
862 if (currentView == VIEWS_FILTER
863 && data instanceof ThreeDBStructureChooserQuerySource)
866 TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
867 .getFTSDataFor(getResultTable(), selectedRow,
868 discoveredStructuresSet);
869 String pageUrl = row.getModelViewUrl();
870 JPopupMenu popup = new JPopupMenu("3D Beacons");
871 JMenuItem viewUrl = new JMenuItem("View model web page");
872 viewUrl.addActionListener(new ActionListener()
875 public void actionPerformed(ActionEvent e)
877 Desktop.showUrl(pageUrl);
881 SwingUtilities.invokeLater(new Runnable()
886 popup.show(getResultTable(), x, y);
891 // event not handled by us
896 * Validates inputs from the Manual PDB entry panel
898 protected void validateAssociationEnterPdb()
900 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
901 .getCmb_assSeq().getSelectedItem();
902 lbl_pdbManualFetchStatus.setIcon(errorImage);
903 lbl_pdbManualFetchStatus.setToolTipText("");
904 if (txt_search.getText().length() > 0)
906 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
907 MessageManager.formatMessage("info.no_pdb_entry_found_for",
908 txt_search.getText())));
911 if (errorWarning.length() > 0)
913 lbl_pdbManualFetchStatus.setIcon(warningImage);
914 lbl_pdbManualFetchStatus.setToolTipText(
915 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
918 if (selectedSequences.length == 1 || !assSeqOpt.getName()
919 .equalsIgnoreCase("-Select Associated Seq-"))
921 txt_search.setEnabled(true);
924 btn_add.setEnabled(true);
925 lbl_pdbManualFetchStatus.setToolTipText("");
926 lbl_pdbManualFetchStatus.setIcon(goodImage);
931 txt_search.setEnabled(false);
932 lbl_pdbManualFetchStatus.setIcon(errorImage);
937 * Validates inputs for the manual PDB file selection options
939 protected void validateAssociationFromFile()
941 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
942 .getCmb_assSeq().getSelectedItem();
943 lbl_fromFileStatus.setIcon(errorImage);
944 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
945 .getName().equalsIgnoreCase("-Select Associated Seq-")))
947 btn_pdbFromFile.setEnabled(true);
948 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
950 btn_add.setEnabled(true);
951 lbl_fromFileStatus.setIcon(goodImage);
956 btn_pdbFromFile.setEnabled(false);
957 lbl_fromFileStatus.setIcon(errorImage);
962 protected void cmbAssSeqStateChanged()
964 validateSelections();
967 private FilterOption lastSelected = null;
970 * Handles the state change event for the 'filter' combo-box and 'invert'
974 protected void stateChanged(ItemEvent e)
976 if (e.getSource() instanceof JCheckBox)
982 if (e.getStateChange() == ItemEvent.SELECTED)
991 * select structures for viewing by their PDB IDs
994 * @return true if structures were found and marked as selected
996 public boolean selectStructure(String... pdbids)
998 boolean found = false;
1000 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1001 .getSelectedItem());
1002 String currentView = selectedFilterOpt.getView();
1003 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1004 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
1006 if (restable == null)
1008 // can't select (enter PDB ID, or load file - need to also select which
1009 // sequence to associate with)
1013 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
1014 for (int r = 0; r < restable.getRowCount(); r++)
1016 for (int p = 0; p < pdbids.length; p++)
1018 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1019 .equalsIgnoreCase(pdbids[p]))
1021 restable.setRowSelectionInterval(r, r);
1030 * Handles the 'New View' action
1033 protected void newView_ActionPerformed()
1035 targetView.setSelectedItem(null);
1036 showStructures(false);
1040 * Handles the 'Add to existing viewer' action
1043 protected void add_ActionPerformed()
1045 showStructures(false);
1049 * structure viewer opened by this dialog, or null
1051 private StructureViewer sViewer = null;
1053 public void showStructures(boolean waitUntilFinished)
1056 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1058 final int preferredHeight = pnl_filter.getHeight();
1060 Runnable viewStruc = new Runnable()
1065 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1066 .getSelectedItem());
1067 String currentView = selectedFilterOpt.getView();
1068 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1071 if (currentView == VIEWS_FILTER)
1073 int[] selectedRows = restable.getSelectedRows();
1074 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1075 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1076 pdbEntriesToView = data.collectSelectedRows(restable,
1077 selectedRows, selectedSeqsToView);
1079 SequenceI[] selectedSeqs = selectedSeqsToView
1080 .toArray(new SequenceI[selectedSeqsToView.size()]);
1081 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1084 else if (currentView == VIEWS_LOCAL_PDB)
1086 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1087 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1089 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1091 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1093 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1094 for (int row : selectedRows)
1096 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1097 .getModel()).getPDBEntryAt(row).getPdbEntry();
1099 pdbEntriesToView[count++] = pdbEntry;
1100 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1101 .getValueAt(row, refSeqColIndex);
1102 selectedSeqsToView.add(selectedSeq);
1104 SequenceI[] selectedSeqs = selectedSeqsToView
1105 .toArray(new SequenceI[selectedSeqsToView.size()]);
1106 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1109 else if (currentView == VIEWS_ENTER_ID)
1111 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1112 .getCmb_assSeq().getSelectedItem()).getSequence();
1113 if (userSelectedSeq != null)
1115 selectedSequence = userSelectedSeq;
1117 String pdbIdStr = txt_search.getText();
1118 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1119 if (pdbEntry == null)
1121 pdbEntry = new PDBEntry();
1122 if (pdbIdStr.split(":").length > 1)
1124 pdbEntry.setId(pdbIdStr.split(":")[0]);
1125 pdbEntry.setChainCode(
1126 pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1130 pdbEntry.setId(pdbIdStr);
1132 pdbEntry.setType(PDBEntry.Type.PDB);
1133 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1136 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1137 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1139 { selectedSequence });
1141 else if (currentView == VIEWS_FROM_FILE)
1143 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1144 .getCmb_assSeq().getSelectedItem()).getSequence();
1145 if (userSelectedSeq != null)
1147 selectedSequence = userSelectedSeq;
1149 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1150 .associatePdbWithSeq(selectedPdbFileName,
1151 DataSourceType.FILE, selectedSequence, true,
1154 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1156 { selectedSequence });
1158 SwingUtilities.invokeLater(new Runnable()
1163 closeAction(preferredHeight);
1164 mainFrame.dispose();
1169 Thread runner = new Thread(viewStruc);
1171 if (waitUntilFinished)
1173 while (sViewer == null ? runner.isAlive()
1174 : (sViewer.sview == null ? true
1175 : !sViewer.sview.hasMapping()))
1180 } catch (InterruptedException ie)
1189 * Answers a structure viewer (new or existing) configured to superimpose
1190 * added structures or not according to the user's choice
1195 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1197 Object sv = targetView.getSelectedItem();
1199 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1203 * Adds PDB structures to a new or existing structure viewer
1206 * @param pdbEntriesToView
1211 private StructureViewer launchStructureViewer(
1212 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1213 final AlignmentPanel alignPanel, SequenceI[] sequences)
1215 long progressId = sequences.hashCode();
1216 setProgressBar(MessageManager
1217 .getString("status.launching_3d_structure_viewer"), progressId);
1218 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1219 boolean superimpose = chk_superpose.isSelected();
1220 theViewer.setSuperpose(superimpose);
1223 * remember user's choice of superimpose or not
1225 Cache.setProperty(AUTOSUPERIMPOSE,
1226 Boolean.valueOf(superimpose).toString());
1228 setProgressBar(null, progressId);
1229 if (SiftsSettings.isMapWithSifts())
1231 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1233 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1234 // real PDB ID. For moment, we can also safely do this if there is already
1235 // a known mapping between the PDBEntry and the sequence.
1236 for (SequenceI seq : sequences)
1238 PDBEntry pdbe = pdbEntriesToView[p++];
1239 if (pdbe != null && pdbe.getFile() != null)
1241 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1242 if (smm != null && smm.length > 0)
1244 for (StructureMapping sm : smm)
1246 if (sm.getSequence() == seq)
1253 if (seq.getPrimaryDBRefs().isEmpty())
1255 seqsWithoutSourceDBRef.add(seq);
1259 if (!seqsWithoutSourceDBRef.isEmpty())
1261 int y = seqsWithoutSourceDBRef.size();
1262 setProgressBar(MessageManager.formatMessage(
1263 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1265 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1266 .toArray(new SequenceI[y]);
1267 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1268 dbRefFetcher.fetchDBRefs(true);
1270 setProgressBar("Fetch complete.", progressId); // todo i18n
1273 if (pdbEntriesToView.length > 1)
1276 MessageManager.getString(
1277 "status.fetching_3d_structures_for_selected_entries"),
1279 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1283 setProgressBar(MessageManager.formatMessage(
1284 "status.fetching_3d_structures_for",
1285 pdbEntriesToView[0].getId()), progressId);
1286 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1288 setProgressBar(null, progressId);
1289 // remember the last viewer we used...
1290 lastTargetedView = theViewer;
1295 * Populates the combo-box used in associating manually fetched structures to
1296 * a unique sequence when more than one sequence selection is made.
1299 protected void populateCmbAssociateSeqOptions(
1300 JComboBox<AssociateSeqOptions> cmb_assSeq,
1301 JLabel lbl_associateSeq)
1303 cmb_assSeq.removeAllItems();
1305 new AssociateSeqOptions("-Select Associated Seq-", null));
1306 lbl_associateSeq.setVisible(false);
1307 if (selectedSequences.length > 1)
1309 for (SequenceI seq : selectedSequences)
1311 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1316 String seqName = selectedSequence.getDisplayId(false);
1317 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1318 lbl_associateSeq.setText(seqName);
1319 lbl_associateSeq.setVisible(true);
1320 cmb_assSeq.setVisible(false);
1324 protected boolean isStructuresDiscovered()
1326 return discoveredStructuresSet != null
1327 && !discoveredStructuresSet.isEmpty();
1330 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1332 // Doing a search for "1" or "1c" is valuable?
1333 // Those work but are enormously slow.
1336 protected void txt_search_ActionPerformed()
1338 String text = txt_search.getText().trim();
1339 if (text.length() >= PDB_ID_MIN)
1346 errorWarning.setLength(0);
1347 isValidPBDEntry = false;
1348 if (text.length() > 0)
1350 // TODO move this pdb id search into the PDB specific
1352 // for moment, it will work fine as is because it is self-contained
1353 String searchTerm = text.toLowerCase(Locale.ROOT);
1354 searchTerm = searchTerm.split(":")[0];
1355 // System.out.println(">>>>> search term : " + searchTerm);
1356 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1357 FTSRestRequest pdbRequest = new FTSRestRequest();
1358 pdbRequest.setAllowEmptySeq(false);
1359 pdbRequest.setResponseSize(1);
1360 pdbRequest.setFieldToSearchBy("(pdb_id:");
1361 pdbRequest.setWantedFields(wantedFields);
1362 pdbRequest.setSearchTerm(searchTerm + ")");
1363 pdbRequest.setAssociatedSequence(selectedSequence);
1364 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1365 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1366 FTSRestResponse resultList;
1369 resultList = pdbRestClient.executeRequest(pdbRequest);
1370 } catch (Exception e)
1372 errorWarning.append(e.getMessage());
1376 validateSelections();
1378 if (resultList.getSearchSummary() != null
1379 && resultList.getSearchSummary().size() > 0)
1381 isValidPBDEntry = true;
1384 validateSelections();
1390 protected void tabRefresh()
1392 if (selectedSequences != null)
1394 lbl_loading.setVisible(true);
1395 Thread refreshThread = new Thread(new Runnable()
1400 fetchStructuresMetaData();
1401 // populateFilterComboBox(true, cachedPDBExists);
1404 ((FilterOption) cmb_filterOption.getSelectedItem())
1406 lbl_loading.setVisible(false);
1409 refreshThread.start();
1413 public class PDBEntryTableModel extends AbstractTableModel
1415 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1418 private List<CachedPDB> pdbEntries;
1420 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1422 this.pdbEntries = new ArrayList<>(pdbEntries);
1426 public String getColumnName(int columnIndex)
1428 return columns[columnIndex];
1432 public int getRowCount()
1434 return pdbEntries.size();
1438 public int getColumnCount()
1440 return columns.length;
1444 public boolean isCellEditable(int row, int column)
1450 public Object getValueAt(int rowIndex, int columnIndex)
1452 Object value = "??";
1453 CachedPDB entry = pdbEntries.get(rowIndex);
1454 switch (columnIndex)
1457 value = entry.getSequence();
1460 value = entry.getQualifiedId();
1463 value = entry.getPdbEntry().getChainCode() == null ? "_"
1464 : entry.getPdbEntry().getChainCode();
1467 value = entry.getPdbEntry().getType();
1470 value = entry.getPdbEntry().getFile();
1477 public Class<?> getColumnClass(int columnIndex)
1479 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1482 public CachedPDB getPDBEntryAt(int row)
1484 return pdbEntries.get(row);
1489 private class CachedPDB
1491 private SequenceI sequence;
1493 private PDBEntry pdbEntry;
1495 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1497 this.sequence = sequence;
1498 this.pdbEntry = pdbEntry;
1501 public String getQualifiedId()
1503 if (pdbEntry.hasProvider())
1505 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1507 return pdbEntry.toString();
1510 public SequenceI getSequence()
1515 public PDBEntry getPdbEntry()
1522 private IProgressIndicator progressBar;
1525 public void setProgressBar(String message, long id)
1527 progressBar.setProgressBar(message, id);
1531 public void registerHandler(long id, IProgressIndicatorHandler handler)
1533 progressBar.registerHandler(id, handler);
1537 public boolean operationInProgress()
1539 return progressBar.operationInProgress();
1542 public JalviewStructureDisplayI getOpenedStructureViewer()
1544 return sViewer == null ? null : sViewer.sview;
1548 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1550 data.setDocFieldPrefs(newPrefs);
1556 * @return true when all initialisation threads have finished and dialog is
1559 public boolean isDialogVisible()
1561 return mainFrame != null && data != null && cmb_filterOption != null
1562 && mainFrame.isVisible()
1563 && cmb_filterOption.getSelectedItem() != null;
1568 * @return true if the 3D-Beacons query button will/has been displayed
1570 public boolean isCanQueryTDB()
1575 public boolean isNotQueriedTDBYet()
1577 return notQueriedTDBYet;