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.Console;
48 import jalview.bin.Jalview;
49 import jalview.datamodel.PDBEntry;
50 import jalview.datamodel.SequenceI;
51 import jalview.fts.api.FTSData;
52 import jalview.fts.api.FTSDataColumnI;
53 import jalview.fts.api.FTSRestClientI;
54 import jalview.fts.core.FTSDataColumnPreferences;
55 import jalview.fts.core.FTSRestRequest;
56 import jalview.fts.core.FTSRestResponse;
57 import jalview.fts.service.pdb.PDBFTSRestClient;
58 import jalview.fts.service.threedbeacons.TDB_FTSData;
59 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
60 import jalview.gui.structurechooser.StructureChooserQuerySource;
61 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
62 import jalview.io.DataSourceType;
63 import jalview.jbgui.FilterOption;
64 import jalview.jbgui.GStructureChooser;
65 import jalview.structure.StructureMapping;
66 import jalview.structure.StructureSelectionManager;
67 import jalview.util.MessageManager;
68 import jalview.ws.DBRefFetcher;
69 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
70 import jalview.ws.seqfetcher.DbSourceProxy;
71 import jalview.ws.sifts.SiftsSettings;
74 * Provides the behaviors for the Structure chooser Panel
79 @SuppressWarnings("serial")
80 public class StructureChooser extends GStructureChooser
81 implements IProgressIndicator
83 protected static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
86 * warn user if need to fetch more than this many uniprot records at once
88 private static final int THRESHOLD_WARN_UNIPROT_FETCH_NEEDED = 20;
89 private SequenceI selectedSequence;
91 private SequenceI[] selectedSequences;
93 private IProgressIndicator progressIndicator;
95 private Collection<FTSData> discoveredStructuresSet;
97 private StructureChooserQuerySource data;
100 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
102 return data.getDocFieldPrefs();
105 private String selectedPdbFileName;
107 private boolean isValidPBDEntry;
109 private boolean cachedPDBExists;
111 private Collection<FTSData> lastDiscoveredStructuresSet;
113 private boolean canQueryTDB = false;
115 private boolean notQueriedTDBYet = true;
117 List<SequenceI> seqsWithoutSourceDBRef = null;
119 protected static StructureViewer lastTargetedView = null;
121 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
124 // which FTS engine to use
125 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
129 this.selectedSequence = selectedSeq;
130 this.selectedSequences = selectedSeqs;
131 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
137 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
138 * least one structure are discovered.
140 private void populateSeqsWithoutSourceDBRef()
142 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
143 boolean needCanonical = false;
144 for (SequenceI seq : selectedSequences)
148 int dbRef = ThreeDBStructureChooserQuerySource
149 .checkUniprotRefs(seq.getDBRefs());
154 // need to retrieve canonicals
155 needCanonical = true;
156 seqsWithoutSourceDBRef.add(seq);
160 // could be a sequence with pdb ref
161 if (seq.getAllPDBEntries() == null
162 || seq.getAllPDBEntries().size() == 0)
164 seqsWithoutSourceDBRef.add(seq);
170 // retrieve database refs for protein sequences
171 if (!seqsWithoutSourceDBRef.isEmpty())
176 // triggers display of the 'Query TDB' button
177 notQueriedTDBYet = true;
183 * Initializes parameters used by the Structure Chooser Panel
185 protected void init()
187 if (!Jalview.isHeadlessMode())
189 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
192 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
193 btn_queryTDB.addActionListener(new ActionListener()
197 public void actionPerformed(ActionEvent e)
199 promptForTDBFetch(false);
203 Executors.defaultThreadFactory().newThread(new Runnable()
208 populateSeqsWithoutSourceDBRef();
209 initialStructureDiscovery();
217 private void initialStructureDiscovery()
219 // check which FTS engine to use
220 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
222 // ensure a filter option is in force for search
223 populateFilterComboBox(true, cachedPDBExists);
225 // looks for any existing structures already loaded
226 // for the sequences (the cached ones)
227 // then queries the StructureChooserQuerySource to
228 // discover more structures.
230 // Possible optimisation is to only begin querying
231 // the structure chooser if there are no cached structures.
233 long startTime = System.currentTimeMillis();
234 updateProgressIndicator(
235 MessageManager.getString("status.loading_cached_pdb_entries"),
237 loadLocalCachedPDBEntries();
238 updateProgressIndicator(null, startTime);
239 updateProgressIndicator(
240 MessageManager.getString("status.searching_for_pdb_structures"),
242 fetchStructuresMetaData();
243 // revise filter options if no results were found
244 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
245 discoverStructureViews();
246 updateProgressIndicator(null, startTime);
247 mainFrame.setVisible(true);
252 * raises dialog for Uniprot fetch followed by 3D beacons search
255 * - when true, don't ask, just fetch
257 public void promptForTDBFetch(boolean ignoreGui)
259 final long progressId = System.currentTimeMillis();
261 // final action after prompting and discovering db refs
262 final Runnable strucDiscovery = new Runnable()
267 mainFrame.setEnabled(false);
268 cmb_filterOption.setEnabled(false);
269 progressBar.setProgressBar(
270 MessageManager.getString("status.searching_3d_beacons"),
272 btn_queryTDB.setEnabled(false);
273 // TODO: warn if no accessions discovered
274 populateSeqsWithoutSourceDBRef();
275 // redo initial discovery - this time with 3d beacons
277 previousWantedFields = null;
278 lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
279 cmb_filterOption.setSelectedItem(null);
280 cachedPDBExists=false; // reset to initial
281 initialStructureDiscovery();
282 if (!isStructuresDiscovered())
284 progressBar.setProgressBar(MessageManager.getString(
285 "status.no_structures_discovered_from_3d_beacons"),
287 btn_queryTDB.setToolTipText(MessageManager.getString(
288 "status.no_structures_discovered_from_3d_beacons"));
289 btn_queryTDB.setEnabled(false);
290 pnl_queryTDB.setVisible(false);
294 cmb_filterOption.setSelectedIndex(0); // select 'best'
295 btn_queryTDB.setVisible(false);
296 pnl_queryTDB.setVisible(false);
297 progressBar.setProgressBar(null, progressId);
299 mainFrame.setEnabled(true);
300 cmb_filterOption.setEnabled(true);
304 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
308 public void finished()
310 // filter has been selected, so we set flag to remove ourselves
311 notQueriedTDBYet = false;
312 // new thread to discover structures - via 3d beacons
313 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
318 // fetch db refs if OK pressed
319 final Runnable discoverCanonicalDBrefs = new Runnable()
324 btn_queryTDB.setEnabled(false);
325 populateSeqsWithoutSourceDBRef();
327 final int y = seqsWithoutSourceDBRef.size();
330 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
331 .toArray(new SequenceI[y]);
332 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
333 progressBar, new DbSourceProxy[]
334 { new jalview.ws.dbsources.Uniprot() }, null, false);
335 dbRefFetcher.addListener(afterDbRefFetch);
336 // ideally this would also gracefully run with callbacks
337 dbRefFetcher.fetchDBRefs(true);
341 // call finished action directly
342 afterDbRefFetch.finished();
347 final Runnable revertview = new Runnable()
352 if (lastSelected != null)
354 cmb_filterOption.setSelectedItem(lastSelected);
358 int threshold = Cache.getDefault("UNIPROT_AUTOFETCH_THRESHOLD",
359 THRESHOLD_WARN_UNIPROT_FETCH_NEEDED);
360 Console.debug("Using Uniprot fetch threshold of " + threshold);
361 if (ignoreGui || seqsWithoutSourceDBRef.size() < threshold)
363 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs).start();
366 // need cancel and no to result in the discoverPDB action - mocked is
367 // 'cancel' TODO: mock should be OK
368 StructureChooser thisSC = this;
369 JvOptionPane.newOptionDialog(thisSC.getFrame())
370 .setResponseHandler(JvOptionPane.OK_OPTION,
371 discoverCanonicalDBrefs)
372 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
373 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
375 MessageManager.formatMessage(
376 "label.fetch_references_for_3dbeacons",
377 seqsWithoutSourceDBRef.size()),
379 .getString("label.3dbeacons"),
380 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
382 { MessageManager.getString("action.ok"),
383 MessageManager.getString("action.cancel") },
384 MessageManager.getString("action.ok"), false);
388 * Builds a drop-down choice list of existing structure viewers to which new
389 * structures may be added. If this list is empty then it, and the 'Add'
390 * button, are hidden.
392 private void discoverStructureViews()
394 if (Desktop.getInstance() != null)
396 targetView.removeAllItems();
397 if (lastTargetedView != null && !lastTargetedView.isVisible())
399 lastTargetedView = null;
401 int linkedViewsAt = 0;
402 for (StructureViewerBase view : Desktop.getInstance()
403 .getStructureViewers(null, null))
405 StructureViewer viewHandler = (lastTargetedView != null
406 && lastTargetedView.sview == view) ? lastTargetedView
407 : StructureViewer.reconfigure(view);
409 if (view.isLinkedWith(ap))
411 targetView.insertItemAt(viewHandler, linkedViewsAt++);
415 targetView.addItem(viewHandler);
420 * show option to Add to viewer if at least 1 viewer found
422 targetView.setVisible(false);
423 if (targetView.getItemCount() > 0)
425 targetView.setVisible(true);
426 if (lastTargetedView != null)
428 targetView.setSelectedItem(lastTargetedView);
432 targetView.setSelectedIndex(0);
435 btn_add.setVisible(targetView.isVisible());
440 * Updates the progress indicator with the specified message
443 * displayed message for the operation
445 * unique handle for this indicator
447 protected void updateProgressIndicator(String message, long id)
449 if (progressIndicator != null)
451 progressIndicator.setProgressBar(message, id);
456 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
459 void fetchStructuresMetaData()
461 long startTime = System.currentTimeMillis();
462 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
463 .getStructureSummaryFields();
465 discoveredStructuresSet = new LinkedHashSet<>();
466 HashSet<String> errors = new HashSet<>();
468 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
471 for (SequenceI seq : selectedSequences)
474 FTSRestResponse resultList;
477 resultList = data.fetchStructuresMetaData(seq, wantedFields,
478 selectedFilterOpt, !chk_invertFilter.isSelected());
479 // null response means the FTSengine didn't yield a query for this
480 // consider designing a special exception if we really wanted to be
482 if (resultList == null)
486 } catch (Exception e)
489 errors.add(e.getMessage());
492 if (resultList.getSearchSummary() != null
493 && !resultList.getSearchSummary().isEmpty())
495 discoveredStructuresSet.addAll(resultList.getSearchSummary());
499 int noOfStructuresFound = 0;
500 String totalTime = (System.currentTimeMillis() - startTime)
502 if (discoveredStructuresSet != null
503 && !discoveredStructuresSet.isEmpty())
506 .setModel(data.getTableModel(discoveredStructuresSet));
508 noOfStructuresFound = discoveredStructuresSet.size();
509 lastDiscoveredStructuresSet = discoveredStructuresSet;
510 mainFrame.setTitle(MessageManager.formatMessage(
511 "label.structure_chooser_no_of_structures",
512 noOfStructuresFound, totalTime));
516 mainFrame.setTitle(MessageManager
517 .getString("label.structure_chooser_manual_association"));
518 if (errors.size() > 0)
520 StringBuilder errorMsg = new StringBuilder();
521 for (String error : errors)
523 errorMsg.append(error).append("\n");
525 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
526 MessageManager.getString("label.pdb_web-service_error"),
527 JvOptionPane.ERROR_MESSAGE);
532 protected void loadLocalCachedPDBEntries()
534 ArrayList<CachedPDB> entries = new ArrayList<>();
535 for (SequenceI seq : selectedSequences)
537 if (seq.getDatasetSequence() != null
538 && seq.getDatasetSequence().getAllPDBEntries() != null)
540 for (PDBEntry pdbEntry : seq.getDatasetSequence()
543 if (pdbEntry.getFile() != null)
545 entries.add(new CachedPDB(seq, pdbEntry));
550 cachedPDBExists = !entries.isEmpty();
551 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
552 tbl_local_pdb.setModel(tableModelx);
556 * Filters a given list of discovered structures based on supplied argument
558 * @param fieldToFilterBy
559 * the field to filter by
561 void filterResultSet(final String fieldToFilterBy)
563 Thread filterThread = new Thread(new Runnable()
569 long startTime = System.currentTimeMillis();
570 lbl_loading.setVisible(true);
571 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
572 .getStructureSummaryFields();
573 Collection<FTSData> filteredResponse = new HashSet<>();
574 HashSet<String> errors = new HashSet<>();
576 for (SequenceI seq : selectedSequences)
579 FTSRestResponse resultList;
582 resultList = data.selectFirstRankedQuery(seq,
583 discoveredStructuresSet, wantedFields, fieldToFilterBy,
584 !chk_invertFilter.isSelected());
586 } catch (Exception e)
589 errors.add(e.getMessage());
592 if (resultList.getSearchSummary() != null
593 && !resultList.getSearchSummary().isEmpty())
595 filteredResponse.addAll(resultList.getSearchSummary());
599 String totalTime = (System.currentTimeMillis() - startTime)
601 if (!filteredResponse.isEmpty())
603 final int filterResponseCount = filteredResponse.size();
604 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
605 reorderedStructuresSet.addAll(filteredResponse);
606 reorderedStructuresSet.addAll(discoveredStructuresSet);
608 .setModel(data.getTableModel(reorderedStructuresSet));
610 FTSRestResponse.configureTableColumn(getResultTable(),
611 wantedFields, tempUserPrefs);
612 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
613 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
614 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
615 // Update table selection model here
616 getResultTable().addRowSelectionInterval(0,
617 filterResponseCount - 1);
618 mainFrame.setTitle(MessageManager.formatMessage(
619 "label.structure_chooser_filter_time", totalTime));
623 mainFrame.setTitle(MessageManager.formatMessage(
624 "label.structure_chooser_filter_time", totalTime));
625 if (errors.size() > 0)
627 StringBuilder errorMsg = new StringBuilder();
628 for (String error : errors)
630 errorMsg.append(error).append("\n");
632 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
633 MessageManager.getString("label.pdb_web-service_error"),
634 JvOptionPane.ERROR_MESSAGE);
638 lbl_loading.setVisible(false);
640 validateSelections();
643 filterThread.start();
647 * Handles action event for btn_pdbFromFile
650 protected void pdbFromFile_actionPerformed()
652 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
655 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
656 Cache.getProperty("LAST_DIRECTORY"));
657 chooser.setFileView(new jalview.io.JalviewFileView());
658 chooser.setDialogTitle(
659 MessageManager.formatMessage("label.select_pdb_file_for",
660 selectedSequence.getDisplayId(false)));
661 chooser.setToolTipText(MessageManager.formatMessage(
662 "label.load_pdb_file_associate_with_sequence",
663 selectedSequence.getDisplayId(false)));
665 int value = chooser.showOpenDialog(null);
666 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
668 selectedPdbFileName = chooser.getSelectedFile().getPath();
669 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
670 validateSelections();
675 * Populates the filter combo-box options dynamically depending on discovered
678 protected void populateFilterComboBox(boolean haveData,
679 boolean cachedPDBExist)
681 populateFilterComboBox(haveData, cachedPDBExist, null);
685 * Populates the filter combo-box options dynamically depending on discovered
688 protected void populateFilterComboBox(boolean haveData,
689 boolean cachedPDBExist, FilterOption lastSel)
693 * temporarily suspend the change listener behaviour
695 cmb_filterOption.removeItemListener(this);
697 cmb_filterOption.removeAllItems();
700 List<FilterOption> filters = data
701 .getAvailableFilterOptions(VIEWS_FILTER);
702 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
703 lastDiscoveredStructuresSet);
705 for (FilterOption filter : filters)
707 if (lastSel != null && filter.equals(lastSel))
712 cmb_filterOption.addItem(filter);
716 cmb_filterOption.addItem(
717 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
718 "-", VIEWS_ENTER_ID, false, null));
719 cmb_filterOption.addItem(
720 new FilterOption(MessageManager.getString("label.from_file"),
721 "-", VIEWS_FROM_FILE, false, null));
722 if (canQueryTDB && notQueriedTDBYet)
724 btn_queryTDB.setVisible(true);
725 pnl_queryTDB.setVisible(true);
730 FilterOption cachedOption = new FilterOption(
731 MessageManager.getString("label.cached_structures"), "-",
732 VIEWS_LOCAL_PDB, false, null);
733 cmb_filterOption.addItem(cachedOption);
736 cmb_filterOption.setSelectedItem(cachedOption);
741 cmb_filterOption.setSelectedIndex(selSet);
743 cmb_filterOption.addItemListener(this);
747 * Updates the displayed view based on the selected filter option
749 protected void updateCurrentView()
751 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
754 if (lastSelected == selectedFilterOpt)
756 // don't need to do anything, probably
759 // otherwise, record selection
760 // and update the layout and dialog accordingly
761 lastSelected = selectedFilterOpt;
763 layout_switchableViews.show(pnl_switchableViews,
764 selectedFilterOpt.getView());
765 String filterTitle = mainFrame.getTitle();
766 mainFrame.setTitle(frameTitle);
767 chk_invertFilter.setVisible(false);
769 if (selectedFilterOpt.getView() == VIEWS_FILTER)
771 mainFrame.setTitle(filterTitle);
772 // TDB Query has no invert as yet
773 chk_invertFilter.setVisible(selectedFilterOpt
774 .getQuerySource() instanceof PDBStructureChooserQuerySource);
776 if (data != selectedFilterOpt.getQuerySource()
777 || data.needsRefetch(selectedFilterOpt))
779 data = selectedFilterOpt.getQuerySource();
780 // rebuild the views completely, since prefs will also change
786 filterResultSet(selectedFilterOpt.getValue());
789 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
790 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
792 mainFrame.setTitle(MessageManager
793 .getString("label.structure_chooser_manual_association"));
794 idInputAssSeqPanel.loadCmbAssSeq();
795 fileChooserAssSeqPanel.loadCmbAssSeq();
797 validateSelections();
801 * Validates user selection and enables the 'Add' and 'New View' buttons if
802 * all parameters are correct (the Add button will only be visible if there is
803 * at least one existing structure viewer open). This basically means at least
804 * one structure selected and no error messages.
806 * The 'Superpose Structures' option is enabled if either more than one
807 * structure is selected, or the 'Add' to existing view option is enabled, and
808 * disabled if the only option is to open a new view of a single structure.
811 protected void validateSelections()
813 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
815 btn_add.setEnabled(false);
816 String currentView = selectedFilterOpt.getView();
817 int selectedCount = 0;
818 if (currentView == VIEWS_FILTER)
820 selectedCount = getResultTable().getSelectedRows().length;
821 if (selectedCount > 0)
823 btn_add.setEnabled(true);
826 else if (currentView == VIEWS_LOCAL_PDB)
828 selectedCount = tbl_local_pdb.getSelectedRows().length;
829 if (selectedCount > 0)
831 btn_add.setEnabled(true);
834 else if (currentView == VIEWS_ENTER_ID)
836 validateAssociationEnterPdb();
838 else if (currentView == VIEWS_FROM_FILE)
840 validateAssociationFromFile();
843 btn_newView.setEnabled(btn_add.isEnabled());
846 * enable 'Superpose' option if more than one structure is selected,
847 * or there are view(s) available to add structure(s) to
850 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
854 protected boolean showPopupFor(int selectedRow, int x, int y)
856 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
858 String currentView = selectedFilterOpt.getView();
859 if (currentView == VIEWS_FILTER
860 && data instanceof ThreeDBStructureChooserQuerySource)
862 TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
863 .getFTSDataFor(getResultTable(), selectedRow,
864 discoveredStructuresSet);
865 String pageUrl = row.getModelViewUrl();
866 JPopupMenu popup = new JPopupMenu("3D Beacons");
867 JMenuItem viewUrl = new JMenuItem("View model web page");
868 viewUrl.addActionListener(new ActionListener()
871 public void actionPerformed(ActionEvent e)
873 Desktop.showUrl(pageUrl);
877 SwingUtilities.invokeLater(new Runnable()
882 popup.show(getResultTable(), x, y);
887 // event not handled by us
891 * Validates inputs from the Manual PDB entry panel
893 protected void validateAssociationEnterPdb()
895 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
896 .getCmb_assSeq().getSelectedItem();
897 lbl_pdbManualFetchStatus.setIcon(errorImage);
898 lbl_pdbManualFetchStatus.setToolTipText("");
899 if (txt_search.getText().length() > 0)
901 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
902 MessageManager.formatMessage("info.no_pdb_entry_found_for",
903 txt_search.getText())));
906 if (errorWarning.length() > 0)
908 lbl_pdbManualFetchStatus.setIcon(warningImage);
909 lbl_pdbManualFetchStatus.setToolTipText(
910 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
913 if (selectedSequences.length == 1 || !assSeqOpt.getName()
914 .equalsIgnoreCase("-Select Associated Seq-"))
916 txt_search.setEnabled(true);
919 btn_add.setEnabled(true);
920 lbl_pdbManualFetchStatus.setToolTipText("");
921 lbl_pdbManualFetchStatus.setIcon(goodImage);
926 txt_search.setEnabled(false);
927 lbl_pdbManualFetchStatus.setIcon(errorImage);
932 * Validates inputs for the manual PDB file selection options
934 protected void validateAssociationFromFile()
936 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
937 .getCmb_assSeq().getSelectedItem();
938 lbl_fromFileStatus.setIcon(errorImage);
939 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
940 .getName().equalsIgnoreCase("-Select Associated Seq-")))
942 btn_pdbFromFile.setEnabled(true);
943 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
945 btn_add.setEnabled(true);
946 lbl_fromFileStatus.setIcon(goodImage);
951 btn_pdbFromFile.setEnabled(false);
952 lbl_fromFileStatus.setIcon(errorImage);
957 protected void cmbAssSeqStateChanged()
959 validateSelections();
961 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();
1050 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1051 boolean superimpose = chk_superpose.isSelected();
1052 final int preferredHeight = pnl_filter.getHeight();
1054 Runnable viewStruc = new Runnable()
1059 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1060 .getSelectedItem());
1061 String currentView = selectedFilterOpt.getView();
1062 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1065 if (currentView == VIEWS_FILTER)
1067 int[] selectedRows = restable.getSelectedRows();
1068 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1069 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1070 pdbEntriesToView = data.collectSelectedRows(restable,
1071 selectedRows, selectedSeqsToView);
1073 SequenceI[] selectedSeqs = selectedSeqsToView
1074 .toArray(new SequenceI[selectedSeqsToView.size()]);
1075 sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
1076 selectedSeqs, superimpose, theViewer, progressBar);
1078 else if (currentView == VIEWS_LOCAL_PDB)
1080 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1081 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1083 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1085 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1087 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1088 for (int row : selectedRows)
1090 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1091 .getModel()).getPDBEntryAt(row).getPdbEntry();
1093 pdbEntriesToView[count++] = pdbEntry;
1094 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1095 .getValueAt(row, refSeqColIndex);
1096 selectedSeqsToView.add(selectedSeq);
1098 SequenceI[] selectedSeqs = selectedSeqsToView
1099 .toArray(new SequenceI[selectedSeqsToView.size()]);
1100 sViewer = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
1101 selectedSeqs, superimpose, theViewer, progressBar);
1103 else if (currentView == VIEWS_ENTER_ID)
1105 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1106 .getCmb_assSeq().getSelectedItem()).getSequence();
1107 if (userSelectedSeq != null)
1109 selectedSequence = userSelectedSeq;
1111 String pdbIdStr = txt_search.getText();
1112 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1113 if (pdbEntry == null)
1115 pdbEntry = new PDBEntry();
1116 if (pdbIdStr.split(":").length > 1)
1118 pdbEntry.setId(pdbIdStr.split(":")[0]);
1119 pdbEntry.setChainCode(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 = StructureViewer.launchStructureViewer(ap, pdbEntriesToView,
1132 { selectedSequence }, superimpose, theViewer,
1135 else if (currentView == VIEWS_FROM_FILE)
1137 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1138 .getCmb_assSeq().getSelectedItem()).getSequence();
1139 if (userSelectedSeq != null)
1141 selectedSequence = userSelectedSeq;
1143 PDBEntry fileEntry = AssociatePdbFileWithSeq.associatePdbWithSeq(selectedPdbFileName,
1144 DataSourceType.FILE, selectedSequence, true);
1146 sViewer = StructureViewer.launchStructureViewer(ap, new PDBEntry[] { fileEntry },
1147 new SequenceI[] { selectedSequence }, superimpose, theViewer,
1150 SwingUtilities.invokeLater(new Runnable()
1155 closeAction(preferredHeight);
1156 mainFrame.dispose();
1161 Thread runner = new Thread(viewStruc);
1163 if (waitUntilFinished)
1165 while (sViewer == null ? runner.isAlive()
1166 : (sViewer.sview == null ? true
1167 : !sViewer.sview.hasMapping()))
1172 } catch (InterruptedException ie)
1181 * Answers a structure viewer (new or existing) configured to superimpose
1182 * added structures or not according to the user's choice
1187 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1189 Object sv = targetView.getSelectedItem();
1191 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1195 * Populates the combo-box used in associating manually fetched structures to
1196 * a unique sequence when more than one sequence selection is made.
1199 protected void populateCmbAssociateSeqOptions(
1200 JComboBox<AssociateSeqOptions> cmb_assSeq,
1201 JLabel lbl_associateSeq)
1203 cmb_assSeq.removeAllItems();
1205 new AssociateSeqOptions("-Select Associated Seq-", null));
1206 lbl_associateSeq.setVisible(false);
1207 if (selectedSequences.length > 1)
1209 for (SequenceI seq : selectedSequences)
1211 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1216 String seqName = selectedSequence.getDisplayId(false);
1217 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1218 lbl_associateSeq.setText(seqName);
1219 lbl_associateSeq.setVisible(true);
1220 cmb_assSeq.setVisible(false);
1224 protected boolean isStructuresDiscovered()
1226 return discoveredStructuresSet != null
1227 && !discoveredStructuresSet.isEmpty();
1230 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1232 // Doing a search for "1" or "1c" is valuable?
1233 // Those work but are enormously slow.
1236 protected void txt_search_ActionPerformed()
1238 String text = txt_search.getText().trim();
1239 if (text.length() >= PDB_ID_MIN)
1246 errorWarning.setLength(0);
1247 isValidPBDEntry = false;
1248 if (text.length() > 0)
1250 // TODO move this pdb id search into the PDB specific
1252 // for moment, it will work fine as is because it is self-contained
1253 String searchTerm = text.toLowerCase(Locale.ROOT);
1254 searchTerm = searchTerm.split(":")[0];
1255 // System.out.println(">>>>> search term : " + searchTerm);
1256 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1257 FTSRestRequest pdbRequest = new FTSRestRequest();
1258 pdbRequest.setAllowEmptySeq(false);
1259 pdbRequest.setResponseSize(1);
1260 pdbRequest.setFieldToSearchBy("(pdb_id:");
1261 pdbRequest.setWantedFields(wantedFields);
1262 pdbRequest.setSearchTerm(searchTerm + ")");
1263 pdbRequest.setAssociatedSequence(selectedSequence);
1264 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1265 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1266 FTSRestResponse resultList;
1269 resultList = pdbRestClient.executeRequest(pdbRequest);
1270 } catch (Exception e)
1272 errorWarning.append(e.getMessage());
1276 validateSelections();
1278 if (resultList.getSearchSummary() != null
1279 && resultList.getSearchSummary().size() > 0)
1281 isValidPBDEntry = true;
1284 validateSelections();
1290 protected void tabRefresh()
1292 if (selectedSequences != null)
1294 lbl_loading.setVisible(true);
1295 Thread refreshThread = new Thread(new Runnable()
1300 fetchStructuresMetaData();
1301 // populateFilterComboBox(true, cachedPDBExists);
1304 ((FilterOption) cmb_filterOption.getSelectedItem())
1306 lbl_loading.setVisible(false);
1309 refreshThread.start();
1313 public class PDBEntryTableModel extends AbstractTableModel
1315 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1318 private List<CachedPDB> pdbEntries;
1320 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1322 this.pdbEntries = new ArrayList<>(pdbEntries);
1326 public String getColumnName(int columnIndex)
1328 return columns[columnIndex];
1332 public int getRowCount()
1334 return pdbEntries.size();
1338 public int getColumnCount()
1340 return columns.length;
1344 public boolean isCellEditable(int row, int column)
1350 public Object getValueAt(int rowIndex, int columnIndex)
1352 Object value = "??";
1353 CachedPDB entry = pdbEntries.get(rowIndex);
1354 switch (columnIndex)
1357 value = entry.getSequence();
1360 value = entry.getQualifiedId();
1363 value = entry.getPdbEntry().getChainCode() == null ? "_"
1364 : entry.getPdbEntry().getChainCode();
1367 value = entry.getPdbEntry().getType();
1370 value = entry.getPdbEntry().getFile();
1377 public Class<?> getColumnClass(int columnIndex)
1379 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1382 public CachedPDB getPDBEntryAt(int row)
1384 return pdbEntries.get(row);
1389 private class CachedPDB
1391 private SequenceI sequence;
1393 private PDBEntry pdbEntry;
1395 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1397 this.sequence = sequence;
1398 this.pdbEntry = pdbEntry;
1401 public String getQualifiedId()
1403 if (pdbEntry.hasProvider())
1405 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1407 return pdbEntry.toString();
1410 public SequenceI getSequence()
1415 public PDBEntry getPdbEntry()
1422 private IProgressIndicator progressBar;
1425 public void setProgressBar(String message, long id)
1427 progressBar.setProgressBar(message, id);
1431 public void addProgressBar(long id, String message)
1433 progressBar.addProgressBar(id, message);
1437 public void removeProgressBar(long id)
1439 progressBar.removeProgressBar(id);
1443 public void registerHandler(long id, IProgressIndicatorHandler handler)
1445 progressBar.registerHandler(id, handler);
1449 public boolean operationInProgress()
1451 return progressBar.operationInProgress();
1454 public JalviewStructureDisplayI getOpenedStructureViewer()
1456 return sViewer == null ? null : sViewer.sview;
1460 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1462 data.setDocFieldPrefs(newPrefs);
1468 * @return true when all initialisation threads have finished and dialog is
1471 public boolean isDialogVisible()
1473 return mainFrame != null && data != null && cmb_filterOption != null
1474 && mainFrame.isVisible()
1475 && cmb_filterOption.getSelectedItem() != null;
1479 * @return true if the 3D-Beacons query button will/has been displayed
1481 public boolean isCanQueryTDB()
1486 public boolean isNotQueriedTDBYet()
1488 return notQueriedTDBYet;