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.io.JalviewFileChooser;
65 import jalview.io.JalviewFileView;
66 import jalview.jbgui.FilterOption;
67 import jalview.jbgui.GStructureChooser;
68 import jalview.structure.StructureImportSettings.TFType;
69 import jalview.structure.StructureMapping;
70 import jalview.structure.StructureSelectionManager;
71 import jalview.util.MessageManager;
72 import jalview.util.Platform;
73 import jalview.util.StringUtils;
74 import jalview.ws.DBRefFetcher;
75 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
76 import jalview.ws.seqfetcher.DbSourceProxy;
77 import jalview.ws.sifts.SiftsSettings;
80 * Provides the behaviors for the Structure chooser Panel
85 @SuppressWarnings("serial")
86 public class StructureChooser extends GStructureChooser
87 implements IProgressIndicator
89 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
92 * warn user if need to fetch more than this many uniprot records at once
94 private static final int THRESHOLD_WARN_UNIPROT_FETCH_NEEDED = 20;
96 private SequenceI selectedSequence;
98 private SequenceI[] selectedSequences;
100 private IProgressIndicator progressIndicator;
102 private Collection<FTSData> discoveredStructuresSet;
104 private StructureChooserQuerySource data;
107 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
109 return data.getDocFieldPrefs();
112 private String selectedPdbFileName;
114 private TFType localPdbTempfacType;
116 private String localPdbPaeMatrixFileName;
118 private boolean isValidPBDEntry;
120 private boolean cachedPDBExists;
122 private Collection<FTSData> lastDiscoveredStructuresSet;
124 private boolean canQueryTDB = false;
126 private boolean notQueriedTDBYet = true;
128 List<SequenceI> seqsWithoutSourceDBRef = null;
130 private boolean showChooserGUI = true;
132 private static StructureViewer lastTargetedView = null;
134 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
137 this(selectedSeqs, selectedSeq, ap, true);
140 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
141 AlignmentPanel ap, boolean showGUI)
143 // which FTS engine to use
144 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
148 this.selectedSequence = selectedSeq;
149 this.selectedSequences = selectedSeqs;
150 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
151 this.showChooserGUI = showGUI;
157 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
158 * least one structure are discovered.
160 private void populateSeqsWithoutSourceDBRef()
162 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
163 boolean needCanonical = false;
164 for (SequenceI seq : selectedSequences)
168 int dbRef = ThreeDBStructureChooserQuerySource
169 .checkUniprotRefs(seq.getDBRefs());
174 // need to retrieve canonicals
175 needCanonical = true;
176 seqsWithoutSourceDBRef.add(seq);
180 // could be a sequence with pdb ref
181 if (seq.getAllPDBEntries() == null
182 || seq.getAllPDBEntries().size() == 0)
184 seqsWithoutSourceDBRef.add(seq);
190 // retrieve database refs for protein sequences
191 if (!seqsWithoutSourceDBRef.isEmpty())
196 // triggers display of the 'Query TDB' button
197 notQueriedTDBYet = true;
203 * Initializes parameters used by the Structure Chooser Panel
205 protected void init()
207 if (!Jalview.isHeadlessMode())
209 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
212 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
213 btn_queryTDB.addActionListener(new ActionListener()
217 public void actionPerformed(ActionEvent e)
219 promptForTDBFetch(false);
223 Executors.defaultThreadFactory().newThread(new Runnable()
228 populateSeqsWithoutSourceDBRef();
229 initialStructureDiscovery();
237 private void initialStructureDiscovery()
239 // check which FTS engine to use
240 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
242 // ensure a filter option is in force for search
243 populateFilterComboBox(true, cachedPDBExists);
245 // looks for any existing structures already loaded
246 // for the sequences (the cached ones)
247 // then queries the StructureChooserQuerySource to
248 // discover more structures.
250 // Possible optimisation is to only begin querying
251 // the structure chooser if there are no cached structures.
253 long startTime = System.currentTimeMillis();
254 updateProgressIndicator(
255 MessageManager.getString("status.loading_cached_pdb_entries"),
257 loadLocalCachedPDBEntries();
258 updateProgressIndicator(null, startTime);
259 updateProgressIndicator(
260 MessageManager.getString("status.searching_for_pdb_structures"),
262 fetchStructuresMetaData();
263 // revise filter options if no results were found
264 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
265 discoverStructureViews();
266 updateProgressIndicator(null, startTime);
267 mainFrame.setVisible(showChooserGUI);
272 * raises dialog for Uniprot fetch followed by 3D beacons search
275 * - when true, don't ask, just fetch
277 public void promptForTDBFetch(boolean ignoreGui)
279 final long progressId = System.currentTimeMillis();
281 // final action after prompting and discovering db refs
282 final Runnable strucDiscovery = new Runnable()
287 mainFrame.setEnabled(false);
288 cmb_filterOption.setEnabled(false);
289 progressBar.setProgressBar(
290 MessageManager.getString("status.searching_3d_beacons"),
292 btn_queryTDB.setEnabled(false);
293 // TODO: warn if no accessions discovered
294 populateSeqsWithoutSourceDBRef();
295 // redo initial discovery - this time with 3d beacons
297 previousWantedFields = null;
298 lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
299 cmb_filterOption.setSelectedItem(null);
300 cachedPDBExists = false; // reset to initial
301 initialStructureDiscovery();
302 if (!isStructuresDiscovered())
304 progressBar.setProgressBar(MessageManager.getString(
305 "status.no_structures_discovered_from_3d_beacons"),
307 btn_queryTDB.setToolTipText(MessageManager.getString(
308 "status.no_structures_discovered_from_3d_beacons"));
309 btn_queryTDB.setEnabled(false);
310 pnl_queryTDB.setVisible(false);
314 cmb_filterOption.setSelectedIndex(0); // select 'best'
315 btn_queryTDB.setVisible(false);
316 pnl_queryTDB.setVisible(false);
317 progressBar.setProgressBar(null, progressId);
319 mainFrame.setEnabled(true);
320 cmb_filterOption.setEnabled(true);
324 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
328 public void finished()
330 // filter has been selected, so we set flag to remove ourselves
331 notQueriedTDBYet = false;
332 // new thread to discover structures - via 3d beacons
333 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
338 // fetch db refs if OK pressed
339 final Callable discoverCanonicalDBrefs = () -> {
340 btn_queryTDB.setEnabled(false);
341 populateSeqsWithoutSourceDBRef();
343 final int y = seqsWithoutSourceDBRef.size();
346 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
347 .toArray(new SequenceI[y]);
348 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
349 progressBar, new DbSourceProxy[]
350 { new jalview.ws.dbsources.Uniprot() }, null, false);
351 dbRefFetcher.addListener(afterDbRefFetch);
352 // ideally this would also gracefully run with callbacks
354 dbRefFetcher.fetchDBRefs(true);
358 // call finished action directly
359 afterDbRefFetch.finished();
363 final Callable revertview = () -> {
364 if (lastSelected != null)
366 cmb_filterOption.setSelectedItem(lastSelected);
370 int threshold = Cache.getDefault("UNIPROT_AUTOFETCH_THRESHOLD",
371 THRESHOLD_WARN_UNIPROT_FETCH_NEEDED);
372 Console.debug("Using Uniprot fetch threshold of " + threshold);
373 if (ignoreGui || seqsWithoutSourceDBRef.size() < threshold)
375 Executors.newSingleThreadExecutor().submit(discoverCanonicalDBrefs);
378 // need cancel and no to result in the discoverPDB action - mocked is
379 // 'cancel' TODO: mock should be OK
381 StructureChooser thisSC = this;
382 JvOptionPane.newOptionDialog(thisSC.getFrame())
383 .setResponseHandler(JvOptionPane.OK_OPTION,
384 discoverCanonicalDBrefs)
385 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
386 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
388 MessageManager.formatMessage(
389 "label.fetch_references_for_3dbeacons",
390 seqsWithoutSourceDBRef.size()),
391 MessageManager.getString("label.3dbeacons"),
392 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
394 { MessageManager.getString("action.ok"),
395 MessageManager.getString("action.cancel") },
396 MessageManager.getString("action.ok"), false);
400 * Builds a drop-down choice list of existing structure viewers to which new
401 * structures may be added. If this list is empty then it, and the 'Add'
402 * button, are hidden.
404 private void discoverStructureViews()
406 if (Desktop.instance != null)
408 targetView.removeAllItems();
409 if (lastTargetedView != null && !lastTargetedView.isVisible())
411 lastTargetedView = null;
413 int linkedViewsAt = 0;
414 for (StructureViewerBase view : Desktop.instance
415 .getStructureViewers(null, null))
417 StructureViewer viewHandler = (lastTargetedView != null
418 && lastTargetedView.sview == view) ? lastTargetedView
419 : StructureViewer.reconfigure(view);
421 if (view.isLinkedWith(ap))
423 targetView.insertItemAt(viewHandler, linkedViewsAt++);
427 targetView.addItem(viewHandler);
432 * show option to Add to viewer if at least 1 viewer found
434 targetView.setVisible(false);
435 if (targetView.getItemCount() > 0)
437 targetView.setVisible(true);
438 if (lastTargetedView != null)
440 targetView.setSelectedItem(lastTargetedView);
444 targetView.setSelectedIndex(0);
447 btn_add.setVisible(targetView.isVisible());
452 * Updates the progress indicator with the specified message
455 * displayed message for the operation
457 * unique handle for this indicator
459 protected void updateProgressIndicator(String message, long id)
461 if (progressIndicator != null)
463 progressIndicator.setProgressBar(message, id);
468 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
471 void fetchStructuresMetaData()
473 long startTime = System.currentTimeMillis();
474 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
475 .getStructureSummaryFields();
477 discoveredStructuresSet = new LinkedHashSet<>();
478 HashSet<String> errors = new HashSet<>();
480 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
483 for (SequenceI seq : selectedSequences)
486 FTSRestResponse resultList;
489 resultList = data.fetchStructuresMetaData(seq, wantedFields,
490 selectedFilterOpt, !chk_invertFilter.isSelected());
491 // null response means the FTSengine didn't yield a query for this
492 // consider designing a special exception if we really wanted to be
494 if (resultList == null)
498 } catch (Exception e)
501 errors.add(e.getMessage());
504 if (resultList.getSearchSummary() != null
505 && !resultList.getSearchSummary().isEmpty())
507 discoveredStructuresSet.addAll(resultList.getSearchSummary());
511 int noOfStructuresFound = 0;
512 String totalTime = (System.currentTimeMillis() - startTime)
514 if (discoveredStructuresSet != null
515 && !discoveredStructuresSet.isEmpty())
518 .setModel(data.getTableModel(discoveredStructuresSet));
520 noOfStructuresFound = discoveredStructuresSet.size();
521 lastDiscoveredStructuresSet = discoveredStructuresSet;
522 mainFrame.setTitle(MessageManager.formatMessage(
523 "label.structure_chooser_no_of_structures",
524 noOfStructuresFound, totalTime));
528 mainFrame.setTitle(MessageManager
529 .getString("label.structure_chooser_manual_association"));
530 if (errors.size() > 0)
532 StringBuilder errorMsg = new StringBuilder();
533 for (String error : errors)
535 errorMsg.append(error).append("\n");
537 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
538 MessageManager.getString("label.pdb_web-service_error"),
539 JvOptionPane.ERROR_MESSAGE);
544 protected void loadLocalCachedPDBEntries()
546 ArrayList<CachedPDB> entries = new ArrayList<>();
547 for (SequenceI seq : selectedSequences)
549 if (seq.getDatasetSequence() != null
550 && seq.getDatasetSequence().getAllPDBEntries() != null)
552 for (PDBEntry pdbEntry : seq.getDatasetSequence()
555 if (pdbEntry.getFile() != null)
557 entries.add(new CachedPDB(seq, pdbEntry));
562 cachedPDBExists = !entries.isEmpty();
563 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
564 tbl_local_pdb.setModel(tableModelx);
568 * Filters a given list of discovered structures based on supplied argument
570 * @param fieldToFilterBy
571 * the field to filter by
573 void filterResultSet(final String fieldToFilterBy)
575 Thread filterThread = new Thread(new Runnable()
581 long startTime = System.currentTimeMillis();
582 lbl_loading.setVisible(true);
583 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
584 .getStructureSummaryFields();
585 Collection<FTSData> filteredResponse = new HashSet<>();
586 HashSet<String> errors = new HashSet<>();
588 for (SequenceI seq : selectedSequences)
591 FTSRestResponse resultList;
594 resultList = data.selectFirstRankedQuery(seq,
595 discoveredStructuresSet, wantedFields, fieldToFilterBy,
596 !chk_invertFilter.isSelected());
598 } catch (Exception e)
601 errors.add(e.getMessage());
604 if (resultList.getSearchSummary() != null
605 && !resultList.getSearchSummary().isEmpty())
607 filteredResponse.addAll(resultList.getSearchSummary());
611 String totalTime = (System.currentTimeMillis() - startTime)
613 if (!filteredResponse.isEmpty())
615 final int filterResponseCount = filteredResponse.size();
616 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
617 reorderedStructuresSet.addAll(filteredResponse);
618 reorderedStructuresSet.addAll(discoveredStructuresSet);
620 .setModel(data.getTableModel(reorderedStructuresSet));
622 FTSRestResponse.configureTableColumn(getResultTable(),
623 wantedFields, tempUserPrefs);
624 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
625 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
626 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
627 // Update table selection model here
628 getResultTable().addRowSelectionInterval(0,
629 filterResponseCount - 1);
630 mainFrame.setTitle(MessageManager.formatMessage(
631 "label.structure_chooser_filter_time", totalTime));
635 mainFrame.setTitle(MessageManager.formatMessage(
636 "label.structure_chooser_filter_time", totalTime));
637 if (errors.size() > 0)
639 StringBuilder errorMsg = new StringBuilder();
640 for (String error : errors)
642 errorMsg.append(error).append("\n");
644 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
645 MessageManager.getString("label.pdb_web-service_error"),
646 JvOptionPane.ERROR_MESSAGE);
650 lbl_loading.setVisible(false);
652 validateSelections();
655 filterThread.start();
659 * Handles action event for btn_pdbFromFile
662 protected void pdbFromFile_actionPerformed()
664 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
667 JalviewFileChooser chooser = new JalviewFileChooser(
668 Cache.getProperty("LAST_DIRECTORY"));
669 chooser.setFileView(new JalviewFileView());
670 chooser.setDialogTitle(
671 MessageManager.formatMessage("label.select_pdb_file_for",
672 selectedSequence.getDisplayId(false)));
673 chooser.setToolTipText(MessageManager.formatMessage(
674 "label.load_pdb_file_associate_with_sequence",
675 selectedSequence.getDisplayId(false)));
677 int value = chooser.showOpenDialog(null);
678 if (value == JalviewFileChooser.APPROVE_OPTION)
680 selectedPdbFileName = chooser.getSelectedFile().getPath();
681 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
682 localPdbPaeMatrixFileName = guessPAEFilename();
683 validateSelections();
688 * Handles action event for btn_pdbFromFile
691 protected void paeMatrixFile_actionPerformed()
693 File pdbFile = new File(selectedPdbFileName);
694 String setFile = Cache.getProperty("LAST_DIRECTORY");
695 if (localPdbPaeMatrixFileName != null)
697 File paeFile = new File(localPdbPaeMatrixFileName);
698 if (paeFile.exists())
699 setFile = paeFile.getAbsolutePath();
700 else if (paeFile.getParentFile().exists())
701 setFile = paeFile.getParentFile().getAbsolutePath();
705 String guess = guessPAEFilename();
709 JalviewFileChooser chooser = new JalviewFileChooser(setFile);
710 chooser.setFileView(new JalviewFileView());
711 chooser.setDialogTitle(MessageManager.formatMessage(
712 "label.select_pae_matrix_file_for", pdbFile.getName()));
713 chooser.setToolTipText(MessageManager.formatMessage(
714 "label.load_pae_matrix_file_associate_with_structure",
717 int value = chooser.showOpenDialog(null);
718 if (value == JalviewFileChooser.APPROVE_OPTION)
720 localPdbPaeMatrixFileName = chooser.getSelectedFile().getPath();
721 Cache.setProperty("LAST_DIRECTORY", localPdbPaeMatrixFileName);
723 validateAssociationFromFile();
726 private String guessPAEFilename()
728 if (selectedPdbFileName.toLowerCase(Locale.ROOT).endsWith(".pdb"))
730 String jsonExt = selectedPdbFileName.substring(0,
731 selectedPdbFileName.length() - 4) + ".json";
732 // AlphaFold naming scheme
733 String guessFile1 = StringUtils.replaceLast(jsonExt, "model",
734 "predicted_aligned_error");
735 // nf-core mode naming scheme
736 String guessFile2 = StringUtils.replaceLast(jsonExt, ".json",
738 if (new File(guessFile1).exists())
742 else if (new File(jsonExt).exists())
746 else if (new File(guessFile2).exists())
755 * Populates the filter combo-box options dynamically depending on discovered
758 protected void populateFilterComboBox(boolean haveData,
759 boolean cachedPDBExist)
761 populateFilterComboBox(haveData, cachedPDBExist, null);
765 * Populates the filter combo-box options dynamically depending on discovered
768 protected void populateFilterComboBox(boolean haveData,
769 boolean cachedPDBExist, FilterOption lastSel)
773 * temporarily suspend the change listener behaviour
775 cmb_filterOption.removeItemListener(this);
777 cmb_filterOption.removeAllItems();
780 List<FilterOption> filters = data
781 .getAvailableFilterOptions(VIEWS_FILTER);
782 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
783 lastDiscoveredStructuresSet);
785 for (FilterOption filter : filters)
787 if (lastSel != null && filter.equals(lastSel))
792 cmb_filterOption.addItem(filter);
796 cmb_filterOption.addItem(
797 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
798 "-", VIEWS_ENTER_ID, false, null));
799 cmb_filterOption.addItem(
800 new FilterOption(MessageManager.getString("label.from_file"),
801 "-", VIEWS_FROM_FILE, false, null));
802 if (canQueryTDB && notQueriedTDBYet)
804 btn_queryTDB.setVisible(true);
805 pnl_queryTDB.setVisible(true);
810 FilterOption cachedOption = new FilterOption(
811 MessageManager.getString("label.cached_structures"), "-",
812 VIEWS_LOCAL_PDB, false, null);
813 cmb_filterOption.addItem(cachedOption);
816 cmb_filterOption.setSelectedItem(cachedOption);
821 cmb_filterOption.setSelectedIndex(selSet);
823 cmb_filterOption.addItemListener(this);
827 * Updates the displayed view based on the selected filter option
829 protected void updateCurrentView()
831 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
834 if (lastSelected == selectedFilterOpt)
836 // don't need to do anything, probably
839 // otherwise, record selection
840 // and update the layout and dialog accordingly
841 lastSelected = selectedFilterOpt;
843 layout_switchableViews.show(pnl_switchableViews,
844 selectedFilterOpt.getView());
845 String filterTitle = mainFrame.getTitle();
846 mainFrame.setTitle(frameTitle);
847 chk_invertFilter.setVisible(false);
849 if (selectedFilterOpt.getView() == VIEWS_FILTER)
851 mainFrame.setTitle(filterTitle);
852 // TDB Query has no invert as yet
853 chk_invertFilter.setVisible(selectedFilterOpt
854 .getQuerySource() instanceof PDBStructureChooserQuerySource);
856 if (data != selectedFilterOpt.getQuerySource()
857 || data.needsRefetch(selectedFilterOpt))
859 data = selectedFilterOpt.getQuerySource();
860 // rebuild the views completely, since prefs will also change
866 filterResultSet(selectedFilterOpt.getValue());
869 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
870 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
872 mainFrame.setTitle(MessageManager
873 .getString("label.structure_chooser_manual_association"));
874 idInputAssSeqPanel.loadCmbAssSeq();
875 fileChooserAssSeqPanel.loadCmbAssSeq();
877 validateSelections();
881 * Validates user selection and enables the 'Add' and 'New View' buttons if
882 * all parameters are correct (the Add button will only be visible if there is
883 * at least one existing structure viewer open). This basically means at least
884 * one structure selected and no error messages.
886 * The 'Superpose Structures' option is enabled if either more than one
887 * structure is selected, or the 'Add' to existing view option is enabled, and
888 * disabled if the only option is to open a new view of a single structure.
891 protected void validateSelections()
893 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
895 btn_add.setEnabled(false);
896 String currentView = selectedFilterOpt.getView();
897 int selectedCount = 0;
898 if (currentView == VIEWS_FILTER)
900 selectedCount = getResultTable().getSelectedRows().length;
901 if (selectedCount > 0)
903 btn_add.setEnabled(true);
906 else if (currentView == VIEWS_LOCAL_PDB)
908 selectedCount = tbl_local_pdb.getSelectedRows().length;
909 if (selectedCount > 0)
911 btn_add.setEnabled(true);
914 else if (currentView == VIEWS_ENTER_ID)
916 validateAssociationEnterPdb();
918 else if (currentView == VIEWS_FROM_FILE)
920 validateAssociationFromFile();
923 btn_newView.setEnabled(btn_add.isEnabled());
926 * enable 'Superpose' option if more than one structure is selected,
927 * or there are view(s) available to add structure(s) to
930 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
934 protected boolean showPopupFor(int selectedRow, int x, int y)
936 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
938 String currentView = selectedFilterOpt.getView();
940 if (currentView == VIEWS_FILTER
941 && data instanceof ThreeDBStructureChooserQuerySource)
944 TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
945 .getFTSDataFor(getResultTable(), selectedRow,
946 discoveredStructuresSet);
947 String pageUrl = row.getModelViewUrl();
948 JPopupMenu popup = new JPopupMenu("3D Beacons");
949 JMenuItem viewUrl = new JMenuItem("View model web page");
950 viewUrl.addActionListener(new ActionListener()
953 public void actionPerformed(ActionEvent e)
955 Desktop.showUrl(pageUrl);
959 SwingUtilities.invokeLater(new Runnable()
964 popup.show(getResultTable(), x, y);
969 // event not handled by us
974 * Validates inputs from the Manual PDB entry panel
976 protected void validateAssociationEnterPdb()
978 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
979 .getCmb_assSeq().getSelectedItem();
980 lbl_pdbManualFetchStatus.setIcon(errorImage);
981 lbl_pdbManualFetchStatus.setToolTipText("");
982 if (txt_search.getText().length() > 0)
984 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
985 MessageManager.formatMessage("info.no_pdb_entry_found_for",
986 txt_search.getText())));
989 if (errorWarning.length() > 0)
991 lbl_pdbManualFetchStatus.setIcon(warningImage);
992 lbl_pdbManualFetchStatus.setToolTipText(
993 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
996 if (selectedSequences.length == 1 || !assSeqOpt.getName()
997 .equalsIgnoreCase("-Select Associated Seq-"))
999 txt_search.setEnabled(true);
1000 if (isValidPBDEntry)
1002 btn_add.setEnabled(true);
1003 lbl_pdbManualFetchStatus.setToolTipText("");
1004 lbl_pdbManualFetchStatus.setIcon(goodImage);
1009 txt_search.setEnabled(false);
1010 lbl_pdbManualFetchStatus.setIcon(errorImage);
1015 * Validates inputs for the manual PDB file selection options
1017 protected void validateAssociationFromFile()
1019 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
1020 .getCmb_assSeq().getSelectedItem();
1021 // lbl_fromFileStatus.setIcon(errorImage);
1022 String pdbFileString = "";
1023 String pdbFileTooltip = "";
1024 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
1025 .getName().equalsIgnoreCase("-Select Associated Seq-")))
1027 btn_pdbFromFile.setEnabled(true);
1028 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
1030 btn_add.setEnabled(true);
1031 // lbl_fromFileStatus.setIcon(goodImage);
1032 pdbFileString = new File(selectedPdbFileName).getName();
1033 pdbFileTooltip = new File(selectedPdbFileName).getAbsolutePath();
1034 setPdbOptionsEnabled(true);
1038 pdbFileString = MessageManager.getString("label.none");
1039 pdbFileTooltip = MessageManager.getString("label.nothing_selected");
1044 btn_pdbFromFile.setEnabled(false);
1045 // lbl_fromFileStatus.setIcon(errorImage);
1046 pdbFileString = MessageManager.getString("label.none");
1047 pdbFileTooltip = MessageManager.getString("label.nothing_selected");
1049 lbl_pdbFile.setText(pdbFileString);
1050 lbl_pdbFile.setToolTipText(pdbFileTooltip);
1053 String paeFileString = "";
1054 String paeFileTooltip = "";
1055 if (localPdbPaeMatrixFileName != null
1056 && localPdbPaeMatrixFileName.length() > 0)
1058 paeFileString = new File(localPdbPaeMatrixFileName).getName();
1059 paeFileTooltip = new File(localPdbPaeMatrixFileName)
1064 paeFileString = MessageManager.getString("label.none");
1065 paeFileTooltip = MessageManager.getString("label.nothing_selected");
1067 lbl_paeFile.setText(paeFileString);
1068 lbl_paeFile.setToolTipText(paeFileTooltip);
1072 protected void cmbAssSeqStateChanged()
1074 validateSelections();
1077 private FilterOption lastSelected = null;
1080 * Handles the state change event for the 'filter' combo-box and 'invert'
1084 protected void stateChanged(ItemEvent e)
1086 if (e.getSource() instanceof JCheckBox)
1088 updateCurrentView();
1092 if (e.getStateChange() == ItemEvent.SELECTED)
1094 updateCurrentView();
1101 * select structures for viewing by their PDB IDs
1104 * @return true if structures were found and marked as selected
1106 public boolean selectStructure(String... pdbids)
1108 boolean found = false;
1110 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1111 .getSelectedItem());
1112 String currentView = selectedFilterOpt.getView();
1113 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1114 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
1116 if (restable == null)
1118 // can't select (enter PDB ID, or load file - need to also select which
1119 // sequence to associate with)
1123 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
1124 for (int r = 0; r < restable.getRowCount(); r++)
1126 for (int p = 0; p < pdbids.length; p++)
1128 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1129 .equalsIgnoreCase(pdbids[p]))
1131 restable.setRowSelectionInterval(r, r);
1140 * Handles the 'New View' action
1143 protected void newView_ActionPerformed()
1145 targetView.setSelectedItem(null);
1146 showStructures(false);
1150 * Handles the 'Add to existing viewer' action
1153 protected void add_ActionPerformed()
1155 showStructures(false);
1159 * structure viewer opened by this dialog, or null
1161 private StructureViewer sViewer = null;
1163 public void showStructures(boolean waitUntilFinished)
1166 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1168 final int preferredHeight = pnl_filter.getHeight();
1170 Runnable viewStruc = new Runnable()
1175 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1176 .getSelectedItem());
1177 String currentView = selectedFilterOpt.getView();
1178 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1181 if (currentView == VIEWS_FILTER)
1183 int[] selectedRows = restable.getSelectedRows();
1184 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1185 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1186 pdbEntriesToView = data.collectSelectedRows(restable,
1187 selectedRows, selectedSeqsToView);
1189 SequenceI[] selectedSeqs = selectedSeqsToView
1190 .toArray(new SequenceI[selectedSeqsToView.size()]);
1191 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1194 else if (currentView == VIEWS_LOCAL_PDB)
1196 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1197 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1199 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1201 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1203 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1204 for (int row : selectedRows)
1206 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1207 .getModel()).getPDBEntryAt(row).getPdbEntry();
1209 pdbEntriesToView[count++] = pdbEntry;
1210 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1211 .getValueAt(row, refSeqColIndex);
1212 selectedSeqsToView.add(selectedSeq);
1214 SequenceI[] selectedSeqs = selectedSeqsToView
1215 .toArray(new SequenceI[selectedSeqsToView.size()]);
1216 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1219 else if (currentView == VIEWS_ENTER_ID)
1221 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1222 .getCmb_assSeq().getSelectedItem()).getSequence();
1223 if (userSelectedSeq != null)
1225 selectedSequence = userSelectedSeq;
1227 String pdbIdStr = txt_search.getText();
1228 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1229 if (pdbEntry == null)
1231 pdbEntry = new PDBEntry();
1232 if (pdbIdStr.split(":").length > 1)
1234 pdbEntry.setId(pdbIdStr.split(":")[0]);
1235 pdbEntry.setChainCode(
1236 pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1240 pdbEntry.setId(pdbIdStr);
1242 pdbEntry.setType(PDBEntry.Type.PDB);
1243 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1246 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1247 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1249 { selectedSequence });
1251 else if (currentView == VIEWS_FROM_FILE)
1253 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1254 .getCmb_assSeq().getSelectedItem()).getSequence();
1255 if (userSelectedSeq != null)
1257 selectedSequence = userSelectedSeq;
1259 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1260 .associatePdbWithSeq(selectedPdbFileName,
1261 DataSourceType.FILE, selectedSequence, true,
1264 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1266 { selectedSequence });
1268 SwingUtilities.invokeLater(new Runnable()
1273 closeAction(preferredHeight);
1274 mainFrame.dispose();
1279 Thread runner = new Thread(viewStruc);
1281 if (waitUntilFinished)
1283 while (sViewer == null ? runner.isAlive()
1284 : (sViewer.sview == null ? true
1285 : !sViewer.sview.hasMapping()))
1290 } catch (InterruptedException ie)
1299 * Answers a structure viewer (new or existing) configured to superimpose
1300 * added structures or not according to the user's choice
1305 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1307 Object sv = targetView.getSelectedItem();
1309 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1313 * Adds PDB structures to a new or existing structure viewer
1316 * @param pdbEntriesToView
1321 private StructureViewer launchStructureViewer(
1322 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1323 final AlignmentPanel alignPanel, SequenceI[] sequences)
1325 long progressId = sequences.hashCode();
1326 setProgressBar(MessageManager
1327 .getString("status.launching_3d_structure_viewer"), progressId);
1328 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1329 boolean superimpose = chk_superpose.isSelected();
1330 theViewer.setSuperpose(superimpose);
1333 * remember user's choice of superimpose or not
1335 Cache.setProperty(AUTOSUPERIMPOSE,
1336 Boolean.valueOf(superimpose).toString());
1338 setProgressBar(null, progressId);
1339 if (SiftsSettings.isMapWithSifts())
1341 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1343 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1344 // real PDB ID. For moment, we can also safely do this if there is already
1345 // a known mapping between the PDBEntry and the sequence.
1346 for (SequenceI seq : sequences)
1348 PDBEntry pdbe = pdbEntriesToView[p++];
1349 if (pdbe != null && pdbe.getFile() != null)
1351 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1352 if (smm != null && smm.length > 0)
1354 for (StructureMapping sm : smm)
1356 if (sm.getSequence() == seq)
1363 if (seq.getPrimaryDBRefs().isEmpty())
1365 seqsWithoutSourceDBRef.add(seq);
1369 if (!seqsWithoutSourceDBRef.isEmpty())
1371 int y = seqsWithoutSourceDBRef.size();
1372 setProgressBar(MessageManager.formatMessage(
1373 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1375 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1376 .toArray(new SequenceI[y]);
1377 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1378 dbRefFetcher.fetchDBRefs(true);
1380 setProgressBar("Fetch complete.", progressId); // todo i18n
1383 if (pdbEntriesToView.length > 1)
1386 MessageManager.getString(
1387 "status.fetching_3d_structures_for_selected_entries"),
1389 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1393 setProgressBar(MessageManager.formatMessage(
1394 "status.fetching_3d_structures_for",
1395 pdbEntriesToView[0].getId()), progressId);
1396 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1398 setProgressBar(null, progressId);
1399 // remember the last viewer we used...
1400 lastTargetedView = theViewer;
1405 * Populates the combo-box used in associating manually fetched structures to
1406 * a unique sequence when more than one sequence selection is made.
1409 protected void populateCmbAssociateSeqOptions(
1410 JComboBox<AssociateSeqOptions> cmb_assSeq,
1411 JLabel lbl_associateSeq)
1413 cmb_assSeq.removeAllItems();
1415 new AssociateSeqOptions("-Select Associated Seq-", null));
1416 lbl_associateSeq.setVisible(false);
1417 if (selectedSequences.length > 1)
1419 for (SequenceI seq : selectedSequences)
1421 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1426 String seqName = selectedSequence.getDisplayId(false);
1427 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1428 lbl_associateSeq.setText(seqName);
1429 lbl_associateSeq.setVisible(true);
1430 cmb_assSeq.setVisible(false);
1434 protected boolean isStructuresDiscovered()
1436 return discoveredStructuresSet != null
1437 && !discoveredStructuresSet.isEmpty();
1440 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1442 // Doing a search for "1" or "1c" is valuable?
1443 // Those work but are enormously slow.
1446 protected void txt_search_ActionPerformed()
1448 String text = txt_search.getText().trim();
1449 if (text.length() >= PDB_ID_MIN)
1456 errorWarning.setLength(0);
1457 isValidPBDEntry = false;
1458 if (text.length() > 0)
1460 // TODO move this pdb id search into the PDB specific
1462 // for moment, it will work fine as is because it is self-contained
1463 String searchTerm = text.toLowerCase(Locale.ROOT);
1464 searchTerm = searchTerm.split(":")[0];
1465 // System.out.println(">>>>> search term : " + searchTerm);
1466 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1467 FTSRestRequest pdbRequest = new FTSRestRequest();
1468 pdbRequest.setAllowEmptySeq(false);
1469 pdbRequest.setResponseSize(1);
1470 pdbRequest.setFieldToSearchBy("(pdb_id:");
1471 pdbRequest.setWantedFields(wantedFields);
1472 pdbRequest.setSearchTerm(searchTerm + ")");
1473 pdbRequest.setAssociatedSequence(selectedSequence);
1474 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1475 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1476 FTSRestResponse resultList;
1479 resultList = pdbRestClient.executeRequest(pdbRequest);
1480 } catch (Exception e)
1482 errorWarning.append(e.getMessage());
1486 validateSelections();
1488 if (resultList.getSearchSummary() != null
1489 && resultList.getSearchSummary().size() > 0)
1491 isValidPBDEntry = true;
1494 validateSelections();
1500 protected void tabRefresh()
1502 if (selectedSequences != null)
1504 lbl_loading.setVisible(true);
1505 Thread refreshThread = new Thread(new Runnable()
1510 fetchStructuresMetaData();
1511 // populateFilterComboBox(true, cachedPDBExists);
1514 ((FilterOption) cmb_filterOption.getSelectedItem())
1516 lbl_loading.setVisible(false);
1519 refreshThread.start();
1523 public class PDBEntryTableModel extends AbstractTableModel
1525 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1528 private List<CachedPDB> pdbEntries;
1530 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1532 this.pdbEntries = new ArrayList<>(pdbEntries);
1536 public String getColumnName(int columnIndex)
1538 return columns[columnIndex];
1542 public int getRowCount()
1544 return pdbEntries.size();
1548 public int getColumnCount()
1550 return columns.length;
1554 public boolean isCellEditable(int row, int column)
1560 public Object getValueAt(int rowIndex, int columnIndex)
1562 Object value = "??";
1563 CachedPDB entry = pdbEntries.get(rowIndex);
1564 switch (columnIndex)
1567 value = entry.getSequence();
1570 value = entry.getQualifiedId();
1573 value = entry.getPdbEntry().getChainCode() == null ? "_"
1574 : entry.getPdbEntry().getChainCode();
1577 value = entry.getPdbEntry().getType();
1580 value = entry.getPdbEntry().getFile();
1587 public Class<?> getColumnClass(int columnIndex)
1589 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1592 public CachedPDB getPDBEntryAt(int row)
1594 return pdbEntries.get(row);
1599 private class CachedPDB
1601 private SequenceI sequence;
1603 private PDBEntry pdbEntry;
1605 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1607 this.sequence = sequence;
1608 this.pdbEntry = pdbEntry;
1611 public String getQualifiedId()
1613 if (pdbEntry.hasProvider())
1615 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1617 return pdbEntry.toString();
1620 public SequenceI getSequence()
1625 public PDBEntry getPdbEntry()
1632 private IProgressIndicator progressBar;
1635 public void setProgressBar(String message, long id)
1637 if (!Platform.isHeadless())
1638 progressBar.setProgressBar(message, id);
1642 public void registerHandler(long id, IProgressIndicatorHandler handler)
1644 progressBar.registerHandler(id, handler);
1648 public boolean operationInProgress()
1650 return progressBar.operationInProgress();
1653 public JalviewStructureDisplayI getOpenedStructureViewer()
1655 return sViewer == null ? null : sViewer.sview;
1659 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1661 data.setDocFieldPrefs(newPrefs);
1667 * @return true when all initialisation threads have finished and dialog is
1670 public boolean isDialogVisible()
1672 return mainFrame != null && data != null && cmb_filterOption != null
1673 && mainFrame.isVisible()
1674 && cmb_filterOption.getSelectedItem() != null;
1679 * @return true if the 3D-Beacons query button will/has been displayed
1681 public boolean isCanQueryTDB()
1686 public boolean isNotQueriedTDBYet()
1688 return notQueriedTDBYet;
1692 * Open a single structure file for a given sequence
1694 public static void openStructureFileForSequence(AlignmentPanel ap,
1695 SequenceI seq, File sFile)
1697 // Open the chooser headlessly. Not sure this is actually needed ?
1698 StructureChooser sc = new StructureChooser(new SequenceI[] { seq }, seq,
1700 StructureSelectionManager ssm = ap.getStructureSelectionManager();
1701 PDBEntry fileEntry = null;
1704 fileEntry = new AssociatePdbFileWithSeq().associatePdbWithSeq(
1705 sFile.getAbsolutePath(), DataSourceType.FILE, seq, true,
1707 } catch (Exception e)
1709 Console.error("Could not open structure file '"
1710 + sFile.getAbsolutePath() + "'");
1714 StructureViewer sViewer = sc.launchStructureViewer(ssm,
1716 { fileEntry }, ap, new SequenceI[] { seq });
1718 sc.mainFrame.dispose();