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 populateSeqsWithoutSourceDBRef();
326 final int y = seqsWithoutSourceDBRef.size();
329 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
330 .toArray(new SequenceI[y]);
331 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
332 progressBar, new DbSourceProxy[]
333 { new jalview.ws.dbsources.Uniprot() }, null, false);
334 dbRefFetcher.addListener(afterDbRefFetch);
335 // ideally this would also gracefully run with callbacks
336 dbRefFetcher.fetchDBRefs(true);
340 // call finished action directly
341 afterDbRefFetch.finished();
346 final Runnable revertview = new Runnable()
351 if (lastSelected != null)
353 cmb_filterOption.setSelectedItem(lastSelected);
357 int threshold = Cache.getDefault("THRESHOLD_WARN_UNIPROT_FETCH",
358 THRESHOLD_WARN_UNIPROT_FETCH_NEEDED);
359 Console.debug("Using Uniprot fetch threshold of " + threshold);
360 boolean runThread = false;
361 if (ignoreGui || seqsWithoutSourceDBRef.size() < threshold)
365 // need cancel and no to result in the discoverPDB action - mocked is
366 // 'cancel' TODO: mock should be OK
369 int answer = JvOptionPane.showOptionDialog(this,
371 MessageManager.formatMessage(
372 "label.fetch_references_for_3dbeacons",
373 seqsWithoutSourceDBRef.size()),
375 MessageManager.getString("label.3dbeacons"),
377 JvOptionPane.YES_NO_OPTION,
379 JvOptionPane.PLAIN_MESSAGE,
384 { MessageManager.getString("action.ok"),
385 MessageManager.getString("action.cancel") },
387 MessageManager.getString("action.ok")
390 runThread = (answer == JvOptionPane.OK_OPTION);
394 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs)
405 * Builds a drop-down choice list of existing structure viewers to which new
406 * structures may be added. If this list is empty then it, and the 'Add'
407 * button, are hidden.
409 private void discoverStructureViews()
411 if (Desktop.instance != null)
413 targetView.removeAllItems();
414 if (lastTargetedView != null && !lastTargetedView.isVisible())
416 lastTargetedView = null;
418 int linkedViewsAt = 0;
419 for (StructureViewerBase view : Desktop.instance
420 .getStructureViewers(null, null))
422 StructureViewer viewHandler = (lastTargetedView != null
423 && lastTargetedView.sview == view) ? lastTargetedView
424 : StructureViewer.reconfigure(view);
426 if (view.isLinkedWith(ap))
428 targetView.insertItemAt(viewHandler, linkedViewsAt++);
432 targetView.addItem(viewHandler);
437 * show option to Add to viewer if at least 1 viewer found
439 targetView.setVisible(false);
440 if (targetView.getItemCount() > 0)
442 targetView.setVisible(true);
443 if (lastTargetedView != null)
445 targetView.setSelectedItem(lastTargetedView);
449 targetView.setSelectedIndex(0);
452 btn_add.setVisible(targetView.isVisible());
457 * Updates the progress indicator with the specified message
460 * displayed message for the operation
462 * unique handle for this indicator
464 protected void updateProgressIndicator(String message, long id)
466 if (progressIndicator != null)
468 progressIndicator.setProgressBar(message, id);
473 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
476 void fetchStructuresMetaData()
478 long startTime = System.currentTimeMillis();
479 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
480 .getStructureSummaryFields();
482 discoveredStructuresSet = new LinkedHashSet<>();
483 HashSet<String> errors = new HashSet<>();
485 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
488 for (SequenceI seq : selectedSequences)
491 FTSRestResponse resultList;
494 resultList = data.fetchStructuresMetaData(seq, wantedFields,
495 selectedFilterOpt, !chk_invertFilter.isSelected());
496 // null response means the FTSengine didn't yield a query for this
497 // consider designing a special exception if we really wanted to be
499 if (resultList == null)
503 } catch (Exception e)
506 errors.add(e.getMessage());
509 if (resultList.getSearchSummary() != null
510 && !resultList.getSearchSummary().isEmpty())
512 discoveredStructuresSet.addAll(resultList.getSearchSummary());
516 int noOfStructuresFound = 0;
517 String totalTime = (System.currentTimeMillis() - startTime)
519 if (discoveredStructuresSet != null
520 && !discoveredStructuresSet.isEmpty())
523 .setModel(data.getTableModel(discoveredStructuresSet));
525 noOfStructuresFound = discoveredStructuresSet.size();
526 lastDiscoveredStructuresSet = discoveredStructuresSet;
527 mainFrame.setTitle(MessageManager.formatMessage(
528 "label.structure_chooser_no_of_structures",
529 noOfStructuresFound, totalTime));
533 mainFrame.setTitle(MessageManager
534 .getString("label.structure_chooser_manual_association"));
535 if (errors.size() > 0)
537 StringBuilder errorMsg = new StringBuilder();
538 for (String error : errors)
540 errorMsg.append(error).append("\n");
542 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
543 MessageManager.getString("label.pdb_web-service_error"),
544 JvOptionPane.ERROR_MESSAGE);
549 protected void loadLocalCachedPDBEntries()
551 ArrayList<CachedPDB> entries = new ArrayList<>();
552 for (SequenceI seq : selectedSequences)
554 if (seq.getDatasetSequence() != null
555 && seq.getDatasetSequence().getAllPDBEntries() != null)
557 for (PDBEntry pdbEntry : seq.getDatasetSequence()
560 if (pdbEntry.getFile() != null)
562 entries.add(new CachedPDB(seq, pdbEntry));
567 cachedPDBExists = !entries.isEmpty();
568 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
569 tbl_local_pdb.setModel(tableModelx);
573 * Filters a given list of discovered structures based on supplied argument
575 * @param fieldToFilterBy
576 * the field to filter by
578 void filterResultSet(final String fieldToFilterBy)
580 Thread filterThread = new Thread(new Runnable()
586 long startTime = System.currentTimeMillis();
587 lbl_loading.setVisible(true);
588 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
589 .getStructureSummaryFields();
590 Collection<FTSData> filteredResponse = new HashSet<>();
591 HashSet<String> errors = new HashSet<>();
593 for (SequenceI seq : selectedSequences)
596 FTSRestResponse resultList;
599 resultList = data.selectFirstRankedQuery(seq,
600 discoveredStructuresSet, wantedFields, fieldToFilterBy,
601 !chk_invertFilter.isSelected());
603 } catch (Exception e)
606 errors.add(e.getMessage());
609 if (resultList.getSearchSummary() != null
610 && !resultList.getSearchSummary().isEmpty())
612 filteredResponse.addAll(resultList.getSearchSummary());
616 String totalTime = (System.currentTimeMillis() - startTime)
618 if (!filteredResponse.isEmpty())
620 final int filterResponseCount = filteredResponse.size();
621 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
622 reorderedStructuresSet.addAll(filteredResponse);
623 reorderedStructuresSet.addAll(discoveredStructuresSet);
625 .setModel(data.getTableModel(reorderedStructuresSet));
627 FTSRestResponse.configureTableColumn(getResultTable(),
628 wantedFields, tempUserPrefs);
629 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
630 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
631 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
632 // Update table selection model here
633 getResultTable().addRowSelectionInterval(0,
634 filterResponseCount - 1);
635 mainFrame.setTitle(MessageManager.formatMessage(
636 "label.structure_chooser_filter_time", totalTime));
640 mainFrame.setTitle(MessageManager.formatMessage(
641 "label.structure_chooser_filter_time", totalTime));
642 if (errors.size() > 0)
644 StringBuilder errorMsg = new StringBuilder();
645 for (String error : errors)
647 errorMsg.append(error).append("\n");
649 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
650 MessageManager.getString("label.pdb_web-service_error"),
651 JvOptionPane.ERROR_MESSAGE);
655 lbl_loading.setVisible(false);
657 validateSelections();
660 filterThread.start();
664 * Handles action event for btn_pdbFromFile
667 protected void pdbFromFile_actionPerformed()
669 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
672 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
673 Cache.getProperty("LAST_DIRECTORY"));
674 chooser.setFileView(new jalview.io.JalviewFileView());
675 chooser.setDialogTitle(
676 MessageManager.formatMessage("label.select_pdb_file_for",
677 selectedSequence.getDisplayId(false)));
678 chooser.setToolTipText(MessageManager.formatMessage(
679 "label.load_pdb_file_associate_with_sequence",
680 selectedSequence.getDisplayId(false)));
682 int value = chooser.showOpenDialog(null);
683 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
685 selectedPdbFileName = chooser.getSelectedFile().getPath();
686 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
687 validateSelections();
692 * Populates the filter combo-box options dynamically depending on discovered
695 protected void populateFilterComboBox(boolean haveData,
696 boolean cachedPDBExist)
698 populateFilterComboBox(haveData, cachedPDBExist, null);
702 * Populates the filter combo-box options dynamically depending on discovered
705 protected void populateFilterComboBox(boolean haveData,
706 boolean cachedPDBExist, FilterOption lastSel)
710 * temporarily suspend the change listener behaviour
712 cmb_filterOption.removeItemListener(this);
714 cmb_filterOption.removeAllItems();
717 List<FilterOption> filters = data
718 .getAvailableFilterOptions(VIEWS_FILTER);
719 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
720 lastDiscoveredStructuresSet);
722 for (FilterOption filter : filters)
724 if (lastSel != null && filter.equals(lastSel))
729 cmb_filterOption.addItem(filter);
733 cmb_filterOption.addItem(
734 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
735 "-", VIEWS_ENTER_ID, false, null));
736 cmb_filterOption.addItem(
737 new FilterOption(MessageManager.getString("label.from_file"),
738 "-", VIEWS_FROM_FILE, false, null));
739 if (canQueryTDB && notQueriedTDBYet)
741 btn_queryTDB.setVisible(true);
742 pnl_queryTDB.setVisible(true);
747 FilterOption cachedOption = new FilterOption(
748 MessageManager.getString("label.cached_structures"), "-",
749 VIEWS_LOCAL_PDB, false, null);
750 cmb_filterOption.addItem(cachedOption);
753 cmb_filterOption.setSelectedItem(cachedOption);
758 cmb_filterOption.setSelectedIndex(selSet);
760 cmb_filterOption.addItemListener(this);
764 * Updates the displayed view based on the selected filter option
766 protected void updateCurrentView()
768 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
771 if (lastSelected == selectedFilterOpt)
773 // don't need to do anything, probably
776 // otherwise, record selection
777 // and update the layout and dialog accordingly
778 lastSelected = selectedFilterOpt;
780 layout_switchableViews.show(pnl_switchableViews,
781 selectedFilterOpt.getView());
782 String filterTitle = mainFrame.getTitle();
783 mainFrame.setTitle(frameTitle);
784 chk_invertFilter.setVisible(false);
786 if (selectedFilterOpt.getView() == VIEWS_FILTER)
788 mainFrame.setTitle(filterTitle);
789 // TDB Query has no invert as yet
790 chk_invertFilter.setVisible(selectedFilterOpt
791 .getQuerySource() instanceof PDBStructureChooserQuerySource);
793 if (data != selectedFilterOpt.getQuerySource()
794 || data.needsRefetch(selectedFilterOpt))
796 data = selectedFilterOpt.getQuerySource();
797 // rebuild the views completely, since prefs will also change
803 filterResultSet(selectedFilterOpt.getValue());
806 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
807 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
809 mainFrame.setTitle(MessageManager
810 .getString("label.structure_chooser_manual_association"));
811 idInputAssSeqPanel.loadCmbAssSeq();
812 fileChooserAssSeqPanel.loadCmbAssSeq();
814 validateSelections();
818 * Validates user selection and enables the 'Add' and 'New View' buttons if
819 * all parameters are correct (the Add button will only be visible if there is
820 * at least one existing structure viewer open). This basically means at least
821 * one structure selected and no error messages.
823 * The 'Superpose Structures' option is enabled if either more than one
824 * structure is selected, or the 'Add' to existing view option is enabled, and
825 * disabled if the only option is to open a new view of a single structure.
828 protected void validateSelections()
830 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
832 btn_add.setEnabled(false);
833 String currentView = selectedFilterOpt.getView();
834 int selectedCount = 0;
835 if (currentView == VIEWS_FILTER)
837 selectedCount = getResultTable().getSelectedRows().length;
838 if (selectedCount > 0)
840 btn_add.setEnabled(true);
843 else if (currentView == VIEWS_LOCAL_PDB)
845 selectedCount = tbl_local_pdb.getSelectedRows().length;
846 if (selectedCount > 0)
848 btn_add.setEnabled(true);
851 else if (currentView == VIEWS_ENTER_ID)
853 validateAssociationEnterPdb();
855 else if (currentView == VIEWS_FROM_FILE)
857 validateAssociationFromFile();
860 btn_newView.setEnabled(btn_add.isEnabled());
863 * enable 'Superpose' option if more than one structure is selected,
864 * or there are view(s) available to add structure(s) to
867 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
871 protected boolean showPopupFor(int selectedRow, int x, int y)
873 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
875 String currentView = selectedFilterOpt.getView();
877 if (currentView == VIEWS_FILTER
878 && data instanceof ThreeDBStructureChooserQuerySource)
881 TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
882 .getFTSDataFor(getResultTable(), selectedRow,
883 discoveredStructuresSet);
884 String pageUrl = row.getModelViewUrl();
885 JPopupMenu popup = new JPopupMenu("3D Beacons");
886 JMenuItem viewUrl = new JMenuItem("View model web page");
887 viewUrl.addActionListener(new ActionListener()
890 public void actionPerformed(ActionEvent e)
892 Desktop.showUrl(pageUrl);
896 SwingUtilities.invokeLater(new Runnable()
901 popup.show(getResultTable(), x, y);
906 // event not handled by us
911 * Validates inputs from the Manual PDB entry panel
913 protected void validateAssociationEnterPdb()
915 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
916 .getCmb_assSeq().getSelectedItem();
917 lbl_pdbManualFetchStatus.setIcon(errorImage);
918 lbl_pdbManualFetchStatus.setToolTipText("");
919 if (txt_search.getText().length() > 0)
921 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
922 MessageManager.formatMessage("info.no_pdb_entry_found_for",
923 txt_search.getText())));
926 if (errorWarning.length() > 0)
928 lbl_pdbManualFetchStatus.setIcon(warningImage);
929 lbl_pdbManualFetchStatus.setToolTipText(
930 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
933 if (selectedSequences.length == 1 || !assSeqOpt.getName()
934 .equalsIgnoreCase("-Select Associated Seq-"))
936 txt_search.setEnabled(true);
939 btn_add.setEnabled(true);
940 lbl_pdbManualFetchStatus.setToolTipText("");
941 lbl_pdbManualFetchStatus.setIcon(goodImage);
946 txt_search.setEnabled(false);
947 lbl_pdbManualFetchStatus.setIcon(errorImage);
952 * Validates inputs for the manual PDB file selection options
954 protected void validateAssociationFromFile()
956 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
957 .getCmb_assSeq().getSelectedItem();
958 lbl_fromFileStatus.setIcon(errorImage);
959 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
960 .getName().equalsIgnoreCase("-Select Associated Seq-")))
962 btn_pdbFromFile.setEnabled(true);
963 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
965 btn_add.setEnabled(true);
966 lbl_fromFileStatus.setIcon(goodImage);
971 btn_pdbFromFile.setEnabled(false);
972 lbl_fromFileStatus.setIcon(errorImage);
977 protected void cmbAssSeqStateChanged()
979 validateSelections();
982 private FilterOption lastSelected = null;
985 * Handles the state change event for the 'filter' combo-box and 'invert'
989 protected void stateChanged(ItemEvent e)
991 if (e.getSource() instanceof JCheckBox)
997 if (e.getStateChange() == ItemEvent.SELECTED)
1006 * select structures for viewing by their PDB IDs
1009 * @return true if structures were found and marked as selected
1011 public boolean selectStructure(String... pdbids)
1013 boolean found = false;
1015 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1016 .getSelectedItem());
1017 String currentView = selectedFilterOpt.getView();
1018 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1019 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
1021 if (restable == null)
1023 // can't select (enter PDB ID, or load file - need to also select which
1024 // sequence to associate with)
1028 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
1029 for (int r = 0; r < restable.getRowCount(); r++)
1031 for (int p = 0; p < pdbids.length; p++)
1033 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1034 .equalsIgnoreCase(pdbids[p]))
1036 restable.setRowSelectionInterval(r, r);
1045 * Handles the 'New View' action
1048 protected void newView_ActionPerformed()
1050 targetView.setSelectedItem(null);
1051 showStructures(false);
1055 * Handles the 'Add to existing viewer' action
1058 protected void add_ActionPerformed()
1060 showStructures(false);
1064 * structure viewer opened by this dialog, or null
1066 private StructureViewer sViewer = null;
1068 public void showStructures(boolean waitUntilFinished)
1071 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1073 final int preferredHeight = pnl_filter.getHeight();
1075 Runnable viewStruc = new Runnable()
1080 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1081 .getSelectedItem());
1082 String currentView = selectedFilterOpt.getView();
1083 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1086 if (currentView == VIEWS_FILTER)
1088 int[] selectedRows = restable.getSelectedRows();
1089 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1090 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1091 pdbEntriesToView = data.collectSelectedRows(restable,
1092 selectedRows, selectedSeqsToView);
1094 SequenceI[] selectedSeqs = selectedSeqsToView
1095 .toArray(new SequenceI[selectedSeqsToView.size()]);
1096 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1099 else if (currentView == VIEWS_LOCAL_PDB)
1101 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1102 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1104 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1106 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1108 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1109 for (int row : selectedRows)
1111 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1112 .getModel()).getPDBEntryAt(row).getPdbEntry();
1114 pdbEntriesToView[count++] = pdbEntry;
1115 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1116 .getValueAt(row, refSeqColIndex);
1117 selectedSeqsToView.add(selectedSeq);
1119 SequenceI[] selectedSeqs = selectedSeqsToView
1120 .toArray(new SequenceI[selectedSeqsToView.size()]);
1121 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1124 else if (currentView == VIEWS_ENTER_ID)
1126 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1127 .getCmb_assSeq().getSelectedItem()).getSequence();
1128 if (userSelectedSeq != null)
1130 selectedSequence = userSelectedSeq;
1132 String pdbIdStr = txt_search.getText();
1133 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1134 if (pdbEntry == null)
1136 pdbEntry = new PDBEntry();
1137 if (pdbIdStr.split(":").length > 1)
1139 pdbEntry.setId(pdbIdStr.split(":")[0]);
1140 pdbEntry.setChainCode(
1141 pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1145 pdbEntry.setId(pdbIdStr);
1147 pdbEntry.setType(PDBEntry.Type.PDB);
1148 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1151 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1152 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1154 { selectedSequence });
1156 else if (currentView == VIEWS_FROM_FILE)
1158 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1159 .getCmb_assSeq().getSelectedItem()).getSequence();
1160 if (userSelectedSeq != null)
1162 selectedSequence = userSelectedSeq;
1164 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1165 .associatePdbWithSeq(selectedPdbFileName,
1166 DataSourceType.FILE, selectedSequence, true,
1169 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1171 { selectedSequence });
1173 SwingUtilities.invokeLater(new Runnable()
1178 closeAction(preferredHeight);
1179 mainFrame.dispose();
1184 Thread runner = new Thread(viewStruc);
1186 if (waitUntilFinished)
1188 while (sViewer == null ? runner.isAlive()
1189 : (sViewer.sview == null ? true
1190 : !sViewer.sview.hasMapping()))
1195 } catch (InterruptedException ie)
1204 * Answers a structure viewer (new or existing) configured to superimpose
1205 * added structures or not according to the user's choice
1210 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1212 Object sv = targetView.getSelectedItem();
1214 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1218 * Adds PDB structures to a new or existing structure viewer
1221 * @param pdbEntriesToView
1226 private StructureViewer launchStructureViewer(
1227 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1228 final AlignmentPanel alignPanel, SequenceI[] sequences)
1230 long progressId = sequences.hashCode();
1231 setProgressBar(MessageManager
1232 .getString("status.launching_3d_structure_viewer"), progressId);
1233 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1234 boolean superimpose = chk_superpose.isSelected();
1235 theViewer.setSuperpose(superimpose);
1238 * remember user's choice of superimpose or not
1240 Cache.setProperty(AUTOSUPERIMPOSE,
1241 Boolean.valueOf(superimpose).toString());
1243 setProgressBar(null, progressId);
1244 if (SiftsSettings.isMapWithSifts())
1246 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1248 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1249 // real PDB ID. For moment, we can also safely do this if there is already
1250 // a known mapping between the PDBEntry and the sequence.
1251 for (SequenceI seq : sequences)
1253 PDBEntry pdbe = pdbEntriesToView[p++];
1254 if (pdbe != null && pdbe.getFile() != null)
1256 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1257 if (smm != null && smm.length > 0)
1259 for (StructureMapping sm : smm)
1261 if (sm.getSequence() == seq)
1268 if (seq.getPrimaryDBRefs().isEmpty())
1270 seqsWithoutSourceDBRef.add(seq);
1274 if (!seqsWithoutSourceDBRef.isEmpty())
1276 int y = seqsWithoutSourceDBRef.size();
1277 setProgressBar(MessageManager.formatMessage(
1278 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1280 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1281 .toArray(new SequenceI[y]);
1282 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1283 dbRefFetcher.fetchDBRefs(true);
1285 setProgressBar("Fetch complete.", progressId); // todo i18n
1288 if (pdbEntriesToView.length > 1)
1291 MessageManager.getString(
1292 "status.fetching_3d_structures_for_selected_entries"),
1294 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1298 setProgressBar(MessageManager.formatMessage(
1299 "status.fetching_3d_structures_for",
1300 pdbEntriesToView[0].getId()), progressId);
1301 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1303 setProgressBar(null, progressId);
1304 // remember the last viewer we used...
1305 lastTargetedView = theViewer;
1310 * Populates the combo-box used in associating manually fetched structures to
1311 * a unique sequence when more than one sequence selection is made.
1314 protected void populateCmbAssociateSeqOptions(
1315 JComboBox<AssociateSeqOptions> cmb_assSeq,
1316 JLabel lbl_associateSeq)
1318 cmb_assSeq.removeAllItems();
1320 new AssociateSeqOptions("-Select Associated Seq-", null));
1321 lbl_associateSeq.setVisible(false);
1322 if (selectedSequences.length > 1)
1324 for (SequenceI seq : selectedSequences)
1326 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1331 String seqName = selectedSequence.getDisplayId(false);
1332 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1333 lbl_associateSeq.setText(seqName);
1334 lbl_associateSeq.setVisible(true);
1335 cmb_assSeq.setVisible(false);
1339 protected boolean isStructuresDiscovered()
1341 return discoveredStructuresSet != null
1342 && !discoveredStructuresSet.isEmpty();
1345 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1347 // Doing a search for "1" or "1c" is valuable?
1348 // Those work but are enormously slow.
1351 protected void txt_search_ActionPerformed()
1353 String text = txt_search.getText().trim();
1354 if (text.length() >= PDB_ID_MIN)
1361 errorWarning.setLength(0);
1362 isValidPBDEntry = false;
1363 if (text.length() > 0)
1365 // TODO move this pdb id search into the PDB specific
1367 // for moment, it will work fine as is because it is self-contained
1368 String searchTerm = text.toLowerCase(Locale.ROOT);
1369 searchTerm = searchTerm.split(":")[0];
1370 // System.out.println(">>>>> search term : " + searchTerm);
1371 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1372 FTSRestRequest pdbRequest = new FTSRestRequest();
1373 pdbRequest.setAllowEmptySeq(false);
1374 pdbRequest.setResponseSize(1);
1375 pdbRequest.setFieldToSearchBy("(pdb_id:");
1376 pdbRequest.setWantedFields(wantedFields);
1377 pdbRequest.setSearchTerm(searchTerm + ")");
1378 pdbRequest.setAssociatedSequence(selectedSequence);
1379 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1380 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1381 FTSRestResponse resultList;
1384 resultList = pdbRestClient.executeRequest(pdbRequest);
1385 } catch (Exception e)
1387 errorWarning.append(e.getMessage());
1391 validateSelections();
1393 if (resultList.getSearchSummary() != null
1394 && resultList.getSearchSummary().size() > 0)
1396 isValidPBDEntry = true;
1399 validateSelections();
1405 protected void tabRefresh()
1407 if (selectedSequences != null)
1409 Thread refreshThread = new Thread(new Runnable()
1414 fetchStructuresMetaData();
1415 // populateFilterComboBox(true, cachedPDBExists);
1418 ((FilterOption) cmb_filterOption.getSelectedItem())
1422 refreshThread.start();
1426 public class PDBEntryTableModel extends AbstractTableModel
1428 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1431 private List<CachedPDB> pdbEntries;
1433 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1435 this.pdbEntries = new ArrayList<>(pdbEntries);
1439 public String getColumnName(int columnIndex)
1441 return columns[columnIndex];
1445 public int getRowCount()
1447 return pdbEntries.size();
1451 public int getColumnCount()
1453 return columns.length;
1457 public boolean isCellEditable(int row, int column)
1463 public Object getValueAt(int rowIndex, int columnIndex)
1465 Object value = "??";
1466 CachedPDB entry = pdbEntries.get(rowIndex);
1467 switch (columnIndex)
1470 value = entry.getSequence();
1473 value = entry.getQualifiedId();
1476 value = entry.getPdbEntry().getChainCode() == null ? "_"
1477 : entry.getPdbEntry().getChainCode();
1480 value = entry.getPdbEntry().getType();
1483 value = entry.getPdbEntry().getFile();
1490 public Class<?> getColumnClass(int columnIndex)
1492 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1495 public CachedPDB getPDBEntryAt(int row)
1497 return pdbEntries.get(row);
1502 private class CachedPDB
1504 private SequenceI sequence;
1506 private PDBEntry pdbEntry;
1508 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1510 this.sequence = sequence;
1511 this.pdbEntry = pdbEntry;
1514 public String getQualifiedId()
1516 if (pdbEntry.hasProvider())
1518 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1520 return pdbEntry.toString();
1523 public SequenceI getSequence()
1528 public PDBEntry getPdbEntry()
1535 private IProgressIndicator progressBar;
1538 public void setProgressBar(String message, long id)
1540 progressBar.setProgressBar(message, id);
1544 public void registerHandler(long id, IProgressIndicatorHandler handler)
1546 progressBar.registerHandler(id, handler);
1550 public boolean operationInProgress()
1552 return progressBar.operationInProgress();
1555 public JalviewStructureDisplayI getOpenedStructureViewer()
1557 return sViewer == null ? null : sViewer.sview;
1561 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1563 data.setDocFieldPrefs(newPrefs);
1569 * @return true when all initialisation threads have finished and dialog is
1572 public boolean isDialogVisible()
1574 return mainFrame != null && data != null && cmb_filterOption != null
1575 && mainFrame.isVisible()
1576 && cmb_filterOption.getSelectedItem() != null;
1581 * @return true if the 3D-Beacons query button will/has been displayed
1583 public boolean isCanQueryTDB()
1588 public boolean isNotQueriedTDBYet()
1590 return notQueriedTDBYet;