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.Jalview;
47 import jalview.datamodel.PDBEntry;
48 import jalview.datamodel.SequenceI;
49 import jalview.fts.api.FTSData;
50 import jalview.fts.api.FTSDataColumnI;
51 import jalview.fts.api.FTSRestClientI;
52 import jalview.fts.core.FTSDataColumnPreferences;
53 import jalview.fts.core.FTSRestRequest;
54 import jalview.fts.core.FTSRestResponse;
55 import jalview.fts.service.pdb.PDBFTSRestClient;
56 import jalview.fts.service.threedbeacons.TDB_FTSData;
57 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
58 import jalview.gui.structurechooser.StructureChooserQuerySource;
59 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
60 import jalview.io.DataSourceType;
61 import jalview.jbgui.FilterOption;
62 import jalview.jbgui.GStructureChooser;
63 import jalview.structure.StructureMapping;
64 import jalview.structure.StructureSelectionManager;
65 import jalview.util.MessageManager;
66 import jalview.ws.DBRefFetcher;
67 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
68 import jalview.ws.seqfetcher.DbSourceProxy;
69 import jalview.ws.sifts.SiftsSettings;
72 * Provides the behaviors for the Structure chooser Panel
77 @SuppressWarnings("serial")
78 public class StructureChooser extends GStructureChooser
79 implements IProgressIndicator
81 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
84 * warn user if need to fetch more than this many uniprot records at once
86 private static final int THRESHOLD_WARN_UNIPROT_FETCH_NEEDED = 20;
88 private SequenceI selectedSequence;
90 private SequenceI[] selectedSequences;
92 private IProgressIndicator progressIndicator;
94 private Collection<FTSData> discoveredStructuresSet;
96 private StructureChooserQuerySource data;
99 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
101 return data.getDocFieldPrefs();
104 private String selectedPdbFileName;
106 private boolean isValidPBDEntry;
108 private boolean cachedPDBExists;
110 private Collection<FTSData> lastDiscoveredStructuresSet;
112 private boolean canQueryTDB = false;
114 private boolean notQueriedTDBYet = true;
116 List<SequenceI> seqsWithoutSourceDBRef = null;
118 private static StructureViewer lastTargetedView = null;
120 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
123 // which FTS engine to use
124 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
128 this.selectedSequence = selectedSeq;
129 this.selectedSequences = selectedSeqs;
130 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
136 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
137 * least one structure are discovered.
139 private void populateSeqsWithoutSourceDBRef()
141 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
142 boolean needCanonical = false;
143 for (SequenceI seq : selectedSequences)
147 int dbRef = ThreeDBStructureChooserQuerySource
148 .checkUniprotRefs(seq.getDBRefs());
153 // need to retrieve canonicals
154 needCanonical = true;
155 seqsWithoutSourceDBRef.add(seq);
159 // could be a sequence with pdb ref
160 if (seq.getAllPDBEntries() == null
161 || seq.getAllPDBEntries().size() == 0)
163 seqsWithoutSourceDBRef.add(seq);
169 // retrieve database refs for protein sequences
170 if (!seqsWithoutSourceDBRef.isEmpty())
175 // triggers display of the 'Query TDB' button
176 notQueriedTDBYet = true;
182 * Initializes parameters used by the Structure Chooser Panel
184 protected void init()
186 if (!Jalview.isHeadlessMode())
188 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
191 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
192 btn_queryTDB.addActionListener(new ActionListener()
196 public void actionPerformed(ActionEvent e)
198 promptForTDBFetch(false);
202 Executors.defaultThreadFactory().newThread(new Runnable()
207 populateSeqsWithoutSourceDBRef();
208 initialStructureDiscovery();
216 private void initialStructureDiscovery()
218 // check which FTS engine to use
219 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
221 // ensure a filter option is in force for search
222 populateFilterComboBox(true, cachedPDBExists);
224 // looks for any existing structures already loaded
225 // for the sequences (the cached ones)
226 // then queries the StructureChooserQuerySource to
227 // discover more structures.
229 // Possible optimisation is to only begin querying
230 // the structure chooser if there are no cached structures.
232 long startTime = System.currentTimeMillis();
233 updateProgressIndicator(
234 MessageManager.getString("status.loading_cached_pdb_entries"),
236 loadLocalCachedPDBEntries();
237 updateProgressIndicator(null, startTime);
238 updateProgressIndicator(
239 MessageManager.getString("status.searching_for_pdb_structures"),
241 fetchStructuresMetaData();
242 // revise filter options if no results were found
243 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
244 discoverStructureViews();
245 updateProgressIndicator(null, startTime);
246 mainFrame.setVisible(true);
251 * raises dialog for Uniprot fetch followed by 3D beacons search
254 * - when true, don't ask, just fetch
256 public void promptForTDBFetch(boolean ignoreGui)
258 final long progressId = System.currentTimeMillis();
260 // final action after prompting and discovering db refs
261 final Runnable strucDiscovery = new Runnable()
266 mainFrame.setEnabled(false);
267 cmb_filterOption.setEnabled(false);
268 progressBar.setProgressBar(
269 MessageManager.getString("status.searching_3d_beacons"),
271 btn_queryTDB.setEnabled(false);
272 // TODO: warn if no accessions discovered
273 populateSeqsWithoutSourceDBRef();
274 // redo initial discovery - this time with 3d beacons
276 previousWantedFields = null;
277 lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
278 cmb_filterOption.setSelectedItem(null);
279 cachedPDBExists = false; // reset to initial
280 initialStructureDiscovery();
281 if (!isStructuresDiscovered())
283 progressBar.setProgressBar(MessageManager.getString(
284 "status.no_structures_discovered_from_3d_beacons"),
286 btn_queryTDB.setToolTipText(MessageManager.getString(
287 "status.no_structures_discovered_from_3d_beacons"));
288 btn_queryTDB.setEnabled(false);
289 pnl_queryTDB.setVisible(false);
293 cmb_filterOption.setSelectedIndex(0); // select 'best'
294 btn_queryTDB.setVisible(false);
295 pnl_queryTDB.setVisible(false);
296 progressBar.setProgressBar(null, progressId);
298 mainFrame.setEnabled(true);
299 cmb_filterOption.setEnabled(true);
303 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
307 public void finished()
309 // filter has been selected, so we set flag to remove ourselves
310 notQueriedTDBYet = false;
311 // new thread to discover structures - via 3d beacons
312 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
317 // fetch db refs if OK pressed
318 final Runnable discoverCanonicalDBrefs = new Runnable()
323 populateSeqsWithoutSourceDBRef();
325 final int y = seqsWithoutSourceDBRef.size();
328 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
329 .toArray(new SequenceI[y]);
330 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
331 progressBar, new DbSourceProxy[]
332 { new jalview.ws.dbsources.Uniprot() }, null, false);
333 dbRefFetcher.addListener(afterDbRefFetch);
334 // ideally this would also gracefully run with callbacks
335 dbRefFetcher.fetchDBRefs(true);
339 // call finished action directly
340 afterDbRefFetch.finished();
345 final Runnable revertview = new Runnable()
350 if (lastSelected != null)
352 cmb_filterOption.setSelectedItem(lastSelected);
356 if (ignoreGui || seqsWithoutSourceDBRef
357 .size() < THRESHOLD_WARN_UNIPROT_FETCH_NEEDED)
359 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs)
363 // need cancel and no to result in the discoverPDB action - mocked is
364 // 'cancel' TODO: mock should be OK
365 JvOptionPane.newOptionDialog(this)
366 .setResponseHandler(JvOptionPane.OK_OPTION,
367 discoverCanonicalDBrefs)
368 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
369 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
371 MessageManager.formatMessage(
372 "label.fetch_references_for_3dbeacons",
373 seqsWithoutSourceDBRef.size()),
374 MessageManager.getString("label.3dbeacons"),
375 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
377 { MessageManager.getString("action.ok"),
378 MessageManager.getString("action.cancel") },
379 MessageManager.getString("action.ok"));
383 * Builds a drop-down choice list of existing structure viewers to which new
384 * structures may be added. If this list is empty then it, and the 'Add'
385 * button, are hidden.
387 private void discoverStructureViews()
389 if (Desktop.instance != null)
391 targetView.removeAllItems();
392 if (lastTargetedView != null && !lastTargetedView.isVisible())
394 lastTargetedView = null;
396 int linkedViewsAt = 0;
397 for (StructureViewerBase view : Desktop.instance
398 .getStructureViewers(null, null))
400 StructureViewer viewHandler = (lastTargetedView != null
401 && lastTargetedView.sview == view) ? lastTargetedView
402 : StructureViewer.reconfigure(view);
404 if (view.isLinkedWith(ap))
406 targetView.insertItemAt(viewHandler, linkedViewsAt++);
410 targetView.addItem(viewHandler);
415 * show option to Add to viewer if at least 1 viewer found
417 targetView.setVisible(false);
418 if (targetView.getItemCount() > 0)
420 targetView.setVisible(true);
421 if (lastTargetedView != null)
423 targetView.setSelectedItem(lastTargetedView);
427 targetView.setSelectedIndex(0);
430 btn_add.setVisible(targetView.isVisible());
435 * Updates the progress indicator with the specified message
438 * displayed message for the operation
440 * unique handle for this indicator
442 protected void updateProgressIndicator(String message, long id)
444 if (progressIndicator != null)
446 progressIndicator.setProgressBar(message, id);
451 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
454 void fetchStructuresMetaData()
456 long startTime = System.currentTimeMillis();
457 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
458 .getStructureSummaryFields();
460 discoveredStructuresSet = new LinkedHashSet<>();
461 HashSet<String> errors = new HashSet<>();
463 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
466 for (SequenceI seq : selectedSequences)
469 FTSRestResponse resultList;
472 resultList = data.fetchStructuresMetaData(seq, wantedFields,
473 selectedFilterOpt, !chk_invertFilter.isSelected());
474 // null response means the FTSengine didn't yield a query for this
475 // consider designing a special exception if we really wanted to be
477 if (resultList == null)
481 } catch (Exception e)
484 errors.add(e.getMessage());
487 if (resultList.getSearchSummary() != null
488 && !resultList.getSearchSummary().isEmpty())
490 discoveredStructuresSet.addAll(resultList.getSearchSummary());
494 int noOfStructuresFound = 0;
495 String totalTime = (System.currentTimeMillis() - startTime)
497 if (discoveredStructuresSet != null
498 && !discoveredStructuresSet.isEmpty())
501 .setModel(data.getTableModel(discoveredStructuresSet));
503 noOfStructuresFound = discoveredStructuresSet.size();
504 lastDiscoveredStructuresSet = discoveredStructuresSet;
505 mainFrame.setTitle(MessageManager.formatMessage(
506 "label.structure_chooser_no_of_structures",
507 noOfStructuresFound, totalTime));
511 mainFrame.setTitle(MessageManager
512 .getString("label.structure_chooser_manual_association"));
513 if (errors.size() > 0)
515 StringBuilder errorMsg = new StringBuilder();
516 for (String error : errors)
518 errorMsg.append(error).append("\n");
520 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
521 MessageManager.getString("label.pdb_web-service_error"),
522 JvOptionPane.ERROR_MESSAGE);
527 protected void loadLocalCachedPDBEntries()
529 ArrayList<CachedPDB> entries = new ArrayList<>();
530 for (SequenceI seq : selectedSequences)
532 if (seq.getDatasetSequence() != null
533 && seq.getDatasetSequence().getAllPDBEntries() != null)
535 for (PDBEntry pdbEntry : seq.getDatasetSequence()
538 if (pdbEntry.getFile() != null)
540 entries.add(new CachedPDB(seq, pdbEntry));
545 cachedPDBExists = !entries.isEmpty();
546 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
547 tbl_local_pdb.setModel(tableModelx);
551 * Filters a given list of discovered structures based on supplied argument
553 * @param fieldToFilterBy
554 * the field to filter by
556 void filterResultSet(final String fieldToFilterBy)
558 Thread filterThread = new Thread(new Runnable()
564 long startTime = System.currentTimeMillis();
565 lbl_loading.setVisible(true);
566 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
567 .getStructureSummaryFields();
568 Collection<FTSData> filteredResponse = new HashSet<>();
569 HashSet<String> errors = new HashSet<>();
571 for (SequenceI seq : selectedSequences)
574 FTSRestResponse resultList;
577 resultList = data.selectFirstRankedQuery(seq,
578 discoveredStructuresSet, wantedFields, fieldToFilterBy,
579 !chk_invertFilter.isSelected());
581 } catch (Exception e)
584 errors.add(e.getMessage());
587 if (resultList.getSearchSummary() != null
588 && !resultList.getSearchSummary().isEmpty())
590 filteredResponse.addAll(resultList.getSearchSummary());
594 String totalTime = (System.currentTimeMillis() - startTime)
596 if (!filteredResponse.isEmpty())
598 final int filterResponseCount = filteredResponse.size();
599 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
600 reorderedStructuresSet.addAll(filteredResponse);
601 reorderedStructuresSet.addAll(discoveredStructuresSet);
603 .setModel(data.getTableModel(reorderedStructuresSet));
605 FTSRestResponse.configureTableColumn(getResultTable(),
606 wantedFields, tempUserPrefs);
607 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
608 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
609 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
610 // Update table selection model here
611 getResultTable().addRowSelectionInterval(0,
612 filterResponseCount - 1);
613 mainFrame.setTitle(MessageManager.formatMessage(
614 "label.structure_chooser_filter_time", totalTime));
618 mainFrame.setTitle(MessageManager.formatMessage(
619 "label.structure_chooser_filter_time", totalTime));
620 if (errors.size() > 0)
622 StringBuilder errorMsg = new StringBuilder();
623 for (String error : errors)
625 errorMsg.append(error).append("\n");
627 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
628 MessageManager.getString("label.pdb_web-service_error"),
629 JvOptionPane.ERROR_MESSAGE);
633 lbl_loading.setVisible(false);
635 validateSelections();
638 filterThread.start();
642 * Handles action event for btn_pdbFromFile
645 protected void pdbFromFile_actionPerformed()
647 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
650 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
651 Cache.getProperty("LAST_DIRECTORY"));
652 chooser.setFileView(new jalview.io.JalviewFileView());
653 chooser.setDialogTitle(
654 MessageManager.formatMessage("label.select_pdb_file_for",
655 selectedSequence.getDisplayId(false)));
656 chooser.setToolTipText(MessageManager.formatMessage(
657 "label.load_pdb_file_associate_with_sequence",
658 selectedSequence.getDisplayId(false)));
660 int value = chooser.showOpenDialog(null);
661 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
663 selectedPdbFileName = chooser.getSelectedFile().getPath();
664 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
665 validateSelections();
670 * Populates the filter combo-box options dynamically depending on discovered
673 protected void populateFilterComboBox(boolean haveData,
674 boolean cachedPDBExist)
676 populateFilterComboBox(haveData, cachedPDBExist, null);
680 * Populates the filter combo-box options dynamically depending on discovered
683 protected void populateFilterComboBox(boolean haveData,
684 boolean cachedPDBExist, FilterOption lastSel)
688 * temporarily suspend the change listener behaviour
690 cmb_filterOption.removeItemListener(this);
692 cmb_filterOption.removeAllItems();
695 List<FilterOption> filters = data
696 .getAvailableFilterOptions(VIEWS_FILTER);
697 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
698 lastDiscoveredStructuresSet);
700 for (FilterOption filter : filters)
702 if (lastSel != null && filter.equals(lastSel))
707 cmb_filterOption.addItem(filter);
711 cmb_filterOption.addItem(
712 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
713 "-", VIEWS_ENTER_ID, false, null));
714 cmb_filterOption.addItem(
715 new FilterOption(MessageManager.getString("label.from_file"),
716 "-", VIEWS_FROM_FILE, false, null));
717 if (canQueryTDB && notQueriedTDBYet)
719 btn_queryTDB.setVisible(true);
720 pnl_queryTDB.setVisible(true);
725 FilterOption cachedOption = new FilterOption(
726 MessageManager.getString("label.cached_structures"), "-",
727 VIEWS_LOCAL_PDB, false, null);
728 cmb_filterOption.addItem(cachedOption);
731 cmb_filterOption.setSelectedItem(cachedOption);
736 cmb_filterOption.setSelectedIndex(selSet);
738 cmb_filterOption.addItemListener(this);
742 * Updates the displayed view based on the selected filter option
744 protected void updateCurrentView()
746 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
749 if (lastSelected == selectedFilterOpt)
751 // don't need to do anything, probably
754 // otherwise, record selection
755 // and update the layout and dialog accordingly
756 lastSelected = selectedFilterOpt;
758 layout_switchableViews.show(pnl_switchableViews,
759 selectedFilterOpt.getView());
760 String filterTitle = mainFrame.getTitle();
761 mainFrame.setTitle(frameTitle);
762 chk_invertFilter.setVisible(false);
764 if (selectedFilterOpt.getView() == VIEWS_FILTER)
766 mainFrame.setTitle(filterTitle);
767 // TDB Query has no invert as yet
768 chk_invertFilter.setVisible(selectedFilterOpt
769 .getQuerySource() instanceof PDBStructureChooserQuerySource);
771 if (data != selectedFilterOpt.getQuerySource()
772 || data.needsRefetch(selectedFilterOpt))
774 data = selectedFilterOpt.getQuerySource();
775 // rebuild the views completely, since prefs will also change
781 filterResultSet(selectedFilterOpt.getValue());
784 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
785 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
787 mainFrame.setTitle(MessageManager
788 .getString("label.structure_chooser_manual_association"));
789 idInputAssSeqPanel.loadCmbAssSeq();
790 fileChooserAssSeqPanel.loadCmbAssSeq();
792 validateSelections();
796 * Validates user selection and enables the 'Add' and 'New View' buttons if
797 * all parameters are correct (the Add button will only be visible if there is
798 * at least one existing structure viewer open). This basically means at least
799 * one structure selected and no error messages.
801 * The 'Superpose Structures' option is enabled if either more than one
802 * structure is selected, or the 'Add' to existing view option is enabled, and
803 * disabled if the only option is to open a new view of a single structure.
806 protected void validateSelections()
808 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
810 btn_add.setEnabled(false);
811 String currentView = selectedFilterOpt.getView();
812 int selectedCount = 0;
813 if (currentView == VIEWS_FILTER)
815 selectedCount = getResultTable().getSelectedRows().length;
816 if (selectedCount > 0)
818 btn_add.setEnabled(true);
821 else if (currentView == VIEWS_LOCAL_PDB)
823 selectedCount = tbl_local_pdb.getSelectedRows().length;
824 if (selectedCount > 0)
826 btn_add.setEnabled(true);
829 else if (currentView == VIEWS_ENTER_ID)
831 validateAssociationEnterPdb();
833 else if (currentView == VIEWS_FROM_FILE)
835 validateAssociationFromFile();
838 btn_newView.setEnabled(btn_add.isEnabled());
841 * enable 'Superpose' option if more than one structure is selected,
842 * or there are view(s) available to add structure(s) to
845 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
849 protected boolean showPopupFor(int selectedRow, int x, int y)
851 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
853 String currentView = selectedFilterOpt.getView();
855 if (currentView == VIEWS_FILTER
856 && data instanceof ThreeDBStructureChooserQuerySource)
859 TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
860 .getFTSDataFor(getResultTable(), selectedRow,
861 discoveredStructuresSet);
862 String pageUrl = row.getModelViewUrl();
863 JPopupMenu popup = new JPopupMenu("3D Beacons");
864 JMenuItem viewUrl = new JMenuItem("View model web page");
865 viewUrl.addActionListener(new ActionListener()
868 public void actionPerformed(ActionEvent e)
870 Desktop.showUrl(pageUrl);
874 SwingUtilities.invokeLater(new Runnable()
879 popup.show(getResultTable(), x, y);
884 // event not handled by us
889 * Validates inputs from the Manual PDB entry panel
891 protected void validateAssociationEnterPdb()
893 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
894 .getCmb_assSeq().getSelectedItem();
895 lbl_pdbManualFetchStatus.setIcon(errorImage);
896 lbl_pdbManualFetchStatus.setToolTipText("");
897 if (txt_search.getText().length() > 0)
899 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
900 MessageManager.formatMessage("info.no_pdb_entry_found_for",
901 txt_search.getText())));
904 if (errorWarning.length() > 0)
906 lbl_pdbManualFetchStatus.setIcon(warningImage);
907 lbl_pdbManualFetchStatus.setToolTipText(
908 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
911 if (selectedSequences.length == 1 || !assSeqOpt.getName()
912 .equalsIgnoreCase("-Select Associated Seq-"))
914 txt_search.setEnabled(true);
917 btn_add.setEnabled(true);
918 lbl_pdbManualFetchStatus.setToolTipText("");
919 lbl_pdbManualFetchStatus.setIcon(goodImage);
924 txt_search.setEnabled(false);
925 lbl_pdbManualFetchStatus.setIcon(errorImage);
930 * Validates inputs for the manual PDB file selection options
932 protected void validateAssociationFromFile()
934 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
935 .getCmb_assSeq().getSelectedItem();
936 lbl_fromFileStatus.setIcon(errorImage);
937 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
938 .getName().equalsIgnoreCase("-Select Associated Seq-")))
940 btn_pdbFromFile.setEnabled(true);
941 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
943 btn_add.setEnabled(true);
944 lbl_fromFileStatus.setIcon(goodImage);
949 btn_pdbFromFile.setEnabled(false);
950 lbl_fromFileStatus.setIcon(errorImage);
955 protected void cmbAssSeqStateChanged()
957 validateSelections();
960 private FilterOption lastSelected = null;
963 * Handles the state change event for the 'filter' combo-box and 'invert'
967 protected void stateChanged(ItemEvent e)
969 if (e.getSource() instanceof JCheckBox)
975 if (e.getStateChange() == ItemEvent.SELECTED)
984 * select structures for viewing by their PDB IDs
987 * @return true if structures were found and marked as selected
989 public boolean selectStructure(String... pdbids)
991 boolean found = false;
993 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
995 String currentView = selectedFilterOpt.getView();
996 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
997 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
999 if (restable == null)
1001 // can't select (enter PDB ID, or load file - need to also select which
1002 // sequence to associate with)
1006 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
1007 for (int r = 0; r < restable.getRowCount(); r++)
1009 for (int p = 0; p < pdbids.length; p++)
1011 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1012 .equalsIgnoreCase(pdbids[p]))
1014 restable.setRowSelectionInterval(r, r);
1023 * Handles the 'New View' action
1026 protected void newView_ActionPerformed()
1028 targetView.setSelectedItem(null);
1029 showStructures(false);
1033 * Handles the 'Add to existing viewer' action
1036 protected void add_ActionPerformed()
1038 showStructures(false);
1042 * structure viewer opened by this dialog, or null
1044 private StructureViewer sViewer = null;
1046 public void showStructures(boolean waitUntilFinished)
1049 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1051 final int preferredHeight = pnl_filter.getHeight();
1053 Runnable viewStruc = new Runnable()
1058 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1059 .getSelectedItem());
1060 String currentView = selectedFilterOpt.getView();
1061 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1064 if (currentView == VIEWS_FILTER)
1066 int[] selectedRows = restable.getSelectedRows();
1067 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1068 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1069 pdbEntriesToView = data.collectSelectedRows(restable,
1070 selectedRows, selectedSeqsToView);
1072 SequenceI[] selectedSeqs = selectedSeqsToView
1073 .toArray(new SequenceI[selectedSeqsToView.size()]);
1074 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1077 else if (currentView == VIEWS_LOCAL_PDB)
1079 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1080 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1082 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1084 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1086 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1087 for (int row : selectedRows)
1089 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1090 .getModel()).getPDBEntryAt(row).getPdbEntry();
1092 pdbEntriesToView[count++] = pdbEntry;
1093 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1094 .getValueAt(row, refSeqColIndex);
1095 selectedSeqsToView.add(selectedSeq);
1097 SequenceI[] selectedSeqs = selectedSeqsToView
1098 .toArray(new SequenceI[selectedSeqsToView.size()]);
1099 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1102 else if (currentView == VIEWS_ENTER_ID)
1104 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1105 .getCmb_assSeq().getSelectedItem()).getSequence();
1106 if (userSelectedSeq != null)
1108 selectedSequence = userSelectedSeq;
1110 String pdbIdStr = txt_search.getText();
1111 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1112 if (pdbEntry == null)
1114 pdbEntry = new PDBEntry();
1115 if (pdbIdStr.split(":").length > 1)
1117 pdbEntry.setId(pdbIdStr.split(":")[0]);
1118 pdbEntry.setChainCode(
1119 pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1123 pdbEntry.setId(pdbIdStr);
1125 pdbEntry.setType(PDBEntry.Type.PDB);
1126 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1129 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1130 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1132 { selectedSequence });
1134 else if (currentView == VIEWS_FROM_FILE)
1136 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1137 .getCmb_assSeq().getSelectedItem()).getSequence();
1138 if (userSelectedSeq != null)
1140 selectedSequence = userSelectedSeq;
1142 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1143 .associatePdbWithSeq(selectedPdbFileName,
1144 DataSourceType.FILE, selectedSequence, true,
1147 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1149 { selectedSequence });
1151 SwingUtilities.invokeLater(new Runnable()
1156 closeAction(preferredHeight);
1157 mainFrame.dispose();
1162 Thread runner = new Thread(viewStruc);
1164 if (waitUntilFinished)
1166 while (sViewer == null ? runner.isAlive()
1167 : (sViewer.sview == null ? true
1168 : !sViewer.sview.hasMapping()))
1173 } catch (InterruptedException ie)
1182 * Answers a structure viewer (new or existing) configured to superimpose
1183 * added structures or not according to the user's choice
1188 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1190 Object sv = targetView.getSelectedItem();
1192 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1196 * Adds PDB structures to a new or existing structure viewer
1199 * @param pdbEntriesToView
1204 private StructureViewer launchStructureViewer(
1205 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1206 final AlignmentPanel alignPanel, SequenceI[] sequences)
1208 long progressId = sequences.hashCode();
1209 setProgressBar(MessageManager
1210 .getString("status.launching_3d_structure_viewer"), progressId);
1211 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1212 boolean superimpose = chk_superpose.isSelected();
1213 theViewer.setSuperpose(superimpose);
1216 * remember user's choice of superimpose or not
1218 Cache.setProperty(AUTOSUPERIMPOSE,
1219 Boolean.valueOf(superimpose).toString());
1221 setProgressBar(null, progressId);
1222 if (SiftsSettings.isMapWithSifts())
1224 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1226 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1227 // real PDB ID. For moment, we can also safely do this if there is already
1228 // a known mapping between the PDBEntry and the sequence.
1229 for (SequenceI seq : sequences)
1231 PDBEntry pdbe = pdbEntriesToView[p++];
1232 if (pdbe != null && pdbe.getFile() != null)
1234 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1235 if (smm != null && smm.length > 0)
1237 for (StructureMapping sm : smm)
1239 if (sm.getSequence() == seq)
1246 if (seq.getPrimaryDBRefs().isEmpty())
1248 seqsWithoutSourceDBRef.add(seq);
1252 if (!seqsWithoutSourceDBRef.isEmpty())
1254 int y = seqsWithoutSourceDBRef.size();
1255 setProgressBar(MessageManager.formatMessage(
1256 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1258 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1259 .toArray(new SequenceI[y]);
1260 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1261 dbRefFetcher.fetchDBRefs(true);
1263 setProgressBar("Fetch complete.", progressId); // todo i18n
1266 if (pdbEntriesToView.length > 1)
1269 MessageManager.getString(
1270 "status.fetching_3d_structures_for_selected_entries"),
1272 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1276 setProgressBar(MessageManager.formatMessage(
1277 "status.fetching_3d_structures_for",
1278 pdbEntriesToView[0].getId()), progressId);
1279 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1281 setProgressBar(null, progressId);
1282 // remember the last viewer we used...
1283 lastTargetedView = theViewer;
1288 * Populates the combo-box used in associating manually fetched structures to
1289 * a unique sequence when more than one sequence selection is made.
1292 protected void populateCmbAssociateSeqOptions(
1293 JComboBox<AssociateSeqOptions> cmb_assSeq,
1294 JLabel lbl_associateSeq)
1296 cmb_assSeq.removeAllItems();
1298 new AssociateSeqOptions("-Select Associated Seq-", null));
1299 lbl_associateSeq.setVisible(false);
1300 if (selectedSequences.length > 1)
1302 for (SequenceI seq : selectedSequences)
1304 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1309 String seqName = selectedSequence.getDisplayId(false);
1310 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1311 lbl_associateSeq.setText(seqName);
1312 lbl_associateSeq.setVisible(true);
1313 cmb_assSeq.setVisible(false);
1317 protected boolean isStructuresDiscovered()
1319 return discoveredStructuresSet != null
1320 && !discoveredStructuresSet.isEmpty();
1323 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1325 // Doing a search for "1" or "1c" is valuable?
1326 // Those work but are enormously slow.
1329 protected void txt_search_ActionPerformed()
1331 String text = txt_search.getText().trim();
1332 if (text.length() >= PDB_ID_MIN)
1339 errorWarning.setLength(0);
1340 isValidPBDEntry = false;
1341 if (text.length() > 0)
1343 // TODO move this pdb id search into the PDB specific
1345 // for moment, it will work fine as is because it is self-contained
1346 String searchTerm = text.toLowerCase(Locale.ROOT);
1347 searchTerm = searchTerm.split(":")[0];
1348 // System.out.println(">>>>> search term : " + searchTerm);
1349 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1350 FTSRestRequest pdbRequest = new FTSRestRequest();
1351 pdbRequest.setAllowEmptySeq(false);
1352 pdbRequest.setResponseSize(1);
1353 pdbRequest.setFieldToSearchBy("(pdb_id:");
1354 pdbRequest.setWantedFields(wantedFields);
1355 pdbRequest.setSearchTerm(searchTerm + ")");
1356 pdbRequest.setAssociatedSequence(selectedSequence);
1357 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1358 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1359 FTSRestResponse resultList;
1362 resultList = pdbRestClient.executeRequest(pdbRequest);
1363 } catch (Exception e)
1365 errorWarning.append(e.getMessage());
1369 validateSelections();
1371 if (resultList.getSearchSummary() != null
1372 && resultList.getSearchSummary().size() > 0)
1374 isValidPBDEntry = true;
1377 validateSelections();
1383 protected void tabRefresh()
1385 if (selectedSequences != null)
1387 Thread refreshThread = new Thread(new Runnable()
1392 fetchStructuresMetaData();
1393 // populateFilterComboBox(true, cachedPDBExists);
1396 ((FilterOption) cmb_filterOption.getSelectedItem())
1400 refreshThread.start();
1404 public class PDBEntryTableModel extends AbstractTableModel
1406 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1409 private List<CachedPDB> pdbEntries;
1411 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1413 this.pdbEntries = new ArrayList<>(pdbEntries);
1417 public String getColumnName(int columnIndex)
1419 return columns[columnIndex];
1423 public int getRowCount()
1425 return pdbEntries.size();
1429 public int getColumnCount()
1431 return columns.length;
1435 public boolean isCellEditable(int row, int column)
1441 public Object getValueAt(int rowIndex, int columnIndex)
1443 Object value = "??";
1444 CachedPDB entry = pdbEntries.get(rowIndex);
1445 switch (columnIndex)
1448 value = entry.getSequence();
1451 value = entry.getQualifiedId();
1454 value = entry.getPdbEntry().getChainCode() == null ? "_"
1455 : entry.getPdbEntry().getChainCode();
1458 value = entry.getPdbEntry().getType();
1461 value = entry.getPdbEntry().getFile();
1468 public Class<?> getColumnClass(int columnIndex)
1470 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1473 public CachedPDB getPDBEntryAt(int row)
1475 return pdbEntries.get(row);
1480 private class CachedPDB
1482 private SequenceI sequence;
1484 private PDBEntry pdbEntry;
1486 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1488 this.sequence = sequence;
1489 this.pdbEntry = pdbEntry;
1492 public String getQualifiedId()
1494 if (pdbEntry.hasProvider())
1496 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1498 return pdbEntry.toString();
1501 public SequenceI getSequence()
1506 public PDBEntry getPdbEntry()
1513 private IProgressIndicator progressBar;
1516 public void setProgressBar(String message, long id)
1518 progressBar.setProgressBar(message, id);
1522 public void registerHandler(long id, IProgressIndicatorHandler handler)
1524 progressBar.registerHandler(id, handler);
1528 public boolean operationInProgress()
1530 return progressBar.operationInProgress();
1533 public JalviewStructureDisplayI getOpenedStructureViewer()
1535 return sViewer == null ? null : sViewer.sview;
1539 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1541 data.setDocFieldPrefs(newPrefs);
1547 * @return true when all initialisation threads have finished and dialog is
1550 public boolean isDialogVisible()
1552 return mainFrame != null && data != null && cmb_filterOption != null
1553 && mainFrame.isVisible()
1554 && cmb_filterOption.getSelectedItem() != null;
1559 * @return true if the 3D-Beacons query button will/has been displayed
1561 public boolean isCanQueryTDB()
1566 public boolean isNotQueriedTDBYet()
1568 return notQueriedTDBYet;