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.JMenu;
39 import javax.swing.JMenuItem;
40 import javax.swing.JPopupMenu;
41 import javax.swing.JTable;
42 import javax.swing.SwingUtilities;
43 import javax.swing.table.AbstractTableModel;
45 import jalview.api.structures.JalviewStructureDisplayI;
46 import jalview.bin.Cache;
47 import jalview.bin.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";
84 private SequenceI selectedSequence;
86 private SequenceI[] selectedSequences;
88 private IProgressIndicator progressIndicator;
90 private Collection<FTSData> discoveredStructuresSet;
92 private StructureChooserQuerySource data;
95 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
97 return data.getDocFieldPrefs();
100 private String selectedPdbFileName;
102 private boolean isValidPBDEntry;
104 private boolean cachedPDBExists;
106 private Collection<FTSData> lastDiscoveredStructuresSet;
108 private boolean canQueryTDB = false;
110 private boolean notQueriedTDBYet = true;
112 List<SequenceI> seqsWithoutSourceDBRef = null;
114 private static StructureViewer lastTargetedView = null;
116 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
119 // which FTS engine to use
120 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
124 this.selectedSequence = selectedSeq;
125 this.selectedSequences = selectedSeqs;
126 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
132 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
133 * least one structure are discovered.
135 private void populateSeqsWithoutSourceDBRef()
137 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
138 boolean needCanonical = false;
139 for (SequenceI seq : selectedSequences)
143 int dbRef = ThreeDBStructureChooserQuerySource
144 .checkUniprotRefs(seq.getDBRefs());
149 // need to retrieve canonicals
150 needCanonical = true;
151 seqsWithoutSourceDBRef.add(seq);
155 // could be a sequence with pdb ref
156 if (seq.getAllPDBEntries() == null
157 || seq.getAllPDBEntries().size() == 0)
159 seqsWithoutSourceDBRef.add(seq);
165 // retrieve database refs for protein sequences
166 if (!seqsWithoutSourceDBRef.isEmpty())
171 // triggers display of the 'Query TDB' button
172 notQueriedTDBYet = true;
178 * Initializes parameters used by the Structure Chooser Panel
180 protected void init()
182 if (!Jalview.isHeadlessMode())
184 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
187 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
188 btn_queryTDB.addActionListener(new ActionListener()
192 public void actionPerformed(ActionEvent e)
194 promptForTDBFetch(false);
198 Executors.defaultThreadFactory().newThread(new Runnable()
202 populateSeqsWithoutSourceDBRef();
203 initialStructureDiscovery();
211 private void initialStructureDiscovery()
213 // check which FTS engine to use
214 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
216 // ensure a filter option is in force for search
217 populateFilterComboBox(true, cachedPDBExists);
219 // looks for any existing structures already loaded
220 // for the sequences (the cached ones)
221 // then queries the StructureChooserQuerySource to
222 // discover more structures.
224 // Possible optimisation is to only begin querying
225 // the structure chooser if there are no cached structures.
227 long startTime = System.currentTimeMillis();
228 updateProgressIndicator(
229 MessageManager.getString("status.loading_cached_pdb_entries"),
231 loadLocalCachedPDBEntries();
232 updateProgressIndicator(null, startTime);
233 updateProgressIndicator(
234 MessageManager.getString("status.searching_for_pdb_structures"),
236 fetchStructuresMetaData();
237 // revise filter options if no results were found
238 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
239 discoverStructureViews();
240 updateProgressIndicator(null, startTime);
241 mainFrame.setVisible(true);
246 * raises dialog for Uniprot fetch followed by 3D beacons search
249 * - when true, don't ask, just fetch
251 public void promptForTDBFetch(boolean ignoreGui)
253 final long progressId = System.currentTimeMillis();
255 // final action after prompting and discovering db refs
256 final Runnable strucDiscovery = new Runnable()
261 mainFrame.setEnabled(false);
262 cmb_filterOption.setEnabled(false);
263 progressBar.setProgressBar(
264 MessageManager.getString("status.searching_3d_beacons"),
266 btn_queryTDB.setEnabled(false);
267 // TODO: warn if no accessions discovered
268 populateSeqsWithoutSourceDBRef();
269 // redo initial discovery - this time with 3d beacons
271 previousWantedFields = null;
272 lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
273 cmb_filterOption.setSelectedItem(null);
274 cachedPDBExists = false; // reset to initial
275 initialStructureDiscovery();
276 if (!isStructuresDiscovered())
278 progressBar.setProgressBar(MessageManager.getString(
279 "status.no_structures_discovered_from_3d_beacons"),
281 btn_queryTDB.setToolTipText(MessageManager.getString(
282 "status.no_structures_discovered_from_3d_beacons"));
283 btn_queryTDB.setEnabled(false);
284 pnl_queryTDB.setVisible(false);
288 cmb_filterOption.setSelectedIndex(0); // select 'best'
289 btn_queryTDB.setVisible(false);
290 pnl_queryTDB.setVisible(false);
291 progressBar.setProgressBar(null, progressId);
293 mainFrame.setEnabled(true);
294 cmb_filterOption.setEnabled(true);
298 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
302 public void finished()
304 // filter has been selected, so we set flag to remove ourselves
305 notQueriedTDBYet = false;
306 // new thread to discover structures - via 3d beacons
307 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
312 // fetch db refs if OK pressed
313 final Runnable discoverCanonicalDBrefs = new Runnable()
318 populateSeqsWithoutSourceDBRef();
320 final int y = seqsWithoutSourceDBRef.size();
323 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
324 .toArray(new SequenceI[y]);
325 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
326 progressBar, new DbSourceProxy[]
327 { new jalview.ws.dbsources.Uniprot() }, null, false);
328 dbRefFetcher.addListener(afterDbRefFetch);
329 // ideally this would also gracefully run with callbacks
330 dbRefFetcher.fetchDBRefs(true);
334 // call finished action directly
335 afterDbRefFetch.finished();
340 final Runnable revertview = new Runnable()
344 if (lastSelected != null)
346 cmb_filterOption.setSelectedItem(lastSelected);
352 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs)
356 // need cancel and no to result in the discoverPDB action - mocked is
357 // 'cancel' TODO: mock should be OK
358 JvOptionPane.newOptionDialog(this)
359 .setResponseHandler(JvOptionPane.OK_OPTION,
360 discoverCanonicalDBrefs)
361 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
362 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
364 MessageManager.formatMessage(
365 "label.fetch_references_for_3dbeacons",
366 seqsWithoutSourceDBRef.size()),
367 MessageManager.getString("label.3dbeacons"),
368 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
370 { MessageManager.getString("action.ok"),
371 MessageManager.getString("action.cancel") },
372 MessageManager.getString("action.ok"));
376 * Builds a drop-down choice list of existing structure viewers to which new
377 * structures may be added. If this list is empty then it, and the 'Add'
378 * button, are hidden.
380 private void discoverStructureViews()
382 if (Desktop.instance != null)
384 targetView.removeAllItems();
385 if (lastTargetedView != null && !lastTargetedView.isVisible())
387 lastTargetedView = null;
389 int linkedViewsAt = 0;
390 for (StructureViewerBase view : Desktop.instance
391 .getStructureViewers(null, null))
393 StructureViewer viewHandler = (lastTargetedView != null
394 && lastTargetedView.sview == view) ? lastTargetedView
395 : StructureViewer.reconfigure(view);
397 if (view.isLinkedWith(ap))
399 targetView.insertItemAt(viewHandler, linkedViewsAt++);
403 targetView.addItem(viewHandler);
408 * show option to Add to viewer if at least 1 viewer found
410 targetView.setVisible(false);
411 if (targetView.getItemCount() > 0)
413 targetView.setVisible(true);
414 if (lastTargetedView != null)
416 targetView.setSelectedItem(lastTargetedView);
420 targetView.setSelectedIndex(0);
423 btn_add.setVisible(targetView.isVisible());
428 * Updates the progress indicator with the specified message
431 * displayed message for the operation
433 * unique handle for this indicator
435 protected void updateProgressIndicator(String message, long id)
437 if (progressIndicator != null)
439 progressIndicator.setProgressBar(message, id);
444 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
447 void fetchStructuresMetaData()
449 long startTime = System.currentTimeMillis();
450 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
451 .getStructureSummaryFields();
453 discoveredStructuresSet = new LinkedHashSet<>();
454 HashSet<String> errors = new HashSet<>();
456 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
459 for (SequenceI seq : selectedSequences)
462 FTSRestResponse resultList;
465 resultList = data.fetchStructuresMetaData(seq, wantedFields,
466 selectedFilterOpt, !chk_invertFilter.isSelected());
467 // null response means the FTSengine didn't yield a query for this
468 // consider designing a special exception if we really wanted to be
470 if (resultList == null)
474 } catch (Exception e)
477 errors.add(e.getMessage());
480 if (resultList.getSearchSummary() != null
481 && !resultList.getSearchSummary().isEmpty())
483 discoveredStructuresSet.addAll(resultList.getSearchSummary());
487 int noOfStructuresFound = 0;
488 String totalTime = (System.currentTimeMillis() - startTime)
490 if (discoveredStructuresSet != null
491 && !discoveredStructuresSet.isEmpty())
494 .setModel(data.getTableModel(discoveredStructuresSet));
496 noOfStructuresFound = discoveredStructuresSet.size();
497 lastDiscoveredStructuresSet = discoveredStructuresSet;
498 mainFrame.setTitle(MessageManager.formatMessage(
499 "label.structure_chooser_no_of_structures",
500 noOfStructuresFound, totalTime));
504 mainFrame.setTitle(MessageManager
505 .getString("label.structure_chooser_manual_association"));
506 if (errors.size() > 0)
508 StringBuilder errorMsg = new StringBuilder();
509 for (String error : errors)
511 errorMsg.append(error).append("\n");
513 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
514 MessageManager.getString("label.pdb_web-service_error"),
515 JvOptionPane.ERROR_MESSAGE);
520 protected void loadLocalCachedPDBEntries()
522 ArrayList<CachedPDB> entries = new ArrayList<>();
523 for (SequenceI seq : selectedSequences)
525 if (seq.getDatasetSequence() != null
526 && seq.getDatasetSequence().getAllPDBEntries() != null)
528 for (PDBEntry pdbEntry : seq.getDatasetSequence()
531 if (pdbEntry.getFile() != null)
533 entries.add(new CachedPDB(seq, pdbEntry));
538 cachedPDBExists = !entries.isEmpty();
539 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
540 tbl_local_pdb.setModel(tableModelx);
544 * Filters a given list of discovered structures based on supplied argument
546 * @param fieldToFilterBy
547 * the field to filter by
549 void filterResultSet(final String fieldToFilterBy)
551 Thread filterThread = new Thread(new Runnable()
557 long startTime = System.currentTimeMillis();
558 lbl_loading.setVisible(true);
559 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
560 .getStructureSummaryFields();
561 Collection<FTSData> filteredResponse = new HashSet<>();
562 HashSet<String> errors = new HashSet<>();
564 for (SequenceI seq : selectedSequences)
567 FTSRestResponse resultList;
570 resultList = data.selectFirstRankedQuery(seq,
571 discoveredStructuresSet, wantedFields, fieldToFilterBy,
572 !chk_invertFilter.isSelected());
574 } catch (Exception e)
577 errors.add(e.getMessage());
580 if (resultList.getSearchSummary() != null
581 && !resultList.getSearchSummary().isEmpty())
583 filteredResponse.addAll(resultList.getSearchSummary());
587 String totalTime = (System.currentTimeMillis() - startTime)
589 if (!filteredResponse.isEmpty())
591 final int filterResponseCount = filteredResponse.size();
592 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
593 reorderedStructuresSet.addAll(filteredResponse);
594 reorderedStructuresSet.addAll(discoveredStructuresSet);
596 .setModel(data.getTableModel(reorderedStructuresSet));
598 FTSRestResponse.configureTableColumn(getResultTable(),
599 wantedFields, tempUserPrefs);
600 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
601 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
602 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
603 // Update table selection model here
604 getResultTable().addRowSelectionInterval(0,
605 filterResponseCount - 1);
606 mainFrame.setTitle(MessageManager.formatMessage(
607 "label.structure_chooser_filter_time", totalTime));
611 mainFrame.setTitle(MessageManager.formatMessage(
612 "label.structure_chooser_filter_time", totalTime));
613 if (errors.size() > 0)
615 StringBuilder errorMsg = new StringBuilder();
616 for (String error : errors)
618 errorMsg.append(error).append("\n");
620 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
621 MessageManager.getString("label.pdb_web-service_error"),
622 JvOptionPane.ERROR_MESSAGE);
626 lbl_loading.setVisible(false);
628 validateSelections();
631 filterThread.start();
635 * Handles action event for btn_pdbFromFile
638 protected void pdbFromFile_actionPerformed()
640 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
643 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
644 Cache.getProperty("LAST_DIRECTORY"));
645 chooser.setFileView(new jalview.io.JalviewFileView());
646 chooser.setDialogTitle(
647 MessageManager.formatMessage("label.select_pdb_file_for",
648 selectedSequence.getDisplayId(false)));
649 chooser.setToolTipText(MessageManager.formatMessage(
650 "label.load_pdb_file_associate_with_sequence",
651 selectedSequence.getDisplayId(false)));
653 int value = chooser.showOpenDialog(null);
654 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
656 selectedPdbFileName = chooser.getSelectedFile().getPath();
657 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
658 validateSelections();
663 * Populates the filter combo-box options dynamically depending on discovered
666 protected void populateFilterComboBox(boolean haveData,
667 boolean cachedPDBExist)
669 populateFilterComboBox(haveData, cachedPDBExist, null);
673 * Populates the filter combo-box options dynamically depending on discovered
676 protected void populateFilterComboBox(boolean haveData,
677 boolean cachedPDBExist, FilterOption lastSel)
681 * temporarily suspend the change listener behaviour
683 cmb_filterOption.removeItemListener(this);
685 cmb_filterOption.removeAllItems();
688 List<FilterOption> filters = data
689 .getAvailableFilterOptions(VIEWS_FILTER);
690 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
691 lastDiscoveredStructuresSet);
693 for (FilterOption filter : filters)
695 if (lastSel != null && filter.equals(lastSel))
700 cmb_filterOption.addItem(filter);
704 cmb_filterOption.addItem(
705 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
706 "-", VIEWS_ENTER_ID, false, null));
707 cmb_filterOption.addItem(
708 new FilterOption(MessageManager.getString("label.from_file"),
709 "-", VIEWS_FROM_FILE, false, null));
710 if (canQueryTDB && notQueriedTDBYet)
712 btn_queryTDB.setVisible(true);
713 pnl_queryTDB.setVisible(true);
718 FilterOption cachedOption = new FilterOption(
719 MessageManager.getString("label.cached_structures"), "-",
720 VIEWS_LOCAL_PDB, false, null);
721 cmb_filterOption.addItem(cachedOption);
724 cmb_filterOption.setSelectedItem(cachedOption);
729 cmb_filterOption.setSelectedIndex(selSet);
731 cmb_filterOption.addItemListener(this);
735 * Updates the displayed view based on the selected filter option
737 protected void updateCurrentView()
739 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
742 if (lastSelected == selectedFilterOpt)
744 // don't need to do anything, probably
747 // otherwise, record selection
748 // and update the layout and dialog accordingly
749 lastSelected = selectedFilterOpt;
751 layout_switchableViews.show(pnl_switchableViews,
752 selectedFilterOpt.getView());
753 String filterTitle = mainFrame.getTitle();
754 mainFrame.setTitle(frameTitle);
755 chk_invertFilter.setVisible(false);
757 if (selectedFilterOpt.getView() == VIEWS_FILTER)
759 mainFrame.setTitle(filterTitle);
760 // TDB Query has no invert as yet
761 chk_invertFilter.setVisible(selectedFilterOpt
762 .getQuerySource() instanceof PDBStructureChooserQuerySource);
764 if (data != selectedFilterOpt.getQuerySource()
765 || data.needsRefetch(selectedFilterOpt))
767 data = selectedFilterOpt.getQuerySource();
768 // rebuild the views completely, since prefs will also change
774 filterResultSet(selectedFilterOpt.getValue());
777 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
778 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
780 mainFrame.setTitle(MessageManager
781 .getString("label.structure_chooser_manual_association"));
782 idInputAssSeqPanel.loadCmbAssSeq();
783 fileChooserAssSeqPanel.loadCmbAssSeq();
785 validateSelections();
789 * Validates user selection and enables the 'Add' and 'New View' buttons if
790 * all parameters are correct (the Add button will only be visible if there is
791 * at least one existing structure viewer open). This basically means at least
792 * one structure selected and no error messages.
794 * The 'Superpose Structures' option is enabled if either more than one
795 * structure is selected, or the 'Add' to existing view option is enabled, and
796 * disabled if the only option is to open a new view of a single structure.
799 protected void validateSelections()
801 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
803 btn_add.setEnabled(false);
804 String currentView = selectedFilterOpt.getView();
805 int selectedCount = 0;
806 if (currentView == VIEWS_FILTER)
808 selectedCount = getResultTable().getSelectedRows().length;
809 if (selectedCount > 0)
811 btn_add.setEnabled(true);
814 else if (currentView == VIEWS_LOCAL_PDB)
816 selectedCount = tbl_local_pdb.getSelectedRows().length;
817 if (selectedCount > 0)
819 btn_add.setEnabled(true);
822 else if (currentView == VIEWS_ENTER_ID)
824 validateAssociationEnterPdb();
826 else if (currentView == VIEWS_FROM_FILE)
828 validateAssociationFromFile();
831 btn_newView.setEnabled(btn_add.isEnabled());
834 * enable 'Superpose' option if more than one structure is selected,
835 * or there are view(s) available to add structure(s) to
838 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
842 protected boolean showPopupFor(int selectedRow, int x, int y)
844 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
846 String currentView = selectedFilterOpt.getView();
848 if (currentView == VIEWS_FILTER
849 && data instanceof ThreeDBStructureChooserQuerySource)
852 TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
853 .getFTSDataFor(getResultTable(), selectedRow,
854 discoveredStructuresSet);
855 String pageUrl = row.getModelViewUrl();
856 JPopupMenu popup = new JPopupMenu("3D Beacons");
857 JMenuItem viewUrl = new JMenuItem("View model web page");
858 viewUrl.addActionListener(new ActionListener()
861 public void actionPerformed(ActionEvent e)
863 Desktop.showUrl(pageUrl);
867 SwingUtilities.invokeLater(new Runnable()
871 popup.show(getResultTable(), x, y);
876 // event not handled by us
881 * Validates inputs from the Manual PDB entry panel
883 protected void validateAssociationEnterPdb()
885 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
886 .getCmb_assSeq().getSelectedItem();
887 lbl_pdbManualFetchStatus.setIcon(errorImage);
888 lbl_pdbManualFetchStatus.setToolTipText("");
889 if (txt_search.getText().length() > 0)
891 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
892 MessageManager.formatMessage("info.no_pdb_entry_found_for",
893 txt_search.getText())));
896 if (errorWarning.length() > 0)
898 lbl_pdbManualFetchStatus.setIcon(warningImage);
899 lbl_pdbManualFetchStatus.setToolTipText(
900 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
903 if (selectedSequences.length == 1 || !assSeqOpt.getName()
904 .equalsIgnoreCase("-Select Associated Seq-"))
906 txt_search.setEnabled(true);
909 btn_add.setEnabled(true);
910 lbl_pdbManualFetchStatus.setToolTipText("");
911 lbl_pdbManualFetchStatus.setIcon(goodImage);
916 txt_search.setEnabled(false);
917 lbl_pdbManualFetchStatus.setIcon(errorImage);
922 * Validates inputs for the manual PDB file selection options
924 protected void validateAssociationFromFile()
926 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
927 .getCmb_assSeq().getSelectedItem();
928 lbl_fromFileStatus.setIcon(errorImage);
929 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
930 .getName().equalsIgnoreCase("-Select Associated Seq-")))
932 btn_pdbFromFile.setEnabled(true);
933 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
935 btn_add.setEnabled(true);
936 lbl_fromFileStatus.setIcon(goodImage);
941 btn_pdbFromFile.setEnabled(false);
942 lbl_fromFileStatus.setIcon(errorImage);
947 protected void cmbAssSeqStateChanged()
949 validateSelections();
952 private FilterOption lastSelected = null;
955 * Handles the state change event for the 'filter' combo-box and 'invert'
959 protected void stateChanged(ItemEvent e)
961 if (e.getSource() instanceof JCheckBox)
967 if (e.getStateChange() == ItemEvent.SELECTED)
976 * select structures for viewing by their PDB IDs
979 * @return true if structures were found and marked as selected
981 public boolean selectStructure(String... pdbids)
983 boolean found = false;
985 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
987 String currentView = selectedFilterOpt.getView();
988 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
989 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
991 if (restable == null)
993 // can't select (enter PDB ID, or load file - need to also select which
994 // sequence to associate with)
998 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
999 for (int r = 0; r < restable.getRowCount(); r++)
1001 for (int p = 0; p < pdbids.length; p++)
1003 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1004 .equalsIgnoreCase(pdbids[p]))
1006 restable.setRowSelectionInterval(r, r);
1015 * Handles the 'New View' action
1018 protected void newView_ActionPerformed()
1020 targetView.setSelectedItem(null);
1021 showStructures(false);
1025 * Handles the 'Add to existing viewer' action
1028 protected void add_ActionPerformed()
1030 showStructures(false);
1034 * structure viewer opened by this dialog, or null
1036 private StructureViewer sViewer = null;
1038 public void showStructures(boolean waitUntilFinished)
1041 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1043 final int preferredHeight = pnl_filter.getHeight();
1045 Runnable viewStruc = new Runnable()
1050 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1051 .getSelectedItem());
1052 String currentView = selectedFilterOpt.getView();
1053 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1056 if (currentView == VIEWS_FILTER)
1058 int[] selectedRows = restable.getSelectedRows();
1059 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1060 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1061 pdbEntriesToView = data.collectSelectedRows(restable,
1062 selectedRows, selectedSeqsToView);
1064 SequenceI[] selectedSeqs = selectedSeqsToView
1065 .toArray(new SequenceI[selectedSeqsToView.size()]);
1066 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1069 else if (currentView == VIEWS_LOCAL_PDB)
1071 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1072 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1074 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1076 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1078 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1079 for (int row : selectedRows)
1081 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1082 .getModel()).getPDBEntryAt(row).getPdbEntry();
1084 pdbEntriesToView[count++] = pdbEntry;
1085 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1086 .getValueAt(row, refSeqColIndex);
1087 selectedSeqsToView.add(selectedSeq);
1089 SequenceI[] selectedSeqs = selectedSeqsToView
1090 .toArray(new SequenceI[selectedSeqsToView.size()]);
1091 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1094 else if (currentView == VIEWS_ENTER_ID)
1096 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1097 .getCmb_assSeq().getSelectedItem()).getSequence();
1098 if (userSelectedSeq != null)
1100 selectedSequence = userSelectedSeq;
1102 String pdbIdStr = txt_search.getText();
1103 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1104 if (pdbEntry == null)
1106 pdbEntry = new PDBEntry();
1107 if (pdbIdStr.split(":").length > 1)
1109 pdbEntry.setId(pdbIdStr.split(":")[0]);
1110 pdbEntry.setChainCode(
1111 pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1115 pdbEntry.setId(pdbIdStr);
1117 pdbEntry.setType(PDBEntry.Type.PDB);
1118 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1121 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1122 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1124 { selectedSequence });
1126 else if (currentView == VIEWS_FROM_FILE)
1128 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1129 .getCmb_assSeq().getSelectedItem()).getSequence();
1130 if (userSelectedSeq != null)
1132 selectedSequence = userSelectedSeq;
1134 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1135 .associatePdbWithSeq(selectedPdbFileName,
1136 DataSourceType.FILE, selectedSequence, true,
1139 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1141 { selectedSequence });
1143 SwingUtilities.invokeLater(new Runnable()
1148 closeAction(preferredHeight);
1149 mainFrame.dispose();
1154 Thread runner = new Thread(viewStruc);
1156 if (waitUntilFinished)
1158 while (sViewer == null ? runner.isAlive()
1159 : (sViewer.sview == null ? true
1160 : !sViewer.sview.hasMapping()))
1165 } catch (InterruptedException ie)
1174 * Answers a structure viewer (new or existing) configured to superimpose
1175 * added structures or not according to the user's choice
1180 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1182 Object sv = targetView.getSelectedItem();
1184 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1188 * Adds PDB structures to a new or existing structure viewer
1191 * @param pdbEntriesToView
1196 private StructureViewer launchStructureViewer(
1197 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1198 final AlignmentPanel alignPanel, SequenceI[] sequences)
1200 long progressId = sequences.hashCode();
1201 setProgressBar(MessageManager
1202 .getString("status.launching_3d_structure_viewer"), progressId);
1203 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1204 boolean superimpose = chk_superpose.isSelected();
1205 theViewer.setSuperpose(superimpose);
1208 * remember user's choice of superimpose or not
1210 Cache.setProperty(AUTOSUPERIMPOSE,
1211 Boolean.valueOf(superimpose).toString());
1213 setProgressBar(null, progressId);
1214 if (SiftsSettings.isMapWithSifts())
1216 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1218 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1219 // real PDB ID. For moment, we can also safely do this if there is already
1220 // a known mapping between the PDBEntry and the sequence.
1221 for (SequenceI seq : sequences)
1223 PDBEntry pdbe = pdbEntriesToView[p++];
1224 if (pdbe != null && pdbe.getFile() != null)
1226 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1227 if (smm != null && smm.length > 0)
1229 for (StructureMapping sm : smm)
1231 if (sm.getSequence() == seq)
1238 if (seq.getPrimaryDBRefs().isEmpty())
1240 seqsWithoutSourceDBRef.add(seq);
1244 if (!seqsWithoutSourceDBRef.isEmpty())
1246 int y = seqsWithoutSourceDBRef.size();
1247 setProgressBar(MessageManager.formatMessage(
1248 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1250 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1251 .toArray(new SequenceI[y]);
1252 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1253 dbRefFetcher.fetchDBRefs(true);
1255 setProgressBar("Fetch complete.", progressId); // todo i18n
1258 if (pdbEntriesToView.length > 1)
1261 MessageManager.getString(
1262 "status.fetching_3d_structures_for_selected_entries"),
1264 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1268 setProgressBar(MessageManager.formatMessage(
1269 "status.fetching_3d_structures_for",
1270 pdbEntriesToView[0].getId()), progressId);
1271 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1273 setProgressBar(null, progressId);
1274 // remember the last viewer we used...
1275 lastTargetedView = theViewer;
1280 * Populates the combo-box used in associating manually fetched structures to
1281 * a unique sequence when more than one sequence selection is made.
1284 protected void populateCmbAssociateSeqOptions(
1285 JComboBox<AssociateSeqOptions> cmb_assSeq,
1286 JLabel lbl_associateSeq)
1288 cmb_assSeq.removeAllItems();
1290 new AssociateSeqOptions("-Select Associated Seq-", null));
1291 lbl_associateSeq.setVisible(false);
1292 if (selectedSequences.length > 1)
1294 for (SequenceI seq : selectedSequences)
1296 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1301 String seqName = selectedSequence.getDisplayId(false);
1302 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1303 lbl_associateSeq.setText(seqName);
1304 lbl_associateSeq.setVisible(true);
1305 cmb_assSeq.setVisible(false);
1309 protected boolean isStructuresDiscovered()
1311 return discoveredStructuresSet != null
1312 && !discoveredStructuresSet.isEmpty();
1315 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1317 // Doing a search for "1" or "1c" is valuable?
1318 // Those work but are enormously slow.
1321 protected void txt_search_ActionPerformed()
1323 String text = txt_search.getText().trim();
1324 if (text.length() >= PDB_ID_MIN)
1331 errorWarning.setLength(0);
1332 isValidPBDEntry = false;
1333 if (text.length() > 0)
1335 // TODO move this pdb id search into the PDB specific
1337 // for moment, it will work fine as is because it is self-contained
1338 String searchTerm = text.toLowerCase(Locale.ROOT);
1339 searchTerm = searchTerm.split(":")[0];
1340 // System.out.println(">>>>> search term : " + searchTerm);
1341 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1342 FTSRestRequest pdbRequest = new FTSRestRequest();
1343 pdbRequest.setAllowEmptySeq(false);
1344 pdbRequest.setResponseSize(1);
1345 pdbRequest.setFieldToSearchBy("(pdb_id:");
1346 pdbRequest.setWantedFields(wantedFields);
1347 pdbRequest.setSearchTerm(searchTerm + ")");
1348 pdbRequest.setAssociatedSequence(selectedSequence);
1349 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1350 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1351 FTSRestResponse resultList;
1354 resultList = pdbRestClient.executeRequest(pdbRequest);
1355 } catch (Exception e)
1357 errorWarning.append(e.getMessage());
1361 validateSelections();
1363 if (resultList.getSearchSummary() != null
1364 && resultList.getSearchSummary().size() > 0)
1366 isValidPBDEntry = true;
1369 validateSelections();
1375 protected void tabRefresh()
1377 if (selectedSequences != null)
1379 Thread refreshThread = new Thread(new Runnable()
1384 fetchStructuresMetaData();
1385 // populateFilterComboBox(true, cachedPDBExists);
1388 ((FilterOption) cmb_filterOption.getSelectedItem())
1392 refreshThread.start();
1396 public class PDBEntryTableModel extends AbstractTableModel
1398 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1401 private List<CachedPDB> pdbEntries;
1403 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1405 this.pdbEntries = new ArrayList<>(pdbEntries);
1409 public String getColumnName(int columnIndex)
1411 return columns[columnIndex];
1415 public int getRowCount()
1417 return pdbEntries.size();
1421 public int getColumnCount()
1423 return columns.length;
1427 public boolean isCellEditable(int row, int column)
1433 public Object getValueAt(int rowIndex, int columnIndex)
1435 Object value = "??";
1436 CachedPDB entry = pdbEntries.get(rowIndex);
1437 switch (columnIndex)
1440 value = entry.getSequence();
1443 value = entry.getQualifiedId();
1446 value = entry.getPdbEntry().getChainCode() == null ? "_"
1447 : entry.getPdbEntry().getChainCode();
1450 value = entry.getPdbEntry().getType();
1453 value = entry.getPdbEntry().getFile();
1460 public Class<?> getColumnClass(int columnIndex)
1462 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1465 public CachedPDB getPDBEntryAt(int row)
1467 return pdbEntries.get(row);
1472 private class CachedPDB
1474 private SequenceI sequence;
1476 private PDBEntry pdbEntry;
1478 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1480 this.sequence = sequence;
1481 this.pdbEntry = pdbEntry;
1484 public String getQualifiedId()
1486 if (pdbEntry.hasProvider())
1488 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1490 return pdbEntry.toString();
1493 public SequenceI getSequence()
1498 public PDBEntry getPdbEntry()
1505 private IProgressIndicator progressBar;
1508 public void setProgressBar(String message, long id)
1510 progressBar.setProgressBar(message, id);
1514 public void registerHandler(long id, IProgressIndicatorHandler handler)
1516 progressBar.registerHandler(id, handler);
1520 public boolean operationInProgress()
1522 return progressBar.operationInProgress();
1525 public JalviewStructureDisplayI getOpenedStructureViewer()
1527 return sViewer == null ? null : sViewer.sview;
1531 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1533 data.setDocFieldPrefs(newPrefs);
1539 * @return true when all initialisation threads have finished and dialog is
1542 public boolean isDialogVisible()
1544 return mainFrame != null && data != null && cmb_filterOption != null
1545 && mainFrame.isVisible()
1546 && cmb_filterOption.getSelectedItem() != null;
1551 * @return true if the 3D-Beacons query button will/has been displayed
1553 public boolean isCanQueryTDB()
1558 public boolean isNotQueriedTDBYet()
1560 return notQueriedTDBYet;