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;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashSet;
31 import java.util.LinkedHashSet;
32 import java.util.List;
33 import java.util.Locale;
34 import java.util.concurrent.Callable;
35 import java.util.concurrent.Executors;
37 import javax.swing.JCheckBox;
38 import javax.swing.JComboBox;
39 import javax.swing.JLabel;
40 import javax.swing.JMenuItem;
41 import javax.swing.JPopupMenu;
42 import javax.swing.JTable;
43 import javax.swing.SwingUtilities;
44 import javax.swing.table.AbstractTableModel;
46 import jalview.api.structures.JalviewStructureDisplayI;
47 import jalview.bin.Cache;
48 import jalview.bin.Console;
49 import jalview.bin.Jalview;
50 import jalview.datamodel.PDBEntry;
51 import jalview.datamodel.SequenceI;
52 import jalview.fts.api.FTSData;
53 import jalview.fts.api.FTSDataColumnI;
54 import jalview.fts.api.FTSRestClientI;
55 import jalview.fts.core.FTSDataColumnPreferences;
56 import jalview.fts.core.FTSRestRequest;
57 import jalview.fts.core.FTSRestResponse;
58 import jalview.fts.service.pdb.PDBFTSRestClient;
59 import jalview.fts.service.threedbeacons.TDB_FTSData;
60 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
61 import jalview.gui.structurechooser.StructureChooserQuerySource;
62 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
63 import jalview.io.DataSourceType;
64 import jalview.jbgui.FilterOption;
65 import jalview.jbgui.GStructureChooser;
66 import jalview.structure.StructureMapping;
67 import jalview.structure.StructureSelectionManager;
68 import jalview.util.MessageManager;
69 import jalview.util.Platform;
70 import jalview.ws.DBRefFetcher;
71 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
72 import jalview.ws.seqfetcher.DbSourceProxy;
73 import jalview.ws.sifts.SiftsSettings;
76 * Provides the behaviors for the Structure chooser Panel
81 @SuppressWarnings("serial")
82 public class StructureChooser extends GStructureChooser
83 implements IProgressIndicator
85 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
88 * warn user if need to fetch more than this many uniprot records at once
90 private static final int THRESHOLD_WARN_UNIPROT_FETCH_NEEDED = 20;
92 private SequenceI selectedSequence;
94 private SequenceI[] selectedSequences;
96 private IProgressIndicator progressIndicator;
98 private Collection<FTSData> discoveredStructuresSet;
100 private StructureChooserQuerySource data;
103 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
105 return data.getDocFieldPrefs();
108 private String selectedPdbFileName;
110 private boolean isValidPBDEntry;
112 private boolean cachedPDBExists;
114 private Collection<FTSData> lastDiscoveredStructuresSet;
116 private boolean canQueryTDB = false;
118 private boolean notQueriedTDBYet = true;
120 List<SequenceI> seqsWithoutSourceDBRef = null;
122 private boolean showChooserGUI = true;
124 private static StructureViewer lastTargetedView = null;
126 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
129 this(selectedSeqs, selectedSeq, ap, true);
132 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
133 AlignmentPanel ap, boolean showGUI)
135 // which FTS engine to use
136 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
140 this.selectedSequence = selectedSeq;
141 this.selectedSequences = selectedSeqs;
142 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
143 this.showChooserGUI = showGUI;
149 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
150 * least one structure are discovered.
152 private void populateSeqsWithoutSourceDBRef()
154 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
155 boolean needCanonical = false;
156 for (SequenceI seq : selectedSequences)
160 int dbRef = ThreeDBStructureChooserQuerySource
161 .checkUniprotRefs(seq.getDBRefs());
166 // need to retrieve canonicals
167 needCanonical = true;
168 seqsWithoutSourceDBRef.add(seq);
172 // could be a sequence with pdb ref
173 if (seq.getAllPDBEntries() == null
174 || seq.getAllPDBEntries().size() == 0)
176 seqsWithoutSourceDBRef.add(seq);
182 // retrieve database refs for protein sequences
183 if (!seqsWithoutSourceDBRef.isEmpty())
188 // triggers display of the 'Query TDB' button
189 notQueriedTDBYet = true;
195 * Initializes parameters used by the Structure Chooser Panel
197 protected void init()
199 if (!Jalview.isHeadlessMode())
201 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
204 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
205 btn_queryTDB.addActionListener(new ActionListener()
209 public void actionPerformed(ActionEvent e)
211 promptForTDBFetch(false);
215 Executors.defaultThreadFactory().newThread(new Runnable()
220 populateSeqsWithoutSourceDBRef();
221 initialStructureDiscovery();
229 private void initialStructureDiscovery()
231 // check which FTS engine to use
232 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
234 // ensure a filter option is in force for search
235 populateFilterComboBox(true, cachedPDBExists);
237 // looks for any existing structures already loaded
238 // for the sequences (the cached ones)
239 // then queries the StructureChooserQuerySource to
240 // discover more structures.
242 // Possible optimisation is to only begin querying
243 // the structure chooser if there are no cached structures.
245 long startTime = System.currentTimeMillis();
246 updateProgressIndicator(
247 MessageManager.getString("status.loading_cached_pdb_entries"),
249 loadLocalCachedPDBEntries();
250 updateProgressIndicator(null, startTime);
251 updateProgressIndicator(
252 MessageManager.getString("status.searching_for_pdb_structures"),
254 fetchStructuresMetaData();
255 // revise filter options if no results were found
256 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
257 discoverStructureViews();
258 updateProgressIndicator(null, startTime);
259 mainFrame.setVisible(showChooserGUI);
264 * raises dialog for Uniprot fetch followed by 3D beacons search
267 * - when true, don't ask, just fetch
269 public void promptForTDBFetch(boolean ignoreGui)
271 final long progressId = System.currentTimeMillis();
273 // final action after prompting and discovering db refs
274 final Runnable strucDiscovery = new Runnable()
279 mainFrame.setEnabled(false);
280 cmb_filterOption.setEnabled(false);
281 progressBar.setProgressBar(
282 MessageManager.getString("status.searching_3d_beacons"),
284 btn_queryTDB.setEnabled(false);
285 // TODO: warn if no accessions discovered
286 populateSeqsWithoutSourceDBRef();
287 // redo initial discovery - this time with 3d beacons
289 previousWantedFields = null;
290 lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
291 cmb_filterOption.setSelectedItem(null);
292 cachedPDBExists = false; // reset to initial
293 initialStructureDiscovery();
294 if (!isStructuresDiscovered())
296 progressBar.setProgressBar(MessageManager.getString(
297 "status.no_structures_discovered_from_3d_beacons"),
299 btn_queryTDB.setToolTipText(MessageManager.getString(
300 "status.no_structures_discovered_from_3d_beacons"));
301 btn_queryTDB.setEnabled(false);
302 pnl_queryTDB.setVisible(false);
306 cmb_filterOption.setSelectedIndex(0); // select 'best'
307 btn_queryTDB.setVisible(false);
308 pnl_queryTDB.setVisible(false);
309 progressBar.setProgressBar(null, progressId);
311 mainFrame.setEnabled(true);
312 cmb_filterOption.setEnabled(true);
316 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
320 public void finished()
322 // filter has been selected, so we set flag to remove ourselves
323 notQueriedTDBYet = false;
324 // new thread to discover structures - via 3d beacons
325 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
330 // fetch db refs if OK pressed
331 final Callable discoverCanonicalDBrefs = () -> {
332 btn_queryTDB.setEnabled(false);
333 populateSeqsWithoutSourceDBRef();
335 final int y = seqsWithoutSourceDBRef.size();
338 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
339 .toArray(new SequenceI[y]);
340 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
341 progressBar, new DbSourceProxy[]
342 { new jalview.ws.dbsources.Uniprot() }, null, false);
343 dbRefFetcher.addListener(afterDbRefFetch);
344 // ideally this would also gracefully run with callbacks
346 dbRefFetcher.fetchDBRefs(true);
350 // call finished action directly
351 afterDbRefFetch.finished();
355 final Callable revertview = () -> {
356 if (lastSelected != null)
358 cmb_filterOption.setSelectedItem(lastSelected);
362 int threshold = Cache.getDefault("UNIPROT_AUTOFETCH_THRESHOLD",
363 THRESHOLD_WARN_UNIPROT_FETCH_NEEDED);
364 Console.debug("Using Uniprot fetch threshold of " + threshold);
365 if (ignoreGui || seqsWithoutSourceDBRef.size() < threshold)
367 Executors.newSingleThreadExecutor().submit(discoverCanonicalDBrefs);
370 // need cancel and no to result in the discoverPDB action - mocked is
371 // 'cancel' TODO: mock should be OK
373 StructureChooser thisSC = this;
374 JvOptionPane.newOptionDialog(thisSC.getFrame())
375 .setResponseHandler(JvOptionPane.OK_OPTION,
376 discoverCanonicalDBrefs)
377 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
378 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
380 MessageManager.formatMessage(
381 "label.fetch_references_for_3dbeacons",
382 seqsWithoutSourceDBRef.size()),
383 MessageManager.getString("label.3dbeacons"),
384 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
386 { MessageManager.getString("action.ok"),
387 MessageManager.getString("action.cancel") },
388 MessageManager.getString("action.ok"), false);
392 * Builds a drop-down choice list of existing structure viewers to which new
393 * structures may be added. If this list is empty then it, and the 'Add'
394 * button, are hidden.
396 private void discoverStructureViews()
398 if (Desktop.instance != null)
400 targetView.removeAllItems();
401 if (lastTargetedView != null && !lastTargetedView.isVisible())
403 lastTargetedView = null;
405 int linkedViewsAt = 0;
406 for (StructureViewerBase view : Desktop.instance
407 .getStructureViewers(null, null))
409 StructureViewer viewHandler = (lastTargetedView != null
410 && lastTargetedView.sview == view) ? lastTargetedView
411 : StructureViewer.reconfigure(view);
413 if (view.isLinkedWith(ap))
415 targetView.insertItemAt(viewHandler, linkedViewsAt++);
419 targetView.addItem(viewHandler);
424 * show option to Add to viewer if at least 1 viewer found
426 targetView.setVisible(false);
427 if (targetView.getItemCount() > 0)
429 targetView.setVisible(true);
430 if (lastTargetedView != null)
432 targetView.setSelectedItem(lastTargetedView);
436 targetView.setSelectedIndex(0);
439 btn_add.setVisible(targetView.isVisible());
444 * Updates the progress indicator with the specified message
447 * displayed message for the operation
449 * unique handle for this indicator
451 protected void updateProgressIndicator(String message, long id)
453 if (progressIndicator != null)
455 progressIndicator.setProgressBar(message, id);
460 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
463 void fetchStructuresMetaData()
465 long startTime = System.currentTimeMillis();
466 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
467 .getStructureSummaryFields();
469 discoveredStructuresSet = new LinkedHashSet<>();
470 HashSet<String> errors = new HashSet<>();
472 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
475 for (SequenceI seq : selectedSequences)
478 FTSRestResponse resultList;
481 resultList = data.fetchStructuresMetaData(seq, wantedFields,
482 selectedFilterOpt, !chk_invertFilter.isSelected());
483 // null response means the FTSengine didn't yield a query for this
484 // consider designing a special exception if we really wanted to be
486 if (resultList == null)
490 } catch (Exception e)
493 errors.add(e.getMessage());
496 if (resultList.getSearchSummary() != null
497 && !resultList.getSearchSummary().isEmpty())
499 discoveredStructuresSet.addAll(resultList.getSearchSummary());
503 int noOfStructuresFound = 0;
504 String totalTime = (System.currentTimeMillis() - startTime)
506 if (discoveredStructuresSet != null
507 && !discoveredStructuresSet.isEmpty())
510 .setModel(data.getTableModel(discoveredStructuresSet));
512 noOfStructuresFound = discoveredStructuresSet.size();
513 lastDiscoveredStructuresSet = discoveredStructuresSet;
514 mainFrame.setTitle(MessageManager.formatMessage(
515 "label.structure_chooser_no_of_structures",
516 noOfStructuresFound, totalTime));
520 mainFrame.setTitle(MessageManager
521 .getString("label.structure_chooser_manual_association"));
522 if (errors.size() > 0)
524 StringBuilder errorMsg = new StringBuilder();
525 for (String error : errors)
527 errorMsg.append(error).append("\n");
529 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
530 MessageManager.getString("label.pdb_web-service_error"),
531 JvOptionPane.ERROR_MESSAGE);
536 protected void loadLocalCachedPDBEntries()
538 ArrayList<CachedPDB> entries = new ArrayList<>();
539 for (SequenceI seq : selectedSequences)
541 if (seq.getDatasetSequence() != null
542 && seq.getDatasetSequence().getAllPDBEntries() != null)
544 for (PDBEntry pdbEntry : seq.getDatasetSequence()
547 if (pdbEntry.getFile() != null)
549 entries.add(new CachedPDB(seq, pdbEntry));
554 cachedPDBExists = !entries.isEmpty();
555 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
556 tbl_local_pdb.setModel(tableModelx);
560 * Filters a given list of discovered structures based on supplied argument
562 * @param fieldToFilterBy
563 * the field to filter by
565 void filterResultSet(final String fieldToFilterBy)
567 Thread filterThread = new Thread(new Runnable()
573 long startTime = System.currentTimeMillis();
574 lbl_loading.setVisible(true);
575 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
576 .getStructureSummaryFields();
577 Collection<FTSData> filteredResponse = new HashSet<>();
578 HashSet<String> errors = new HashSet<>();
580 for (SequenceI seq : selectedSequences)
583 FTSRestResponse resultList;
586 resultList = data.selectFirstRankedQuery(seq,
587 discoveredStructuresSet, wantedFields, fieldToFilterBy,
588 !chk_invertFilter.isSelected());
590 } catch (Exception e)
593 errors.add(e.getMessage());
596 if (resultList.getSearchSummary() != null
597 && !resultList.getSearchSummary().isEmpty())
599 filteredResponse.addAll(resultList.getSearchSummary());
603 String totalTime = (System.currentTimeMillis() - startTime)
605 if (!filteredResponse.isEmpty())
607 final int filterResponseCount = filteredResponse.size();
608 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
609 reorderedStructuresSet.addAll(filteredResponse);
610 reorderedStructuresSet.addAll(discoveredStructuresSet);
612 .setModel(data.getTableModel(reorderedStructuresSet));
614 FTSRestResponse.configureTableColumn(getResultTable(),
615 wantedFields, tempUserPrefs);
616 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
617 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
618 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
619 // Update table selection model here
620 getResultTable().addRowSelectionInterval(0,
621 filterResponseCount - 1);
622 mainFrame.setTitle(MessageManager.formatMessage(
623 "label.structure_chooser_filter_time", totalTime));
627 mainFrame.setTitle(MessageManager.formatMessage(
628 "label.structure_chooser_filter_time", totalTime));
629 if (errors.size() > 0)
631 StringBuilder errorMsg = new StringBuilder();
632 for (String error : errors)
634 errorMsg.append(error).append("\n");
636 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
637 MessageManager.getString("label.pdb_web-service_error"),
638 JvOptionPane.ERROR_MESSAGE);
642 lbl_loading.setVisible(false);
644 validateSelections();
647 filterThread.start();
651 * Handles action event for btn_pdbFromFile
654 protected void pdbFromFile_actionPerformed()
656 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
659 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
660 Cache.getProperty("LAST_DIRECTORY"));
661 chooser.setFileView(new jalview.io.JalviewFileView());
662 chooser.setDialogTitle(
663 MessageManager.formatMessage("label.select_pdb_file_for",
664 selectedSequence.getDisplayId(false)));
665 chooser.setToolTipText(MessageManager.formatMessage(
666 "label.load_pdb_file_associate_with_sequence",
667 selectedSequence.getDisplayId(false)));
669 int value = chooser.showOpenDialog(null);
670 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
672 selectedPdbFileName = chooser.getSelectedFile().getPath();
673 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
674 validateSelections();
679 * Populates the filter combo-box options dynamically depending on discovered
682 protected void populateFilterComboBox(boolean haveData,
683 boolean cachedPDBExist)
685 populateFilterComboBox(haveData, cachedPDBExist, null);
689 * Populates the filter combo-box options dynamically depending on discovered
692 protected void populateFilterComboBox(boolean haveData,
693 boolean cachedPDBExist, FilterOption lastSel)
697 * temporarily suspend the change listener behaviour
699 cmb_filterOption.removeItemListener(this);
701 cmb_filterOption.removeAllItems();
704 List<FilterOption> filters = data
705 .getAvailableFilterOptions(VIEWS_FILTER);
706 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
707 lastDiscoveredStructuresSet);
709 for (FilterOption filter : filters)
711 if (lastSel != null && filter.equals(lastSel))
716 cmb_filterOption.addItem(filter);
720 cmb_filterOption.addItem(
721 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
722 "-", VIEWS_ENTER_ID, false, null));
723 cmb_filterOption.addItem(
724 new FilterOption(MessageManager.getString("label.from_file"),
725 "-", VIEWS_FROM_FILE, false, null));
726 if (canQueryTDB && notQueriedTDBYet)
728 btn_queryTDB.setVisible(true);
729 pnl_queryTDB.setVisible(true);
734 FilterOption cachedOption = new FilterOption(
735 MessageManager.getString("label.cached_structures"), "-",
736 VIEWS_LOCAL_PDB, false, null);
737 cmb_filterOption.addItem(cachedOption);
740 cmb_filterOption.setSelectedItem(cachedOption);
745 cmb_filterOption.setSelectedIndex(selSet);
747 cmb_filterOption.addItemListener(this);
751 * Updates the displayed view based on the selected filter option
753 protected void updateCurrentView()
755 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
758 if (lastSelected == selectedFilterOpt)
760 // don't need to do anything, probably
763 // otherwise, record selection
764 // and update the layout and dialog accordingly
765 lastSelected = selectedFilterOpt;
767 layout_switchableViews.show(pnl_switchableViews,
768 selectedFilterOpt.getView());
769 String filterTitle = mainFrame.getTitle();
770 mainFrame.setTitle(frameTitle);
771 chk_invertFilter.setVisible(false);
773 if (selectedFilterOpt.getView() == VIEWS_FILTER)
775 mainFrame.setTitle(filterTitle);
776 // TDB Query has no invert as yet
777 chk_invertFilter.setVisible(selectedFilterOpt
778 .getQuerySource() instanceof PDBStructureChooserQuerySource);
780 if (data != selectedFilterOpt.getQuerySource()
781 || data.needsRefetch(selectedFilterOpt))
783 data = selectedFilterOpt.getQuerySource();
784 // rebuild the views completely, since prefs will also change
790 filterResultSet(selectedFilterOpt.getValue());
793 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
794 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
796 mainFrame.setTitle(MessageManager
797 .getString("label.structure_chooser_manual_association"));
798 idInputAssSeqPanel.loadCmbAssSeq();
799 fileChooserAssSeqPanel.loadCmbAssSeq();
801 validateSelections();
805 * Validates user selection and enables the 'Add' and 'New View' buttons if
806 * all parameters are correct (the Add button will only be visible if there is
807 * at least one existing structure viewer open). This basically means at least
808 * one structure selected and no error messages.
810 * The 'Superpose Structures' option is enabled if either more than one
811 * structure is selected, or the 'Add' to existing view option is enabled, and
812 * disabled if the only option is to open a new view of a single structure.
815 protected void validateSelections()
817 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
819 btn_add.setEnabled(false);
820 String currentView = selectedFilterOpt.getView();
821 int selectedCount = 0;
822 if (currentView == VIEWS_FILTER)
824 selectedCount = getResultTable().getSelectedRows().length;
825 if (selectedCount > 0)
827 btn_add.setEnabled(true);
830 else if (currentView == VIEWS_LOCAL_PDB)
832 selectedCount = tbl_local_pdb.getSelectedRows().length;
833 if (selectedCount > 0)
835 btn_add.setEnabled(true);
838 else if (currentView == VIEWS_ENTER_ID)
840 validateAssociationEnterPdb();
842 else if (currentView == VIEWS_FROM_FILE)
844 validateAssociationFromFile();
847 btn_newView.setEnabled(btn_add.isEnabled());
850 * enable 'Superpose' option if more than one structure is selected,
851 * or there are view(s) available to add structure(s) to
854 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
858 protected boolean showPopupFor(int selectedRow, int x, int y)
860 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
862 String currentView = selectedFilterOpt.getView();
864 if (currentView == VIEWS_FILTER
865 && data instanceof ThreeDBStructureChooserQuerySource)
868 TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
869 .getFTSDataFor(getResultTable(), selectedRow,
870 discoveredStructuresSet);
871 String pageUrl = row.getModelViewUrl();
872 JPopupMenu popup = new JPopupMenu("3D Beacons");
873 JMenuItem viewUrl = new JMenuItem("View model web page");
874 viewUrl.addActionListener(new ActionListener()
877 public void actionPerformed(ActionEvent e)
879 Desktop.showUrl(pageUrl);
883 SwingUtilities.invokeLater(new Runnable()
888 popup.show(getResultTable(), x, y);
893 // event not handled by us
898 * Validates inputs from the Manual PDB entry panel
900 protected void validateAssociationEnterPdb()
902 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
903 .getCmb_assSeq().getSelectedItem();
904 lbl_pdbManualFetchStatus.setIcon(errorImage);
905 lbl_pdbManualFetchStatus.setToolTipText("");
906 if (txt_search.getText().length() > 0)
908 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
909 MessageManager.formatMessage("info.no_pdb_entry_found_for",
910 txt_search.getText())));
913 if (errorWarning.length() > 0)
915 lbl_pdbManualFetchStatus.setIcon(warningImage);
916 lbl_pdbManualFetchStatus.setToolTipText(
917 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
920 if (selectedSequences.length == 1 || !assSeqOpt.getName()
921 .equalsIgnoreCase("-Select Associated Seq-"))
923 txt_search.setEnabled(true);
926 btn_add.setEnabled(true);
927 lbl_pdbManualFetchStatus.setToolTipText("");
928 lbl_pdbManualFetchStatus.setIcon(goodImage);
933 txt_search.setEnabled(false);
934 lbl_pdbManualFetchStatus.setIcon(errorImage);
939 * Validates inputs for the manual PDB file selection options
941 protected void validateAssociationFromFile()
943 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
944 .getCmb_assSeq().getSelectedItem();
945 lbl_fromFileStatus.setIcon(errorImage);
946 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
947 .getName().equalsIgnoreCase("-Select Associated Seq-")))
949 btn_pdbFromFile.setEnabled(true);
950 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
952 btn_add.setEnabled(true);
953 lbl_fromFileStatus.setIcon(goodImage);
958 btn_pdbFromFile.setEnabled(false);
959 lbl_fromFileStatus.setIcon(errorImage);
964 protected void cmbAssSeqStateChanged()
966 validateSelections();
969 private FilterOption lastSelected = null;
972 * Handles the state change event for the 'filter' combo-box and 'invert'
976 protected void stateChanged(ItemEvent e)
978 if (e.getSource() instanceof JCheckBox)
984 if (e.getStateChange() == ItemEvent.SELECTED)
993 * select structures for viewing by their PDB IDs
996 * @return true if structures were found and marked as selected
998 public boolean selectStructure(String... pdbids)
1000 boolean found = false;
1002 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1003 .getSelectedItem());
1004 String currentView = selectedFilterOpt.getView();
1005 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1006 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
1008 if (restable == null)
1010 // can't select (enter PDB ID, or load file - need to also select which
1011 // sequence to associate with)
1015 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
1016 for (int r = 0; r < restable.getRowCount(); r++)
1018 for (int p = 0; p < pdbids.length; p++)
1020 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1021 .equalsIgnoreCase(pdbids[p]))
1023 restable.setRowSelectionInterval(r, r);
1032 * Handles the 'New View' action
1035 protected void newView_ActionPerformed()
1037 targetView.setSelectedItem(null);
1038 showStructures(false);
1042 * Handles the 'Add to existing viewer' action
1045 protected void add_ActionPerformed()
1047 showStructures(false);
1051 * structure viewer opened by this dialog, or null
1053 private StructureViewer sViewer = null;
1055 public void showStructures(boolean waitUntilFinished)
1058 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1060 final int preferredHeight = pnl_filter.getHeight();
1062 Runnable viewStruc = new Runnable()
1067 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1068 .getSelectedItem());
1069 String currentView = selectedFilterOpt.getView();
1070 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1073 if (currentView == VIEWS_FILTER)
1075 int[] selectedRows = restable.getSelectedRows();
1076 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1077 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1078 pdbEntriesToView = data.collectSelectedRows(restable,
1079 selectedRows, selectedSeqsToView);
1081 SequenceI[] selectedSeqs = selectedSeqsToView
1082 .toArray(new SequenceI[selectedSeqsToView.size()]);
1083 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1086 else if (currentView == VIEWS_LOCAL_PDB)
1088 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1089 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1091 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1093 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1095 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1096 for (int row : selectedRows)
1098 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1099 .getModel()).getPDBEntryAt(row).getPdbEntry();
1101 pdbEntriesToView[count++] = pdbEntry;
1102 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1103 .getValueAt(row, refSeqColIndex);
1104 selectedSeqsToView.add(selectedSeq);
1106 SequenceI[] selectedSeqs = selectedSeqsToView
1107 .toArray(new SequenceI[selectedSeqsToView.size()]);
1108 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1111 else if (currentView == VIEWS_ENTER_ID)
1113 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1114 .getCmb_assSeq().getSelectedItem()).getSequence();
1115 if (userSelectedSeq != null)
1117 selectedSequence = userSelectedSeq;
1119 String pdbIdStr = txt_search.getText();
1120 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1121 if (pdbEntry == null)
1123 pdbEntry = new PDBEntry();
1124 if (pdbIdStr.split(":").length > 1)
1126 pdbEntry.setId(pdbIdStr.split(":")[0]);
1127 pdbEntry.setChainCode(
1128 pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1132 pdbEntry.setId(pdbIdStr);
1134 pdbEntry.setType(PDBEntry.Type.PDB);
1135 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1138 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1139 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1141 { selectedSequence });
1143 else if (currentView == VIEWS_FROM_FILE)
1145 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1146 .getCmb_assSeq().getSelectedItem()).getSequence();
1147 if (userSelectedSeq != null)
1149 selectedSequence = userSelectedSeq;
1151 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1152 .associatePdbWithSeq(selectedPdbFileName,
1153 DataSourceType.FILE, selectedSequence, true,
1156 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1158 { selectedSequence });
1160 SwingUtilities.invokeLater(new Runnable()
1165 closeAction(preferredHeight);
1166 mainFrame.dispose();
1171 Thread runner = new Thread(viewStruc);
1173 if (waitUntilFinished)
1175 while (sViewer == null ? runner.isAlive()
1176 : (sViewer.sview == null ? true
1177 : !sViewer.sview.hasMapping()))
1182 } catch (InterruptedException ie)
1191 * Answers a structure viewer (new or existing) configured to superimpose
1192 * added structures or not according to the user's choice
1197 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1199 Object sv = targetView.getSelectedItem();
1201 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1205 * Adds PDB structures to a new or existing structure viewer
1208 * @param pdbEntriesToView
1213 private StructureViewer launchStructureViewer(
1214 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1215 final AlignmentPanel alignPanel, SequenceI[] sequences)
1217 long progressId = sequences.hashCode();
1218 setProgressBar(MessageManager
1219 .getString("status.launching_3d_structure_viewer"), progressId);
1220 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1221 boolean superimpose = chk_superpose.isSelected();
1222 theViewer.setSuperpose(superimpose);
1225 * remember user's choice of superimpose or not
1227 Cache.setProperty(AUTOSUPERIMPOSE,
1228 Boolean.valueOf(superimpose).toString());
1230 setProgressBar(null, progressId);
1231 if (SiftsSettings.isMapWithSifts())
1233 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1235 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1236 // real PDB ID. For moment, we can also safely do this if there is already
1237 // a known mapping between the PDBEntry and the sequence.
1238 for (SequenceI seq : sequences)
1240 PDBEntry pdbe = pdbEntriesToView[p++];
1241 if (pdbe != null && pdbe.getFile() != null)
1243 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1244 if (smm != null && smm.length > 0)
1246 for (StructureMapping sm : smm)
1248 if (sm.getSequence() == seq)
1255 if (seq.getPrimaryDBRefs().isEmpty())
1257 seqsWithoutSourceDBRef.add(seq);
1261 if (!seqsWithoutSourceDBRef.isEmpty())
1263 int y = seqsWithoutSourceDBRef.size();
1264 setProgressBar(MessageManager.formatMessage(
1265 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1267 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1268 .toArray(new SequenceI[y]);
1269 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1270 dbRefFetcher.fetchDBRefs(true);
1272 setProgressBar("Fetch complete.", progressId); // todo i18n
1275 if (pdbEntriesToView.length > 1)
1278 MessageManager.getString(
1279 "status.fetching_3d_structures_for_selected_entries"),
1281 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1285 setProgressBar(MessageManager.formatMessage(
1286 "status.fetching_3d_structures_for",
1287 pdbEntriesToView[0].getId()), progressId);
1288 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1290 setProgressBar(null, progressId);
1291 // remember the last viewer we used...
1292 lastTargetedView = theViewer;
1297 * Populates the combo-box used in associating manually fetched structures to
1298 * a unique sequence when more than one sequence selection is made.
1301 protected void populateCmbAssociateSeqOptions(
1302 JComboBox<AssociateSeqOptions> cmb_assSeq,
1303 JLabel lbl_associateSeq)
1305 cmb_assSeq.removeAllItems();
1307 new AssociateSeqOptions("-Select Associated Seq-", null));
1308 lbl_associateSeq.setVisible(false);
1309 if (selectedSequences.length > 1)
1311 for (SequenceI seq : selectedSequences)
1313 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1318 String seqName = selectedSequence.getDisplayId(false);
1319 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1320 lbl_associateSeq.setText(seqName);
1321 lbl_associateSeq.setVisible(true);
1322 cmb_assSeq.setVisible(false);
1326 protected boolean isStructuresDiscovered()
1328 return discoveredStructuresSet != null
1329 && !discoveredStructuresSet.isEmpty();
1332 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1334 // Doing a search for "1" or "1c" is valuable?
1335 // Those work but are enormously slow.
1338 protected void txt_search_ActionPerformed()
1340 String text = txt_search.getText().trim();
1341 if (text.length() >= PDB_ID_MIN)
1348 errorWarning.setLength(0);
1349 isValidPBDEntry = false;
1350 if (text.length() > 0)
1352 // TODO move this pdb id search into the PDB specific
1354 // for moment, it will work fine as is because it is self-contained
1355 String searchTerm = text.toLowerCase(Locale.ROOT);
1356 searchTerm = searchTerm.split(":")[0];
1357 // System.out.println(">>>>> search term : " + searchTerm);
1358 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1359 FTSRestRequest pdbRequest = new FTSRestRequest();
1360 pdbRequest.setAllowEmptySeq(false);
1361 pdbRequest.setResponseSize(1);
1362 pdbRequest.setFieldToSearchBy("(pdb_id:");
1363 pdbRequest.setWantedFields(wantedFields);
1364 pdbRequest.setSearchTerm(searchTerm + ")");
1365 pdbRequest.setAssociatedSequence(selectedSequence);
1366 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1367 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1368 FTSRestResponse resultList;
1371 resultList = pdbRestClient.executeRequest(pdbRequest);
1372 } catch (Exception e)
1374 errorWarning.append(e.getMessage());
1378 validateSelections();
1380 if (resultList.getSearchSummary() != null
1381 && resultList.getSearchSummary().size() > 0)
1383 isValidPBDEntry = true;
1386 validateSelections();
1392 protected void tabRefresh()
1394 if (selectedSequences != null)
1396 lbl_loading.setVisible(true);
1397 Thread refreshThread = new Thread(new Runnable()
1402 fetchStructuresMetaData();
1403 // populateFilterComboBox(true, cachedPDBExists);
1406 ((FilterOption) cmb_filterOption.getSelectedItem())
1408 lbl_loading.setVisible(false);
1411 refreshThread.start();
1415 public class PDBEntryTableModel extends AbstractTableModel
1417 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1420 private List<CachedPDB> pdbEntries;
1422 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1424 this.pdbEntries = new ArrayList<>(pdbEntries);
1428 public String getColumnName(int columnIndex)
1430 return columns[columnIndex];
1434 public int getRowCount()
1436 return pdbEntries.size();
1440 public int getColumnCount()
1442 return columns.length;
1446 public boolean isCellEditable(int row, int column)
1452 public Object getValueAt(int rowIndex, int columnIndex)
1454 Object value = "??";
1455 CachedPDB entry = pdbEntries.get(rowIndex);
1456 switch (columnIndex)
1459 value = entry.getSequence();
1462 value = entry.getQualifiedId();
1465 value = entry.getPdbEntry().getChainCode() == null ? "_"
1466 : entry.getPdbEntry().getChainCode();
1469 value = entry.getPdbEntry().getType();
1472 value = entry.getPdbEntry().getFile();
1479 public Class<?> getColumnClass(int columnIndex)
1481 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1484 public CachedPDB getPDBEntryAt(int row)
1486 return pdbEntries.get(row);
1491 private class CachedPDB
1493 private SequenceI sequence;
1495 private PDBEntry pdbEntry;
1497 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1499 this.sequence = sequence;
1500 this.pdbEntry = pdbEntry;
1503 public String getQualifiedId()
1505 if (pdbEntry.hasProvider())
1507 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1509 return pdbEntry.toString();
1512 public SequenceI getSequence()
1517 public PDBEntry getPdbEntry()
1524 private IProgressIndicator progressBar;
1527 public void setProgressBar(String message, long id)
1529 if (!Platform.isHeadless())
1530 progressBar.setProgressBar(message, id);
1534 public void registerHandler(long id, IProgressIndicatorHandler handler)
1536 progressBar.registerHandler(id, handler);
1540 public boolean operationInProgress()
1542 return progressBar.operationInProgress();
1545 public JalviewStructureDisplayI getOpenedStructureViewer()
1547 return sViewer == null ? null : sViewer.sview;
1551 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1553 data.setDocFieldPrefs(newPrefs);
1559 * @return true when all initialisation threads have finished and dialog is
1562 public boolean isDialogVisible()
1564 return mainFrame != null && data != null && cmb_filterOption != null
1565 && mainFrame.isVisible()
1566 && cmb_filterOption.getSelectedItem() != null;
1571 * @return true if the 3D-Beacons query button will/has been displayed
1573 public boolean isCanQueryTDB()
1578 public boolean isNotQueriedTDBYet()
1580 return notQueriedTDBYet;
1584 * Open a single structure file for a given sequence
1586 public static void openStructureFileForSequence(AlignmentPanel ap,
1587 SequenceI seq, File sFile)
1589 //Open the chooser headlessly. Not sure this is actually needed ?
1590 StructureChooser sc = new StructureChooser(new SequenceI[] { seq }, seq,
1592 StructureSelectionManager ssm = ap.getStructureSelectionManager();
1593 PDBEntry fileEntry = null;
1596 fileEntry = new AssociatePdbFileWithSeq().associatePdbWithSeq(
1597 sFile.getAbsolutePath(), DataSourceType.FILE, seq, true,
1599 } catch (Exception e)
1601 Console.error("Could not open structure file '"
1602 + sFile.getAbsolutePath() + "'");
1606 StructureViewer sViewer = sc.launchStructureViewer(ssm,
1608 { fileEntry }, ap, new SequenceI[] { seq });
1610 sc.mainFrame.dispose();