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 // TODO: warn if no accessions discovered
267 populateSeqsWithoutSourceDBRef();
268 // redo initial discovery - this time with 3d beacons
270 previousWantedFields = null;
271 lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
272 cmb_filterOption.setSelectedItem(null);
273 cachedPDBExists = false; // reset to initial
274 initialStructureDiscovery();
275 if (!isStructuresDiscovered())
277 progressBar.setProgressBar(MessageManager.getString(
278 "status.no_structures_discovered_from_3d_beacons"),
280 btn_queryTDB.setToolTipText(MessageManager.getString(
281 "status.no_structures_discovered_from_3d_beacons"));
282 btn_queryTDB.setEnabled(false);
286 cmb_filterOption.setSelectedIndex(0); // select 'best'
287 btn_queryTDB.setVisible(false);
288 progressBar.setProgressBar(null, progressId);
290 mainFrame.setEnabled(true);
291 cmb_filterOption.setEnabled(true);
295 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
299 public void finished()
301 // filter has been selected, so we set flag to remove ourselves
302 notQueriedTDBYet = false;
303 // new thread to discover structures - via 3d beacons
304 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
309 // fetch db refs if OK pressed
310 final Runnable discoverCanonicalDBrefs = new Runnable()
315 populateSeqsWithoutSourceDBRef();
317 final int y = seqsWithoutSourceDBRef.size();
320 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
321 .toArray(new SequenceI[y]);
322 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
323 progressBar, new DbSourceProxy[]
324 { new jalview.ws.dbsources.Uniprot() }, null, false);
325 dbRefFetcher.addListener(afterDbRefFetch);
326 // ideally this would also gracefully run with callbacks
327 dbRefFetcher.fetchDBRefs(true);
331 // call finished action directly
332 afterDbRefFetch.finished();
337 final Runnable revertview = new Runnable()
341 if (lastSelected != null)
343 cmb_filterOption.setSelectedItem(lastSelected);
349 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs)
353 // need cancel and no to result in the discoverPDB action - mocked is
354 // 'cancel' TODO: mock should be OK
355 JvOptionPane.newOptionDialog(this)
356 .setResponseHandler(JvOptionPane.OK_OPTION,
357 discoverCanonicalDBrefs)
358 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
359 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
361 MessageManager.formatMessage(
362 "label.fetch_references_for_3dbeacons",
363 seqsWithoutSourceDBRef.size()),
364 MessageManager.getString("label.3dbeacons"),
365 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
367 { MessageManager.getString("action.ok"),
368 MessageManager.getString("action.cancel") },
369 MessageManager.getString("action.ok"));
373 * Builds a drop-down choice list of existing structure viewers to which new
374 * structures may be added. If this list is empty then it, and the 'Add'
375 * button, are hidden.
377 private void discoverStructureViews()
379 if (Desktop.instance != null)
381 targetView.removeAllItems();
382 if (lastTargetedView != null && !lastTargetedView.isVisible())
384 lastTargetedView = null;
386 int linkedViewsAt = 0;
387 for (StructureViewerBase view : Desktop.instance
388 .getStructureViewers(null, null))
390 StructureViewer viewHandler = (lastTargetedView != null
391 && lastTargetedView.sview == view) ? lastTargetedView
392 : StructureViewer.reconfigure(view);
394 if (view.isLinkedWith(ap))
396 targetView.insertItemAt(viewHandler, linkedViewsAt++);
400 targetView.addItem(viewHandler);
405 * show option to Add to viewer if at least 1 viewer found
407 targetView.setVisible(false);
408 if (targetView.getItemCount() > 0)
410 targetView.setVisible(true);
411 if (lastTargetedView != null)
413 targetView.setSelectedItem(lastTargetedView);
417 targetView.setSelectedIndex(0);
420 btn_add.setVisible(targetView.isVisible());
425 * Updates the progress indicator with the specified message
428 * displayed message for the operation
430 * unique handle for this indicator
432 protected void updateProgressIndicator(String message, long id)
434 if (progressIndicator != null)
436 progressIndicator.setProgressBar(message, id);
441 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
444 void fetchStructuresMetaData()
446 long startTime = System.currentTimeMillis();
447 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
448 .getStructureSummaryFields();
450 discoveredStructuresSet = new LinkedHashSet<>();
451 HashSet<String> errors = new HashSet<>();
453 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
456 for (SequenceI seq : selectedSequences)
459 FTSRestResponse resultList;
462 resultList = data.fetchStructuresMetaData(seq, wantedFields,
463 selectedFilterOpt, !chk_invertFilter.isSelected());
464 // null response means the FTSengine didn't yield a query for this
465 // consider designing a special exception if we really wanted to be
467 if (resultList == null)
471 } catch (Exception e)
474 errors.add(e.getMessage());
477 if (resultList.getSearchSummary() != null
478 && !resultList.getSearchSummary().isEmpty())
480 discoveredStructuresSet.addAll(resultList.getSearchSummary());
484 int noOfStructuresFound = 0;
485 String totalTime = (System.currentTimeMillis() - startTime)
487 if (discoveredStructuresSet != null
488 && !discoveredStructuresSet.isEmpty())
491 .setModel(data.getTableModel(discoveredStructuresSet));
493 noOfStructuresFound = discoveredStructuresSet.size();
494 lastDiscoveredStructuresSet = discoveredStructuresSet;
495 mainFrame.setTitle(MessageManager.formatMessage(
496 "label.structure_chooser_no_of_structures",
497 noOfStructuresFound, totalTime));
501 mainFrame.setTitle(MessageManager
502 .getString("label.structure_chooser_manual_association"));
503 if (errors.size() > 0)
505 StringBuilder errorMsg = new StringBuilder();
506 for (String error : errors)
508 errorMsg.append(error).append("\n");
510 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
511 MessageManager.getString("label.pdb_web-service_error"),
512 JvOptionPane.ERROR_MESSAGE);
517 protected void loadLocalCachedPDBEntries()
519 ArrayList<CachedPDB> entries = new ArrayList<>();
520 for (SequenceI seq : selectedSequences)
522 if (seq.getDatasetSequence() != null
523 && seq.getDatasetSequence().getAllPDBEntries() != null)
525 for (PDBEntry pdbEntry : seq.getDatasetSequence()
528 if (pdbEntry.getFile() != null)
530 entries.add(new CachedPDB(seq, pdbEntry));
535 cachedPDBExists = !entries.isEmpty();
536 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
537 tbl_local_pdb.setModel(tableModelx);
541 * Filters a given list of discovered structures based on supplied argument
543 * @param fieldToFilterBy
544 * the field to filter by
546 void filterResultSet(final String fieldToFilterBy)
548 Thread filterThread = new Thread(new Runnable()
554 long startTime = System.currentTimeMillis();
555 lbl_loading.setVisible(true);
556 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
557 .getStructureSummaryFields();
558 Collection<FTSData> filteredResponse = new HashSet<>();
559 HashSet<String> errors = new HashSet<>();
561 for (SequenceI seq : selectedSequences)
564 FTSRestResponse resultList;
567 resultList = data.selectFirstRankedQuery(seq,
568 discoveredStructuresSet, wantedFields, fieldToFilterBy,
569 !chk_invertFilter.isSelected());
571 } catch (Exception e)
574 errors.add(e.getMessage());
577 if (resultList.getSearchSummary() != null
578 && !resultList.getSearchSummary().isEmpty())
580 filteredResponse.addAll(resultList.getSearchSummary());
584 String totalTime = (System.currentTimeMillis() - startTime)
586 if (!filteredResponse.isEmpty())
588 final int filterResponseCount = filteredResponse.size();
589 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
590 reorderedStructuresSet.addAll(filteredResponse);
591 reorderedStructuresSet.addAll(discoveredStructuresSet);
593 .setModel(data.getTableModel(reorderedStructuresSet));
595 FTSRestResponse.configureTableColumn(getResultTable(),
596 wantedFields, tempUserPrefs);
597 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
598 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
599 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
600 // Update table selection model here
601 getResultTable().addRowSelectionInterval(0,
602 filterResponseCount - 1);
603 mainFrame.setTitle(MessageManager.formatMessage(
604 "label.structure_chooser_filter_time", totalTime));
608 mainFrame.setTitle(MessageManager.formatMessage(
609 "label.structure_chooser_filter_time", totalTime));
610 if (errors.size() > 0)
612 StringBuilder errorMsg = new StringBuilder();
613 for (String error : errors)
615 errorMsg.append(error).append("\n");
617 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
618 MessageManager.getString("label.pdb_web-service_error"),
619 JvOptionPane.ERROR_MESSAGE);
623 lbl_loading.setVisible(false);
625 validateSelections();
628 filterThread.start();
632 * Handles action event for btn_pdbFromFile
635 protected void pdbFromFile_actionPerformed()
637 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
640 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
641 Cache.getProperty("LAST_DIRECTORY"));
642 chooser.setFileView(new jalview.io.JalviewFileView());
643 chooser.setDialogTitle(
644 MessageManager.formatMessage("label.select_pdb_file_for",
645 selectedSequence.getDisplayId(false)));
646 chooser.setToolTipText(MessageManager.formatMessage(
647 "label.load_pdb_file_associate_with_sequence",
648 selectedSequence.getDisplayId(false)));
650 int value = chooser.showOpenDialog(null);
651 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
653 selectedPdbFileName = chooser.getSelectedFile().getPath();
654 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
655 validateSelections();
660 * Populates the filter combo-box options dynamically depending on discovered
663 protected void populateFilterComboBox(boolean haveData,
664 boolean cachedPDBExist)
666 populateFilterComboBox(haveData, cachedPDBExist, null);
670 * Populates the filter combo-box options dynamically depending on discovered
673 protected void populateFilterComboBox(boolean haveData,
674 boolean cachedPDBExist, FilterOption lastSel)
678 * temporarily suspend the change listener behaviour
680 cmb_filterOption.removeItemListener(this);
682 cmb_filterOption.removeAllItems();
685 List<FilterOption> filters = data
686 .getAvailableFilterOptions(VIEWS_FILTER);
687 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
688 lastDiscoveredStructuresSet);
690 for (FilterOption filter : filters)
692 if (lastSel != null && filter.equals(lastSel))
697 cmb_filterOption.addItem(filter);
701 cmb_filterOption.addItem(
702 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
703 "-", VIEWS_ENTER_ID, false, null));
704 cmb_filterOption.addItem(
705 new FilterOption(MessageManager.getString("label.from_file"),
706 "-", VIEWS_FROM_FILE, false, null));
707 if (canQueryTDB && notQueriedTDBYet)
709 btn_queryTDB.setVisible(true);
714 FilterOption cachedOption = new FilterOption(
715 MessageManager.getString("label.cached_structures"), "-",
716 VIEWS_LOCAL_PDB, false, null);
717 cmb_filterOption.addItem(cachedOption);
720 cmb_filterOption.setSelectedItem(cachedOption);
725 cmb_filterOption.setSelectedIndex(selSet);
727 cmb_filterOption.addItemListener(this);
731 * Updates the displayed view based on the selected filter option
733 protected void updateCurrentView()
735 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
738 if (lastSelected == selectedFilterOpt)
740 // don't need to do anything, probably
743 // otherwise, record selection
744 // and update the layout and dialog accordingly
745 lastSelected = selectedFilterOpt;
747 layout_switchableViews.show(pnl_switchableViews,
748 selectedFilterOpt.getView());
749 String filterTitle = mainFrame.getTitle();
750 mainFrame.setTitle(frameTitle);
751 chk_invertFilter.setVisible(false);
753 if (selectedFilterOpt.getView() == VIEWS_FILTER)
755 mainFrame.setTitle(filterTitle);
756 // TDB Query has no invert as yet
757 chk_invertFilter.setVisible(selectedFilterOpt
758 .getQuerySource() instanceof PDBStructureChooserQuerySource);
760 if (data != selectedFilterOpt.getQuerySource()
761 || data.needsRefetch(selectedFilterOpt))
763 data = selectedFilterOpt.getQuerySource();
764 // rebuild the views completely, since prefs will also change
770 filterResultSet(selectedFilterOpt.getValue());
773 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
774 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
776 mainFrame.setTitle(MessageManager
777 .getString("label.structure_chooser_manual_association"));
778 idInputAssSeqPanel.loadCmbAssSeq();
779 fileChooserAssSeqPanel.loadCmbAssSeq();
781 validateSelections();
785 * Validates user selection and enables the 'Add' and 'New View' buttons if
786 * all parameters are correct (the Add button will only be visible if there is
787 * at least one existing structure viewer open). This basically means at least
788 * one structure selected and no error messages.
790 * The 'Superpose Structures' option is enabled if either more than one
791 * structure is selected, or the 'Add' to existing view option is enabled, and
792 * disabled if the only option is to open a new view of a single structure.
795 protected void validateSelections()
797 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
799 btn_add.setEnabled(false);
800 String currentView = selectedFilterOpt.getView();
801 int selectedCount = 0;
802 if (currentView == VIEWS_FILTER)
804 selectedCount = getResultTable().getSelectedRows().length;
805 if (selectedCount > 0)
807 btn_add.setEnabled(true);
810 else if (currentView == VIEWS_LOCAL_PDB)
812 selectedCount = tbl_local_pdb.getSelectedRows().length;
813 if (selectedCount > 0)
815 btn_add.setEnabled(true);
818 else if (currentView == VIEWS_ENTER_ID)
820 validateAssociationEnterPdb();
822 else if (currentView == VIEWS_FROM_FILE)
824 validateAssociationFromFile();
827 btn_newView.setEnabled(btn_add.isEnabled());
830 * enable 'Superpose' option if more than one structure is selected,
831 * or there are view(s) available to add structure(s) to
834 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
838 protected boolean showPopupFor(int selectedRow, int x, int y)
840 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
842 String currentView = selectedFilterOpt.getView();
844 if (currentView == VIEWS_FILTER
845 && data instanceof ThreeDBStructureChooserQuerySource)
848 TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
849 .getFTSDataFor(getResultTable(), selectedRow,
850 discoveredStructuresSet);
851 String pageUrl = row.getModelViewUrl();
852 JPopupMenu popup = new JPopupMenu("3D Beacons");
853 JMenuItem viewUrl = new JMenuItem("View model web page");
854 viewUrl.addActionListener(new ActionListener()
857 public void actionPerformed(ActionEvent e)
859 Desktop.showUrl(pageUrl);
863 SwingUtilities.invokeLater(new Runnable()
867 popup.show(getResultTable(), x, y);
872 // event not handled by us
877 * Validates inputs from the Manual PDB entry panel
879 protected void validateAssociationEnterPdb()
881 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
882 .getCmb_assSeq().getSelectedItem();
883 lbl_pdbManualFetchStatus.setIcon(errorImage);
884 lbl_pdbManualFetchStatus.setToolTipText("");
885 if (txt_search.getText().length() > 0)
887 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
888 MessageManager.formatMessage("info.no_pdb_entry_found_for",
889 txt_search.getText())));
892 if (errorWarning.length() > 0)
894 lbl_pdbManualFetchStatus.setIcon(warningImage);
895 lbl_pdbManualFetchStatus.setToolTipText(
896 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
899 if (selectedSequences.length == 1 || !assSeqOpt.getName()
900 .equalsIgnoreCase("-Select Associated Seq-"))
902 txt_search.setEnabled(true);
905 btn_add.setEnabled(true);
906 lbl_pdbManualFetchStatus.setToolTipText("");
907 lbl_pdbManualFetchStatus.setIcon(goodImage);
912 txt_search.setEnabled(false);
913 lbl_pdbManualFetchStatus.setIcon(errorImage);
918 * Validates inputs for the manual PDB file selection options
920 protected void validateAssociationFromFile()
922 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
923 .getCmb_assSeq().getSelectedItem();
924 lbl_fromFileStatus.setIcon(errorImage);
925 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
926 .getName().equalsIgnoreCase("-Select Associated Seq-")))
928 btn_pdbFromFile.setEnabled(true);
929 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
931 btn_add.setEnabled(true);
932 lbl_fromFileStatus.setIcon(goodImage);
937 btn_pdbFromFile.setEnabled(false);
938 lbl_fromFileStatus.setIcon(errorImage);
943 protected void cmbAssSeqStateChanged()
945 validateSelections();
948 private FilterOption lastSelected = null;
951 * Handles the state change event for the 'filter' combo-box and 'invert'
955 protected void stateChanged(ItemEvent e)
957 if (e.getSource() instanceof JCheckBox)
963 if (e.getStateChange() == ItemEvent.SELECTED)
972 * select structures for viewing by their PDB IDs
975 * @return true if structures were found and marked as selected
977 public boolean selectStructure(String... pdbids)
979 boolean found = false;
981 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
983 String currentView = selectedFilterOpt.getView();
984 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
985 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
987 if (restable == null)
989 // can't select (enter PDB ID, or load file - need to also select which
990 // sequence to associate with)
994 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
995 for (int r = 0; r < restable.getRowCount(); r++)
997 for (int p = 0; p < pdbids.length; p++)
999 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1000 .equalsIgnoreCase(pdbids[p]))
1002 restable.setRowSelectionInterval(r, r);
1011 * Handles the 'New View' action
1014 protected void newView_ActionPerformed()
1016 targetView.setSelectedItem(null);
1017 showStructures(false);
1021 * Handles the 'Add to existing viewer' action
1024 protected void add_ActionPerformed()
1026 showStructures(false);
1030 * structure viewer opened by this dialog, or null
1032 private StructureViewer sViewer = null;
1034 public void showStructures(boolean waitUntilFinished)
1037 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1039 final int preferredHeight = pnl_filter.getHeight();
1041 Runnable viewStruc = new Runnable()
1046 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1047 .getSelectedItem());
1048 String currentView = selectedFilterOpt.getView();
1049 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1052 if (currentView == VIEWS_FILTER)
1054 int[] selectedRows = restable.getSelectedRows();
1055 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1056 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1057 pdbEntriesToView = data.collectSelectedRows(restable,
1058 selectedRows, selectedSeqsToView);
1060 SequenceI[] selectedSeqs = selectedSeqsToView
1061 .toArray(new SequenceI[selectedSeqsToView.size()]);
1062 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1065 else if (currentView == VIEWS_LOCAL_PDB)
1067 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1068 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1070 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1072 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1074 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1075 for (int row : selectedRows)
1077 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1078 .getModel()).getPDBEntryAt(row).getPdbEntry();
1080 pdbEntriesToView[count++] = pdbEntry;
1081 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1082 .getValueAt(row, refSeqColIndex);
1083 selectedSeqsToView.add(selectedSeq);
1085 SequenceI[] selectedSeqs = selectedSeqsToView
1086 .toArray(new SequenceI[selectedSeqsToView.size()]);
1087 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1090 else if (currentView == VIEWS_ENTER_ID)
1092 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1093 .getCmb_assSeq().getSelectedItem()).getSequence();
1094 if (userSelectedSeq != null)
1096 selectedSequence = userSelectedSeq;
1098 String pdbIdStr = txt_search.getText();
1099 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1100 if (pdbEntry == null)
1102 pdbEntry = new PDBEntry();
1103 if (pdbIdStr.split(":").length > 1)
1105 pdbEntry.setId(pdbIdStr.split(":")[0]);
1106 pdbEntry.setChainCode(
1107 pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1111 pdbEntry.setId(pdbIdStr);
1113 pdbEntry.setType(PDBEntry.Type.PDB);
1114 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1117 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1118 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1120 { selectedSequence });
1122 else if (currentView == VIEWS_FROM_FILE)
1124 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1125 .getCmb_assSeq().getSelectedItem()).getSequence();
1126 if (userSelectedSeq != null)
1128 selectedSequence = userSelectedSeq;
1130 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1131 .associatePdbWithSeq(selectedPdbFileName,
1132 DataSourceType.FILE, selectedSequence, true,
1135 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1137 { selectedSequence });
1139 SwingUtilities.invokeLater(new Runnable()
1144 closeAction(preferredHeight);
1145 mainFrame.dispose();
1150 Thread runner = new Thread(viewStruc);
1152 if (waitUntilFinished)
1154 while (sViewer == null ? runner.isAlive()
1155 : (sViewer.sview == null ? true
1156 : !sViewer.sview.hasMapping()))
1161 } catch (InterruptedException ie)
1170 * Answers a structure viewer (new or existing) configured to superimpose
1171 * added structures or not according to the user's choice
1176 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1178 Object sv = targetView.getSelectedItem();
1180 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1184 * Adds PDB structures to a new or existing structure viewer
1187 * @param pdbEntriesToView
1192 private StructureViewer launchStructureViewer(
1193 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1194 final AlignmentPanel alignPanel, SequenceI[] sequences)
1196 long progressId = sequences.hashCode();
1197 setProgressBar(MessageManager
1198 .getString("status.launching_3d_structure_viewer"), progressId);
1199 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1200 boolean superimpose = chk_superpose.isSelected();
1201 theViewer.setSuperpose(superimpose);
1204 * remember user's choice of superimpose or not
1206 Cache.setProperty(AUTOSUPERIMPOSE,
1207 Boolean.valueOf(superimpose).toString());
1209 setProgressBar(null, progressId);
1210 if (SiftsSettings.isMapWithSifts())
1212 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1214 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1215 // real PDB ID. For moment, we can also safely do this if there is already
1216 // a known mapping between the PDBEntry and the sequence.
1217 for (SequenceI seq : sequences)
1219 PDBEntry pdbe = pdbEntriesToView[p++];
1220 if (pdbe != null && pdbe.getFile() != null)
1222 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1223 if (smm != null && smm.length > 0)
1225 for (StructureMapping sm : smm)
1227 if (sm.getSequence() == seq)
1234 if (seq.getPrimaryDBRefs().isEmpty())
1236 seqsWithoutSourceDBRef.add(seq);
1240 if (!seqsWithoutSourceDBRef.isEmpty())
1242 int y = seqsWithoutSourceDBRef.size();
1243 setProgressBar(MessageManager.formatMessage(
1244 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1246 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1247 .toArray(new SequenceI[y]);
1248 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1249 dbRefFetcher.fetchDBRefs(true);
1251 setProgressBar("Fetch complete.", progressId); // todo i18n
1254 if (pdbEntriesToView.length > 1)
1257 MessageManager.getString(
1258 "status.fetching_3d_structures_for_selected_entries"),
1260 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1264 setProgressBar(MessageManager.formatMessage(
1265 "status.fetching_3d_structures_for",
1266 pdbEntriesToView[0].getId()), progressId);
1267 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1269 setProgressBar(null, progressId);
1270 // remember the last viewer we used...
1271 lastTargetedView = theViewer;
1276 * Populates the combo-box used in associating manually fetched structures to
1277 * a unique sequence when more than one sequence selection is made.
1280 protected void populateCmbAssociateSeqOptions(
1281 JComboBox<AssociateSeqOptions> cmb_assSeq,
1282 JLabel lbl_associateSeq)
1284 cmb_assSeq.removeAllItems();
1286 new AssociateSeqOptions("-Select Associated Seq-", null));
1287 lbl_associateSeq.setVisible(false);
1288 if (selectedSequences.length > 1)
1290 for (SequenceI seq : selectedSequences)
1292 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1297 String seqName = selectedSequence.getDisplayId(false);
1298 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1299 lbl_associateSeq.setText(seqName);
1300 lbl_associateSeq.setVisible(true);
1301 cmb_assSeq.setVisible(false);
1305 protected boolean isStructuresDiscovered()
1307 return discoveredStructuresSet != null
1308 && !discoveredStructuresSet.isEmpty();
1311 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1313 // Doing a search for "1" or "1c" is valuable?
1314 // Those work but are enormously slow.
1317 protected void txt_search_ActionPerformed()
1319 String text = txt_search.getText().trim();
1320 if (text.length() >= PDB_ID_MIN)
1327 errorWarning.setLength(0);
1328 isValidPBDEntry = false;
1329 if (text.length() > 0)
1331 // TODO move this pdb id search into the PDB specific
1333 // for moment, it will work fine as is because it is self-contained
1334 String searchTerm = text.toLowerCase(Locale.ROOT);
1335 searchTerm = searchTerm.split(":")[0];
1336 // System.out.println(">>>>> search term : " + searchTerm);
1337 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1338 FTSRestRequest pdbRequest = new FTSRestRequest();
1339 pdbRequest.setAllowEmptySeq(false);
1340 pdbRequest.setResponseSize(1);
1341 pdbRequest.setFieldToSearchBy("(pdb_id:");
1342 pdbRequest.setWantedFields(wantedFields);
1343 pdbRequest.setSearchTerm(searchTerm + ")");
1344 pdbRequest.setAssociatedSequence(selectedSequence);
1345 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1346 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1347 FTSRestResponse resultList;
1350 resultList = pdbRestClient.executeRequest(pdbRequest);
1351 } catch (Exception e)
1353 errorWarning.append(e.getMessage());
1357 validateSelections();
1359 if (resultList.getSearchSummary() != null
1360 && resultList.getSearchSummary().size() > 0)
1362 isValidPBDEntry = true;
1365 validateSelections();
1371 protected void tabRefresh()
1373 if (selectedSequences != null)
1375 Thread refreshThread = new Thread(new Runnable()
1380 fetchStructuresMetaData();
1381 // populateFilterComboBox(true, cachedPDBExists);
1384 ((FilterOption) cmb_filterOption.getSelectedItem())
1388 refreshThread.start();
1392 public class PDBEntryTableModel extends AbstractTableModel
1394 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1397 private List<CachedPDB> pdbEntries;
1399 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1401 this.pdbEntries = new ArrayList<>(pdbEntries);
1405 public String getColumnName(int columnIndex)
1407 return columns[columnIndex];
1411 public int getRowCount()
1413 return pdbEntries.size();
1417 public int getColumnCount()
1419 return columns.length;
1423 public boolean isCellEditable(int row, int column)
1429 public Object getValueAt(int rowIndex, int columnIndex)
1431 Object value = "??";
1432 CachedPDB entry = pdbEntries.get(rowIndex);
1433 switch (columnIndex)
1436 value = entry.getSequence();
1439 value = entry.getQualifiedId();
1442 value = entry.getPdbEntry().getChainCode() == null ? "_"
1443 : entry.getPdbEntry().getChainCode();
1446 value = entry.getPdbEntry().getType();
1449 value = entry.getPdbEntry().getFile();
1456 public Class<?> getColumnClass(int columnIndex)
1458 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1461 public CachedPDB getPDBEntryAt(int row)
1463 return pdbEntries.get(row);
1468 private class CachedPDB
1470 private SequenceI sequence;
1472 private PDBEntry pdbEntry;
1474 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1476 this.sequence = sequence;
1477 this.pdbEntry = pdbEntry;
1480 public String getQualifiedId()
1482 if (pdbEntry.hasProvider())
1484 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1486 return pdbEntry.toString();
1489 public SequenceI getSequence()
1494 public PDBEntry getPdbEntry()
1501 private IProgressIndicator progressBar;
1504 public void setProgressBar(String message, long id)
1506 progressBar.setProgressBar(message, id);
1510 public void registerHandler(long id, IProgressIndicatorHandler handler)
1512 progressBar.registerHandler(id, handler);
1516 public boolean operationInProgress()
1518 return progressBar.operationInProgress();
1521 public JalviewStructureDisplayI getOpenedStructureViewer()
1523 return sViewer == null ? null : sViewer.sview;
1527 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1529 data.setDocFieldPrefs(newPrefs);
1535 * @return true when all initialisation threads have finished and dialog is
1538 public boolean isDialogVisible()
1540 return mainFrame != null && data != null && cmb_filterOption != null
1541 && mainFrame.isVisible()
1542 && cmb_filterOption.getSelectedItem() != null;
1547 * @return true if the 3D-Beacons query button will/has been displayed
1549 public boolean isCanQueryTDB()
1554 public boolean isNotQueriedTDBYet()
1556 return notQueriedTDBYet;