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.JMenuItem;
39 import javax.swing.JPopupMenu;
40 import javax.swing.JTable;
41 import javax.swing.SwingUtilities;
42 import javax.swing.table.AbstractTableModel;
44 import jalview.api.structures.JalviewStructureDisplayI;
45 import jalview.bin.Cache;
46 import jalview.bin.Console;
47 import jalview.bin.Jalview;
48 import jalview.datamodel.PDBEntry;
49 import jalview.datamodel.SequenceI;
50 import jalview.fts.api.FTSData;
51 import jalview.fts.api.FTSDataColumnI;
52 import jalview.fts.api.FTSRestClientI;
53 import jalview.fts.core.FTSDataColumnPreferences;
54 import jalview.fts.core.FTSRestRequest;
55 import jalview.fts.core.FTSRestResponse;
56 import jalview.fts.service.pdb.PDBFTSRestClient;
57 import jalview.fts.service.threedbeacons.TDB_FTSData;
58 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
59 import jalview.gui.structurechooser.StructureChooserQuerySource;
60 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
61 import jalview.io.DataSourceType;
62 import jalview.jbgui.FilterOption;
63 import jalview.jbgui.GStructureChooser;
64 import jalview.structure.StructureMapping;
65 import jalview.structure.StructureSelectionManager;
66 import jalview.util.MessageManager;
67 import jalview.ws.DBRefFetcher;
68 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
69 import jalview.ws.seqfetcher.DbSourceProxy;
70 import jalview.ws.sifts.SiftsSettings;
73 * Provides the behaviors for the Structure chooser Panel
78 @SuppressWarnings("serial")
79 public class StructureChooser extends GStructureChooser
80 implements IProgressIndicator
82 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
85 * warn user if need to fetch more than this many uniprot records at once
87 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 private 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 populateSeqsWithoutSourceDBRef();
326 final int y = seqsWithoutSourceDBRef.size();
329 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
330 .toArray(new SequenceI[y]);
331 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
332 progressBar, new DbSourceProxy[]
333 { new jalview.ws.dbsources.Uniprot() }, null, false);
334 dbRefFetcher.addListener(afterDbRefFetch);
335 // ideally this would also gracefully run with callbacks
336 dbRefFetcher.fetchDBRefs(true);
340 // call finished action directly
341 afterDbRefFetch.finished();
346 final Runnable revertview = new Runnable()
351 if (lastSelected != null)
353 cmb_filterOption.setSelectedItem(lastSelected);
357 int threshold = Cache.getDefault("THRESHOLD_WARN_UNIPROT_FETCH",
358 THRESHOLD_WARN_UNIPROT_FETCH_NEEDED);
359 Console.debug("Using Uniprot fetch threshold of " + threshold);
360 if (ignoreGui || seqsWithoutSourceDBRef.size() < threshold)
362 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs)
366 // need cancel and no to result in the discoverPDB action - mocked is
367 // 'cancel' TODO: mock should be OK
368 JvOptionPane.newOptionDialog(this)
369 .setResponseHandler(JvOptionPane.OK_OPTION,
370 discoverCanonicalDBrefs)
371 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
372 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
374 MessageManager.formatMessage(
375 "label.fetch_references_for_3dbeacons",
376 seqsWithoutSourceDBRef.size()),
377 MessageManager.getString("label.3dbeacons"),
378 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
380 { MessageManager.getString("action.ok"),
381 MessageManager.getString("action.cancel") },
382 MessageManager.getString("action.ok"));
386 * Builds a drop-down choice list of existing structure viewers to which new
387 * structures may be added. If this list is empty then it, and the 'Add'
388 * button, are hidden.
390 private void discoverStructureViews()
392 if (Desktop.instance != null)
394 targetView.removeAllItems();
395 if (lastTargetedView != null && !lastTargetedView.isVisible())
397 lastTargetedView = null;
399 int linkedViewsAt = 0;
400 for (StructureViewerBase view : Desktop.instance
401 .getStructureViewers(null, null))
403 StructureViewer viewHandler = (lastTargetedView != null
404 && lastTargetedView.sview == view) ? lastTargetedView
405 : StructureViewer.reconfigure(view);
407 if (view.isLinkedWith(ap))
409 targetView.insertItemAt(viewHandler, linkedViewsAt++);
413 targetView.addItem(viewHandler);
418 * show option to Add to viewer if at least 1 viewer found
420 targetView.setVisible(false);
421 if (targetView.getItemCount() > 0)
423 targetView.setVisible(true);
424 if (lastTargetedView != null)
426 targetView.setSelectedItem(lastTargetedView);
430 targetView.setSelectedIndex(0);
433 btn_add.setVisible(targetView.isVisible());
438 * Updates the progress indicator with the specified message
441 * displayed message for the operation
443 * unique handle for this indicator
445 protected void updateProgressIndicator(String message, long id)
447 if (progressIndicator != null)
449 progressIndicator.setProgressBar(message, id);
454 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
457 void fetchStructuresMetaData()
459 long startTime = System.currentTimeMillis();
460 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
461 .getStructureSummaryFields();
463 discoveredStructuresSet = new LinkedHashSet<>();
464 HashSet<String> errors = new HashSet<>();
466 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
469 for (SequenceI seq : selectedSequences)
472 FTSRestResponse resultList;
475 resultList = data.fetchStructuresMetaData(seq, wantedFields,
476 selectedFilterOpt, !chk_invertFilter.isSelected());
477 // null response means the FTSengine didn't yield a query for this
478 // consider designing a special exception if we really wanted to be
480 if (resultList == null)
484 } catch (Exception e)
487 errors.add(e.getMessage());
490 if (resultList.getSearchSummary() != null
491 && !resultList.getSearchSummary().isEmpty())
493 discoveredStructuresSet.addAll(resultList.getSearchSummary());
497 int noOfStructuresFound = 0;
498 String totalTime = (System.currentTimeMillis() - startTime)
500 if (discoveredStructuresSet != null
501 && !discoveredStructuresSet.isEmpty())
504 .setModel(data.getTableModel(discoveredStructuresSet));
506 noOfStructuresFound = discoveredStructuresSet.size();
507 lastDiscoveredStructuresSet = discoveredStructuresSet;
508 mainFrame.setTitle(MessageManager.formatMessage(
509 "label.structure_chooser_no_of_structures",
510 noOfStructuresFound, totalTime));
514 mainFrame.setTitle(MessageManager
515 .getString("label.structure_chooser_manual_association"));
516 if (errors.size() > 0)
518 StringBuilder errorMsg = new StringBuilder();
519 for (String error : errors)
521 errorMsg.append(error).append("\n");
523 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
524 MessageManager.getString("label.pdb_web-service_error"),
525 JvOptionPane.ERROR_MESSAGE);
530 protected void loadLocalCachedPDBEntries()
532 ArrayList<CachedPDB> entries = new ArrayList<>();
533 for (SequenceI seq : selectedSequences)
535 if (seq.getDatasetSequence() != null
536 && seq.getDatasetSequence().getAllPDBEntries() != null)
538 for (PDBEntry pdbEntry : seq.getDatasetSequence()
541 if (pdbEntry.getFile() != null)
543 entries.add(new CachedPDB(seq, pdbEntry));
548 cachedPDBExists = !entries.isEmpty();
549 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
550 tbl_local_pdb.setModel(tableModelx);
554 * Filters a given list of discovered structures based on supplied argument
556 * @param fieldToFilterBy
557 * the field to filter by
559 void filterResultSet(final String fieldToFilterBy)
561 Thread filterThread = new Thread(new Runnable()
567 long startTime = System.currentTimeMillis();
568 lbl_loading.setVisible(true);
569 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
570 .getStructureSummaryFields();
571 Collection<FTSData> filteredResponse = new HashSet<>();
572 HashSet<String> errors = new HashSet<>();
574 for (SequenceI seq : selectedSequences)
577 FTSRestResponse resultList;
580 resultList = data.selectFirstRankedQuery(seq,
581 discoveredStructuresSet, wantedFields, fieldToFilterBy,
582 !chk_invertFilter.isSelected());
584 } catch (Exception e)
587 errors.add(e.getMessage());
590 if (resultList.getSearchSummary() != null
591 && !resultList.getSearchSummary().isEmpty())
593 filteredResponse.addAll(resultList.getSearchSummary());
597 String totalTime = (System.currentTimeMillis() - startTime)
599 if (!filteredResponse.isEmpty())
601 final int filterResponseCount = filteredResponse.size();
602 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
603 reorderedStructuresSet.addAll(filteredResponse);
604 reorderedStructuresSet.addAll(discoveredStructuresSet);
606 .setModel(data.getTableModel(reorderedStructuresSet));
608 FTSRestResponse.configureTableColumn(getResultTable(),
609 wantedFields, tempUserPrefs);
610 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
611 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
612 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
613 // Update table selection model here
614 getResultTable().addRowSelectionInterval(0,
615 filterResponseCount - 1);
616 mainFrame.setTitle(MessageManager.formatMessage(
617 "label.structure_chooser_filter_time", totalTime));
621 mainFrame.setTitle(MessageManager.formatMessage(
622 "label.structure_chooser_filter_time", totalTime));
623 if (errors.size() > 0)
625 StringBuilder errorMsg = new StringBuilder();
626 for (String error : errors)
628 errorMsg.append(error).append("\n");
630 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
631 MessageManager.getString("label.pdb_web-service_error"),
632 JvOptionPane.ERROR_MESSAGE);
636 lbl_loading.setVisible(false);
638 validateSelections();
641 filterThread.start();
645 * Handles action event for btn_pdbFromFile
648 protected void pdbFromFile_actionPerformed()
650 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
653 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
654 Cache.getProperty("LAST_DIRECTORY"));
655 chooser.setFileView(new jalview.io.JalviewFileView());
656 chooser.setDialogTitle(
657 MessageManager.formatMessage("label.select_pdb_file_for",
658 selectedSequence.getDisplayId(false)));
659 chooser.setToolTipText(MessageManager.formatMessage(
660 "label.load_pdb_file_associate_with_sequence",
661 selectedSequence.getDisplayId(false)));
663 int value = chooser.showOpenDialog(null);
664 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
666 selectedPdbFileName = chooser.getSelectedFile().getPath();
667 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
668 validateSelections();
673 * Populates the filter combo-box options dynamically depending on discovered
676 protected void populateFilterComboBox(boolean haveData,
677 boolean cachedPDBExist)
679 populateFilterComboBox(haveData, cachedPDBExist, null);
683 * Populates the filter combo-box options dynamically depending on discovered
686 protected void populateFilterComboBox(boolean haveData,
687 boolean cachedPDBExist, FilterOption lastSel)
691 * temporarily suspend the change listener behaviour
693 cmb_filterOption.removeItemListener(this);
695 cmb_filterOption.removeAllItems();
698 List<FilterOption> filters = data
699 .getAvailableFilterOptions(VIEWS_FILTER);
700 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
701 lastDiscoveredStructuresSet);
703 for (FilterOption filter : filters)
705 if (lastSel != null && filter.equals(lastSel))
710 cmb_filterOption.addItem(filter);
714 cmb_filterOption.addItem(
715 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
716 "-", VIEWS_ENTER_ID, false, null));
717 cmb_filterOption.addItem(
718 new FilterOption(MessageManager.getString("label.from_file"),
719 "-", VIEWS_FROM_FILE, false, null));
720 if (canQueryTDB && notQueriedTDBYet)
722 btn_queryTDB.setVisible(true);
723 pnl_queryTDB.setVisible(true);
728 FilterOption cachedOption = new FilterOption(
729 MessageManager.getString("label.cached_structures"), "-",
730 VIEWS_LOCAL_PDB, false, null);
731 cmb_filterOption.addItem(cachedOption);
734 cmb_filterOption.setSelectedItem(cachedOption);
739 cmb_filterOption.setSelectedIndex(selSet);
741 cmb_filterOption.addItemListener(this);
745 * Updates the displayed view based on the selected filter option
747 protected void updateCurrentView()
749 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
752 if (lastSelected == selectedFilterOpt)
754 // don't need to do anything, probably
757 // otherwise, record selection
758 // and update the layout and dialog accordingly
759 lastSelected = selectedFilterOpt;
761 layout_switchableViews.show(pnl_switchableViews,
762 selectedFilterOpt.getView());
763 String filterTitle = mainFrame.getTitle();
764 mainFrame.setTitle(frameTitle);
765 chk_invertFilter.setVisible(false);
767 if (selectedFilterOpt.getView() == VIEWS_FILTER)
769 mainFrame.setTitle(filterTitle);
770 // TDB Query has no invert as yet
771 chk_invertFilter.setVisible(selectedFilterOpt
772 .getQuerySource() instanceof PDBStructureChooserQuerySource);
774 if (data != selectedFilterOpt.getQuerySource()
775 || data.needsRefetch(selectedFilterOpt))
777 data = selectedFilterOpt.getQuerySource();
778 // rebuild the views completely, since prefs will also change
784 filterResultSet(selectedFilterOpt.getValue());
787 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
788 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
790 mainFrame.setTitle(MessageManager
791 .getString("label.structure_chooser_manual_association"));
792 idInputAssSeqPanel.loadCmbAssSeq();
793 fileChooserAssSeqPanel.loadCmbAssSeq();
795 validateSelections();
799 * Validates user selection and enables the 'Add' and 'New View' buttons if
800 * all parameters are correct (the Add button will only be visible if there is
801 * at least one existing structure viewer open). This basically means at least
802 * one structure selected and no error messages.
804 * The 'Superpose Structures' option is enabled if either more than one
805 * structure is selected, or the 'Add' to existing view option is enabled, and
806 * disabled if the only option is to open a new view of a single structure.
809 protected void validateSelections()
811 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
813 btn_add.setEnabled(false);
814 String currentView = selectedFilterOpt.getView();
815 int selectedCount = 0;
816 if (currentView == VIEWS_FILTER)
818 selectedCount = getResultTable().getSelectedRows().length;
819 if (selectedCount > 0)
821 btn_add.setEnabled(true);
824 else if (currentView == VIEWS_LOCAL_PDB)
826 selectedCount = tbl_local_pdb.getSelectedRows().length;
827 if (selectedCount > 0)
829 btn_add.setEnabled(true);
832 else if (currentView == VIEWS_ENTER_ID)
834 validateAssociationEnterPdb();
836 else if (currentView == VIEWS_FROM_FILE)
838 validateAssociationFromFile();
841 btn_newView.setEnabled(btn_add.isEnabled());
844 * enable 'Superpose' option if more than one structure is selected,
845 * or there are view(s) available to add structure(s) to
848 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
852 protected boolean showPopupFor(int selectedRow, int x, int y)
854 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
856 String currentView = selectedFilterOpt.getView();
858 if (currentView == VIEWS_FILTER
859 && 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
892 * Validates inputs from the Manual PDB entry panel
894 protected void validateAssociationEnterPdb()
896 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
897 .getCmb_assSeq().getSelectedItem();
898 lbl_pdbManualFetchStatus.setIcon(errorImage);
899 lbl_pdbManualFetchStatus.setToolTipText("");
900 if (txt_search.getText().length() > 0)
902 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
903 MessageManager.formatMessage("info.no_pdb_entry_found_for",
904 txt_search.getText())));
907 if (errorWarning.length() > 0)
909 lbl_pdbManualFetchStatus.setIcon(warningImage);
910 lbl_pdbManualFetchStatus.setToolTipText(
911 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
914 if (selectedSequences.length == 1 || !assSeqOpt.getName()
915 .equalsIgnoreCase("-Select Associated Seq-"))
917 txt_search.setEnabled(true);
920 btn_add.setEnabled(true);
921 lbl_pdbManualFetchStatus.setToolTipText("");
922 lbl_pdbManualFetchStatus.setIcon(goodImage);
927 txt_search.setEnabled(false);
928 lbl_pdbManualFetchStatus.setIcon(errorImage);
933 * Validates inputs for the manual PDB file selection options
935 protected void validateAssociationFromFile()
937 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
938 .getCmb_assSeq().getSelectedItem();
939 lbl_fromFileStatus.setIcon(errorImage);
940 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
941 .getName().equalsIgnoreCase("-Select Associated Seq-")))
943 btn_pdbFromFile.setEnabled(true);
944 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
946 btn_add.setEnabled(true);
947 lbl_fromFileStatus.setIcon(goodImage);
952 btn_pdbFromFile.setEnabled(false);
953 lbl_fromFileStatus.setIcon(errorImage);
958 protected void cmbAssSeqStateChanged()
960 validateSelections();
963 private FilterOption lastSelected = null;
966 * Handles the state change event for the 'filter' combo-box and 'invert'
970 protected void stateChanged(ItemEvent e)
972 if (e.getSource() instanceof JCheckBox)
978 if (e.getStateChange() == ItemEvent.SELECTED)
987 * select structures for viewing by their PDB IDs
990 * @return true if structures were found and marked as selected
992 public boolean selectStructure(String... pdbids)
994 boolean found = false;
996 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
998 String currentView = selectedFilterOpt.getView();
999 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1000 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
1002 if (restable == null)
1004 // can't select (enter PDB ID, or load file - need to also select which
1005 // sequence to associate with)
1009 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
1010 for (int r = 0; r < restable.getRowCount(); r++)
1012 for (int p = 0; p < pdbids.length; p++)
1014 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1015 .equalsIgnoreCase(pdbids[p]))
1017 restable.setRowSelectionInterval(r, r);
1026 * Handles the 'New View' action
1029 protected void newView_ActionPerformed()
1031 targetView.setSelectedItem(null);
1032 showStructures(false);
1036 * Handles the 'Add to existing viewer' action
1039 protected void add_ActionPerformed()
1041 showStructures(false);
1045 * structure viewer opened by this dialog, or null
1047 private StructureViewer sViewer = null;
1049 public void showStructures(boolean waitUntilFinished)
1052 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1054 final int preferredHeight = pnl_filter.getHeight();
1056 Runnable viewStruc = new Runnable()
1061 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1062 .getSelectedItem());
1063 String currentView = selectedFilterOpt.getView();
1064 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1067 if (currentView == VIEWS_FILTER)
1069 int[] selectedRows = restable.getSelectedRows();
1070 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1071 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1072 pdbEntriesToView = data.collectSelectedRows(restable,
1073 selectedRows, selectedSeqsToView);
1075 SequenceI[] selectedSeqs = selectedSeqsToView
1076 .toArray(new SequenceI[selectedSeqsToView.size()]);
1077 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1080 else if (currentView == VIEWS_LOCAL_PDB)
1082 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1083 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1085 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1087 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1089 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1090 for (int row : selectedRows)
1092 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1093 .getModel()).getPDBEntryAt(row).getPdbEntry();
1095 pdbEntriesToView[count++] = pdbEntry;
1096 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1097 .getValueAt(row, refSeqColIndex);
1098 selectedSeqsToView.add(selectedSeq);
1100 SequenceI[] selectedSeqs = selectedSeqsToView
1101 .toArray(new SequenceI[selectedSeqsToView.size()]);
1102 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1105 else if (currentView == VIEWS_ENTER_ID)
1107 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1108 .getCmb_assSeq().getSelectedItem()).getSequence();
1109 if (userSelectedSeq != null)
1111 selectedSequence = userSelectedSeq;
1113 String pdbIdStr = txt_search.getText();
1114 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1115 if (pdbEntry == null)
1117 pdbEntry = new PDBEntry();
1118 if (pdbIdStr.split(":").length > 1)
1120 pdbEntry.setId(pdbIdStr.split(":")[0]);
1121 pdbEntry.setChainCode(
1122 pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1126 pdbEntry.setId(pdbIdStr);
1128 pdbEntry.setType(PDBEntry.Type.PDB);
1129 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1132 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1133 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1135 { selectedSequence });
1137 else if (currentView == VIEWS_FROM_FILE)
1139 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1140 .getCmb_assSeq().getSelectedItem()).getSequence();
1141 if (userSelectedSeq != null)
1143 selectedSequence = userSelectedSeq;
1145 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1146 .associatePdbWithSeq(selectedPdbFileName,
1147 DataSourceType.FILE, selectedSequence, true,
1150 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1152 { selectedSequence });
1154 SwingUtilities.invokeLater(new Runnable()
1159 closeAction(preferredHeight);
1160 mainFrame.dispose();
1165 Thread runner = new Thread(viewStruc);
1167 if (waitUntilFinished)
1169 while (sViewer == null ? runner.isAlive()
1170 : (sViewer.sview == null ? true
1171 : !sViewer.sview.hasMapping()))
1176 } catch (InterruptedException ie)
1185 * Answers a structure viewer (new or existing) configured to superimpose
1186 * added structures or not according to the user's choice
1191 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1193 Object sv = targetView.getSelectedItem();
1195 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1199 * Adds PDB structures to a new or existing structure viewer
1202 * @param pdbEntriesToView
1207 private StructureViewer launchStructureViewer(
1208 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1209 final AlignmentPanel alignPanel, SequenceI[] sequences)
1211 long progressId = sequences.hashCode();
1212 setProgressBar(MessageManager
1213 .getString("status.launching_3d_structure_viewer"), progressId);
1214 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1215 boolean superimpose = chk_superpose.isSelected();
1216 theViewer.setSuperpose(superimpose);
1219 * remember user's choice of superimpose or not
1221 Cache.setProperty(AUTOSUPERIMPOSE,
1222 Boolean.valueOf(superimpose).toString());
1224 setProgressBar(null, progressId);
1225 if (SiftsSettings.isMapWithSifts())
1227 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1229 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1230 // real PDB ID. For moment, we can also safely do this if there is already
1231 // a known mapping between the PDBEntry and the sequence.
1232 for (SequenceI seq : sequences)
1234 PDBEntry pdbe = pdbEntriesToView[p++];
1235 if (pdbe != null && pdbe.getFile() != null)
1237 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1238 if (smm != null && smm.length > 0)
1240 for (StructureMapping sm : smm)
1242 if (sm.getSequence() == seq)
1249 if (seq.getPrimaryDBRefs().isEmpty())
1251 seqsWithoutSourceDBRef.add(seq);
1255 if (!seqsWithoutSourceDBRef.isEmpty())
1257 int y = seqsWithoutSourceDBRef.size();
1258 setProgressBar(MessageManager.formatMessage(
1259 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1261 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1262 .toArray(new SequenceI[y]);
1263 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1264 dbRefFetcher.fetchDBRefs(true);
1266 setProgressBar("Fetch complete.", progressId); // todo i18n
1269 if (pdbEntriesToView.length > 1)
1272 MessageManager.getString(
1273 "status.fetching_3d_structures_for_selected_entries"),
1275 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1279 setProgressBar(MessageManager.formatMessage(
1280 "status.fetching_3d_structures_for",
1281 pdbEntriesToView[0].getId()), progressId);
1282 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1284 setProgressBar(null, progressId);
1285 // remember the last viewer we used...
1286 lastTargetedView = theViewer;
1291 * Populates the combo-box used in associating manually fetched structures to
1292 * a unique sequence when more than one sequence selection is made.
1295 protected void populateCmbAssociateSeqOptions(
1296 JComboBox<AssociateSeqOptions> cmb_assSeq,
1297 JLabel lbl_associateSeq)
1299 cmb_assSeq.removeAllItems();
1301 new AssociateSeqOptions("-Select Associated Seq-", null));
1302 lbl_associateSeq.setVisible(false);
1303 if (selectedSequences.length > 1)
1305 for (SequenceI seq : selectedSequences)
1307 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1312 String seqName = selectedSequence.getDisplayId(false);
1313 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1314 lbl_associateSeq.setText(seqName);
1315 lbl_associateSeq.setVisible(true);
1316 cmb_assSeq.setVisible(false);
1320 protected boolean isStructuresDiscovered()
1322 return discoveredStructuresSet != null
1323 && !discoveredStructuresSet.isEmpty();
1326 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1328 // Doing a search for "1" or "1c" is valuable?
1329 // Those work but are enormously slow.
1332 protected void txt_search_ActionPerformed()
1334 String text = txt_search.getText().trim();
1335 if (text.length() >= PDB_ID_MIN)
1342 errorWarning.setLength(0);
1343 isValidPBDEntry = false;
1344 if (text.length() > 0)
1346 // TODO move this pdb id search into the PDB specific
1348 // for moment, it will work fine as is because it is self-contained
1349 String searchTerm = text.toLowerCase(Locale.ROOT);
1350 searchTerm = searchTerm.split(":")[0];
1351 // System.out.println(">>>>> search term : " + searchTerm);
1352 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1353 FTSRestRequest pdbRequest = new FTSRestRequest();
1354 pdbRequest.setAllowEmptySeq(false);
1355 pdbRequest.setResponseSize(1);
1356 pdbRequest.setFieldToSearchBy("(pdb_id:");
1357 pdbRequest.setWantedFields(wantedFields);
1358 pdbRequest.setSearchTerm(searchTerm + ")");
1359 pdbRequest.setAssociatedSequence(selectedSequence);
1360 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1361 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1362 FTSRestResponse resultList;
1365 resultList = pdbRestClient.executeRequest(pdbRequest);
1366 } catch (Exception e)
1368 errorWarning.append(e.getMessage());
1372 validateSelections();
1374 if (resultList.getSearchSummary() != null
1375 && resultList.getSearchSummary().size() > 0)
1377 isValidPBDEntry = true;
1380 validateSelections();
1386 protected void tabRefresh()
1388 if (selectedSequences != null)
1390 Thread refreshThread = new Thread(new Runnable()
1395 fetchStructuresMetaData();
1396 // populateFilterComboBox(true, cachedPDBExists);
1399 ((FilterOption) cmb_filterOption.getSelectedItem())
1403 refreshThread.start();
1407 public class PDBEntryTableModel extends AbstractTableModel
1409 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1412 private List<CachedPDB> pdbEntries;
1414 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1416 this.pdbEntries = new ArrayList<>(pdbEntries);
1420 public String getColumnName(int columnIndex)
1422 return columns[columnIndex];
1426 public int getRowCount()
1428 return pdbEntries.size();
1432 public int getColumnCount()
1434 return columns.length;
1438 public boolean isCellEditable(int row, int column)
1444 public Object getValueAt(int rowIndex, int columnIndex)
1446 Object value = "??";
1447 CachedPDB entry = pdbEntries.get(rowIndex);
1448 switch (columnIndex)
1451 value = entry.getSequence();
1454 value = entry.getQualifiedId();
1457 value = entry.getPdbEntry().getChainCode() == null ? "_"
1458 : entry.getPdbEntry().getChainCode();
1461 value = entry.getPdbEntry().getType();
1464 value = entry.getPdbEntry().getFile();
1471 public Class<?> getColumnClass(int columnIndex)
1473 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1476 public CachedPDB getPDBEntryAt(int row)
1478 return pdbEntries.get(row);
1483 private class CachedPDB
1485 private SequenceI sequence;
1487 private PDBEntry pdbEntry;
1489 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1491 this.sequence = sequence;
1492 this.pdbEntry = pdbEntry;
1495 public String getQualifiedId()
1497 if (pdbEntry.hasProvider())
1499 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1501 return pdbEntry.toString();
1504 public SequenceI getSequence()
1509 public PDBEntry getPdbEntry()
1516 private IProgressIndicator progressBar;
1519 public void setProgressBar(String message, long id)
1521 progressBar.setProgressBar(message, id);
1525 public void registerHandler(long id, IProgressIndicatorHandler handler)
1527 progressBar.registerHandler(id, handler);
1531 public boolean operationInProgress()
1533 return progressBar.operationInProgress();
1536 public JalviewStructureDisplayI getOpenedStructureViewer()
1538 return sViewer == null ? null : sViewer.sview;
1542 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1544 data.setDocFieldPrefs(newPrefs);
1550 * @return true when all initialisation threads have finished and dialog is
1553 public boolean isDialogVisible()
1555 return mainFrame != null && data != null && cmb_filterOption != null
1556 && mainFrame.isVisible()
1557 && cmb_filterOption.getSelectedItem() != null;
1562 * @return true if the 3D-Beacons query button will/has been displayed
1564 public boolean isCanQueryTDB()
1569 public boolean isNotQueriedTDBYet()
1571 return notQueriedTDBYet;