2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
24 import java.awt.event.ActionEvent;
25 import java.awt.event.ActionListener;
26 import java.awt.event.ItemEvent;
27 import java.util.ArrayList;
28 import java.util.Collection;
29 import java.util.HashSet;
30 import java.util.LinkedHashSet;
31 import java.util.List;
32 import java.util.Locale;
33 import java.util.concurrent.Executors;
35 import javax.swing.JCheckBox;
36 import javax.swing.JComboBox;
37 import javax.swing.JLabel;
38 import javax.swing.JMenu;
39 import javax.swing.JMenuItem;
40 import javax.swing.JPopupMenu;
41 import javax.swing.JTable;
42 import javax.swing.SwingUtilities;
43 import javax.swing.table.AbstractTableModel;
45 import jalview.api.structures.JalviewStructureDisplayI;
46 import jalview.bin.Cache;
47 import jalview.bin.Jalview;
48 import jalview.datamodel.PDBEntry;
49 import jalview.datamodel.SequenceI;
50 import jalview.fts.api.FTSData;
51 import jalview.fts.api.FTSDataColumnI;
52 import jalview.fts.api.FTSRestClientI;
53 import jalview.fts.core.FTSDataColumnPreferences;
54 import jalview.fts.core.FTSRestRequest;
55 import jalview.fts.core.FTSRestResponse;
56 import jalview.fts.service.pdb.PDBFTSRestClient;
57 import jalview.fts.service.threedbeacons.TDB_FTSData;
58 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
59 import jalview.gui.structurechooser.StructureChooserQuerySource;
60 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
61 import jalview.io.DataSourceType;
62 import jalview.jbgui.FilterOption;
63 import jalview.jbgui.GStructureChooser;
64 import jalview.structure.StructureMapping;
65 import jalview.structure.StructureSelectionManager;
66 import jalview.util.MessageManager;
67 import jalview.ws.DBRefFetcher;
68 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
69 import jalview.ws.seqfetcher.DbSourceProxy;
70 import jalview.ws.sifts.SiftsSettings;
73 * Provides the behaviors for the Structure chooser Panel
78 @SuppressWarnings("serial")
79 public class StructureChooser extends GStructureChooser
80 implements IProgressIndicator
82 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
84 private SequenceI selectedSequence;
86 private SequenceI[] selectedSequences;
88 private IProgressIndicator progressIndicator;
90 private Collection<FTSData> discoveredStructuresSet;
92 private StructureChooserQuerySource data;
95 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
97 return data.getDocFieldPrefs();
100 private String selectedPdbFileName;
102 private boolean isValidPBDEntry;
104 private boolean cachedPDBExists;
106 private Collection<FTSData> lastDiscoveredStructuresSet;
108 private boolean canQueryTDB = false;
110 private boolean notQueriedTDBYet = true;
112 List<SequenceI> seqsWithoutSourceDBRef = null;
114 private static StructureViewer lastTargetedView = null;
116 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
119 // which FTS engine to use
120 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
124 this.selectedSequence = selectedSeq;
125 this.selectedSequences = selectedSeqs;
126 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
132 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
133 * least one structure are discovered.
135 private void populateSeqsWithoutSourceDBRef()
137 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
138 boolean needCanonical = false;
139 for (SequenceI seq : selectedSequences)
143 int dbRef = ThreeDBStructureChooserQuerySource
144 .checkUniprotRefs(seq.getDBRefs());
149 // need to retrieve canonicals
150 needCanonical = true;
151 seqsWithoutSourceDBRef.add(seq);
155 // could be a sequence with pdb ref
156 if (seq.getAllPDBEntries() == null
157 || seq.getAllPDBEntries().size() == 0)
159 seqsWithoutSourceDBRef.add(seq);
165 // retrieve database refs for protein sequences
166 if (!seqsWithoutSourceDBRef.isEmpty())
171 // triggers display of the 'Query TDB' button
172 notQueriedTDBYet = true;
178 * Initializes parameters used by the Structure Chooser Panel
180 protected void init()
182 if (!Jalview.isHeadlessMode())
184 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
187 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
188 btn_queryTDB.addActionListener(new ActionListener()
192 public void actionPerformed(ActionEvent e)
198 Executors.defaultThreadFactory().newThread(new Runnable()
202 populateSeqsWithoutSourceDBRef();
203 initialStructureDiscovery();
211 private void initialStructureDiscovery()
213 // check which FTS engine to use
214 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
216 // ensure a filter option is in force for search
217 populateFilterComboBox(true, cachedPDBExists);
219 // looks for any existing structures already loaded
220 // for the sequences (the cached ones)
221 // then queries the StructureChooserQuerySource to
222 // discover more structures.
224 // Possible optimisation is to only begin querying
225 // the structure chooser if there are no cached structures.
227 long startTime = System.currentTimeMillis();
228 updateProgressIndicator(
229 MessageManager.getString("status.loading_cached_pdb_entries"),
231 loadLocalCachedPDBEntries();
232 updateProgressIndicator(null, startTime);
233 updateProgressIndicator(
234 MessageManager.getString("status.searching_for_pdb_structures"),
236 fetchStructuresMetaData();
237 // revise filter options if no results were found
238 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
239 discoverStructureViews();
240 updateProgressIndicator(null, startTime);
241 mainFrame.setVisible(true);
245 private void promptForTDBFetch()
247 final long progressId = System.currentTimeMillis();
249 // final action after prompting and discovering db refs
250 final Runnable strucDiscovery = new Runnable()
255 mainFrame.setEnabled(false);
256 cmb_filterOption.setEnabled(false);
257 progressBar.setProgressBar(MessageManager.getString("status.searching_3d_beacons"), progressId);
258 // TODO: warn if no accessions discovered
259 populateSeqsWithoutSourceDBRef();
260 // redo initial discovery - this time with 3d beacons
262 previousWantedFields=null;
263 initialStructureDiscovery();
264 if (!isStructuresDiscovered())
266 progressBar.setProgressBar(MessageManager.getString("status.no_structures_discovered_from_3d_beacons"), progressId);
267 btn_queryTDB.setToolTipText(MessageManager.getString("status.no_structures_discovered_from_3d_beacons"));
268 btn_queryTDB.setEnabled(false);
270 btn_queryTDB.setVisible(false);
271 progressBar.setProgressBar(null, progressId);
273 mainFrame.setEnabled(true);
274 cmb_filterOption.setEnabled(true);
278 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
282 public void finished()
284 // filter has been selected, so we set flag to remove ourselves
285 notQueriedTDBYet = false;
286 // new thread to discover structures - via 3d beacons
287 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
292 // fetch db refs if OK pressed
293 final Runnable discoverCanonicalDBrefs = new Runnable()
298 populateSeqsWithoutSourceDBRef();
300 final int y = seqsWithoutSourceDBRef.size();
303 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
304 .toArray(new SequenceI[y]);
305 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
306 progressBar, new DbSourceProxy[]
307 { new jalview.ws.dbsources.Uniprot() }, null, false);
308 dbRefFetcher.addListener(afterDbRefFetch);
309 // ideally this would also gracefully run with callbacks
310 dbRefFetcher.fetchDBRefs(true);
312 // call finished action directly
313 afterDbRefFetch.finished();
318 final Runnable revertview = new Runnable() {
320 if (lastSelected!=null) {
321 cmb_filterOption.setSelectedItem(lastSelected);
325 // need cancel and no to result in the discoverPDB action - mocked is
327 JvOptionPane.newOptionDialog(this)
328 .setResponseHandler(JvOptionPane.OK_OPTION,
329 discoverCanonicalDBrefs)
330 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
331 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
333 MessageManager.formatMessage(
334 "label.fetch_references_for_3dbeacons",
335 seqsWithoutSourceDBRef.size()),
337 .getString("label.3dbeacons"),
338 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
340 { MessageManager.getString("action.ok"),
341 MessageManager.getString("action.cancel") },
342 MessageManager.getString("action.ok"));
346 * Builds a drop-down choice list of existing structure viewers to which new
347 * structures may be added. If this list is empty then it, and the 'Add'
348 * button, are hidden.
350 private void discoverStructureViews()
352 if (Desktop.instance != null)
354 targetView.removeAllItems();
355 if (lastTargetedView != null && !lastTargetedView.isVisible())
357 lastTargetedView = null;
359 int linkedViewsAt = 0;
360 for (StructureViewerBase view : Desktop.instance
361 .getStructureViewers(null, null))
363 StructureViewer viewHandler = (lastTargetedView != null
364 && lastTargetedView.sview == view) ? lastTargetedView
365 : StructureViewer.reconfigure(view);
367 if (view.isLinkedWith(ap))
369 targetView.insertItemAt(viewHandler, linkedViewsAt++);
373 targetView.addItem(viewHandler);
378 * show option to Add to viewer if at least 1 viewer found
380 targetView.setVisible(false);
381 if (targetView.getItemCount() > 0)
383 targetView.setVisible(true);
384 if (lastTargetedView != null)
386 targetView.setSelectedItem(lastTargetedView);
390 targetView.setSelectedIndex(0);
393 btn_add.setVisible(targetView.isVisible());
398 * Updates the progress indicator with the specified message
401 * displayed message for the operation
403 * unique handle for this indicator
405 protected void updateProgressIndicator(String message, long id)
407 if (progressIndicator != null)
409 progressIndicator.setProgressBar(message, id);
414 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
417 void fetchStructuresMetaData()
419 long startTime = System.currentTimeMillis();
420 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
421 .getStructureSummaryFields();
423 discoveredStructuresSet = new LinkedHashSet<>();
424 HashSet<String> errors = new HashSet<>();
426 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
429 for (SequenceI seq : selectedSequences)
432 FTSRestResponse resultList;
435 resultList = data.fetchStructuresMetaData(seq, wantedFields,
436 selectedFilterOpt, !chk_invertFilter.isSelected());
437 // null response means the FTSengine didn't yield a query for this
438 // consider designing a special exception if we really wanted to be
440 if (resultList == null)
444 } catch (Exception e)
447 errors.add(e.getMessage());
450 if (resultList.getSearchSummary() != null
451 && !resultList.getSearchSummary().isEmpty())
453 discoveredStructuresSet.addAll(resultList.getSearchSummary());
457 int noOfStructuresFound = 0;
458 String totalTime = (System.currentTimeMillis() - startTime)
460 if (discoveredStructuresSet != null
461 && !discoveredStructuresSet.isEmpty())
464 .setModel(data.getTableModel(discoveredStructuresSet));
466 noOfStructuresFound = discoveredStructuresSet.size();
467 lastDiscoveredStructuresSet = discoveredStructuresSet;
468 mainFrame.setTitle(MessageManager.formatMessage(
469 "label.structure_chooser_no_of_structures",
470 noOfStructuresFound, totalTime));
474 mainFrame.setTitle(MessageManager
475 .getString("label.structure_chooser_manual_association"));
476 if (errors.size() > 0)
478 StringBuilder errorMsg = new StringBuilder();
479 for (String error : errors)
481 errorMsg.append(error).append("\n");
483 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
484 MessageManager.getString("label.pdb_web-service_error"),
485 JvOptionPane.ERROR_MESSAGE);
490 protected void loadLocalCachedPDBEntries()
492 ArrayList<CachedPDB> entries = new ArrayList<>();
493 for (SequenceI seq : selectedSequences)
495 if (seq.getDatasetSequence() != null
496 && seq.getDatasetSequence().getAllPDBEntries() != null)
498 for (PDBEntry pdbEntry : seq.getDatasetSequence()
501 if (pdbEntry.getFile() != null)
503 entries.add(new CachedPDB(seq, pdbEntry));
508 cachedPDBExists = !entries.isEmpty();
509 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
510 tbl_local_pdb.setModel(tableModelx);
514 * Filters a given list of discovered structures based on supplied argument
516 * @param fieldToFilterBy
517 * the field to filter by
519 void filterResultSet(final String fieldToFilterBy)
521 Thread filterThread = new Thread(new Runnable()
527 long startTime = System.currentTimeMillis();
528 lbl_loading.setVisible(true);
529 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
530 .getStructureSummaryFields();
531 Collection<FTSData> filteredResponse = new HashSet<>();
532 HashSet<String> errors = new HashSet<>();
534 for (SequenceI seq : selectedSequences)
537 FTSRestResponse resultList;
540 resultList = data.selectFirstRankedQuery(seq,
541 discoveredStructuresSet, wantedFields, fieldToFilterBy,
542 !chk_invertFilter.isSelected());
544 } catch (Exception e)
547 errors.add(e.getMessage());
550 if (resultList.getSearchSummary() != null
551 && !resultList.getSearchSummary().isEmpty())
553 filteredResponse.addAll(resultList.getSearchSummary());
557 String totalTime = (System.currentTimeMillis() - startTime)
559 if (!filteredResponse.isEmpty())
561 final int filterResponseCount = filteredResponse.size();
562 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
563 reorderedStructuresSet.addAll(filteredResponse);
564 reorderedStructuresSet.addAll(discoveredStructuresSet);
566 .setModel(data.getTableModel(reorderedStructuresSet));
568 FTSRestResponse.configureTableColumn(getResultTable(),
569 wantedFields, tempUserPrefs);
570 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
571 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
572 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
573 // Update table selection model here
574 getResultTable().addRowSelectionInterval(0,
575 filterResponseCount - 1);
576 mainFrame.setTitle(MessageManager.formatMessage(
577 "label.structure_chooser_filter_time", totalTime));
581 mainFrame.setTitle(MessageManager.formatMessage(
582 "label.structure_chooser_filter_time", totalTime));
583 if (errors.size() > 0)
585 StringBuilder errorMsg = new StringBuilder();
586 for (String error : errors)
588 errorMsg.append(error).append("\n");
590 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
591 MessageManager.getString("label.pdb_web-service_error"),
592 JvOptionPane.ERROR_MESSAGE);
596 lbl_loading.setVisible(false);
598 validateSelections();
601 filterThread.start();
605 * Handles action event for btn_pdbFromFile
608 protected void pdbFromFile_actionPerformed()
610 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
613 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
614 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
615 chooser.setFileView(new jalview.io.JalviewFileView());
616 chooser.setDialogTitle(
617 MessageManager.formatMessage("label.select_pdb_file_for",
618 selectedSequence.getDisplayId(false)));
619 chooser.setToolTipText(MessageManager.formatMessage(
620 "label.load_pdb_file_associate_with_sequence",
621 selectedSequence.getDisplayId(false)));
623 int value = chooser.showOpenDialog(null);
624 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
626 selectedPdbFileName = chooser.getSelectedFile().getPath();
627 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
628 validateSelections();
633 * Populates the filter combo-box options dynamically depending on discovered
636 protected void populateFilterComboBox(boolean haveData,
637 boolean cachedPDBExist)
639 populateFilterComboBox(haveData, cachedPDBExist, null);
643 * Populates the filter combo-box options dynamically depending on discovered
646 protected void populateFilterComboBox(boolean haveData,
647 boolean cachedPDBExist, FilterOption lastSel)
651 * temporarily suspend the change listener behaviour
653 cmb_filterOption.removeItemListener(this);
655 cmb_filterOption.removeAllItems();
658 List<FilterOption> filters = data
659 .getAvailableFilterOptions(VIEWS_FILTER);
660 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
661 lastDiscoveredStructuresSet);
663 for (FilterOption filter : filters)
665 if (lastSel != null && filter.equals(lastSel))
670 cmb_filterOption.addItem(filter);
674 cmb_filterOption.addItem(
675 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
676 "-", VIEWS_ENTER_ID, false, null));
677 cmb_filterOption.addItem(
678 new FilterOption(MessageManager.getString("label.from_file"),
679 "-", VIEWS_FROM_FILE, false, null));
680 if (canQueryTDB && notQueriedTDBYet)
682 btn_queryTDB.setVisible(true);
687 FilterOption cachedOption = new FilterOption(
688 MessageManager.getString("label.cached_structures"), "-",
689 VIEWS_LOCAL_PDB, false, null);
690 cmb_filterOption.addItem(cachedOption);
693 cmb_filterOption.setSelectedItem(cachedOption);
698 cmb_filterOption.setSelectedIndex(selSet);
700 cmb_filterOption.addItemListener(this);
704 * Updates the displayed view based on the selected filter option
706 protected void updateCurrentView()
708 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
711 if (lastSelected == selectedFilterOpt)
713 // don't need to do anything, probably
716 // otherwise, record selection
717 // and update the layout and dialog accordingly
718 lastSelected = selectedFilterOpt;
720 layout_switchableViews.show(pnl_switchableViews,
721 selectedFilterOpt.getView());
722 String filterTitle = mainFrame.getTitle();
723 mainFrame.setTitle(frameTitle);
724 chk_invertFilter.setVisible(false);
726 if (selectedFilterOpt.getView() == VIEWS_FILTER)
728 mainFrame.setTitle(filterTitle);
729 // TDB Query has no invert as yet
730 chk_invertFilter.setVisible(selectedFilterOpt
731 .getQuerySource() instanceof PDBStructureChooserQuerySource);
733 if (data != selectedFilterOpt.getQuerySource()
734 || data.needsRefetch(selectedFilterOpt))
736 data = selectedFilterOpt.getQuerySource();
737 // rebuild the views completely, since prefs will also change
743 filterResultSet(selectedFilterOpt.getValue());
746 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
747 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
749 mainFrame.setTitle(MessageManager
750 .getString("label.structure_chooser_manual_association"));
751 idInputAssSeqPanel.loadCmbAssSeq();
752 fileChooserAssSeqPanel.loadCmbAssSeq();
754 validateSelections();
758 * Validates user selection and enables the 'Add' and 'New View' buttons if
759 * all parameters are correct (the Add button will only be visible if there is
760 * at least one existing structure viewer open). This basically means at least
761 * one structure selected and no error messages.
763 * The 'Superpose Structures' option is enabled if either more than one
764 * structure is selected, or the 'Add' to existing view option is enabled, and
765 * disabled if the only option is to open a new view of a single structure.
768 protected void validateSelections()
770 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
772 btn_add.setEnabled(false);
773 String currentView = selectedFilterOpt.getView();
774 int selectedCount = 0;
775 if (currentView == VIEWS_FILTER)
777 selectedCount = getResultTable().getSelectedRows().length;
778 if (selectedCount > 0)
780 btn_add.setEnabled(true);
783 else if (currentView == VIEWS_LOCAL_PDB)
785 selectedCount = tbl_local_pdb.getSelectedRows().length;
786 if (selectedCount > 0)
788 btn_add.setEnabled(true);
791 else if (currentView == VIEWS_ENTER_ID)
793 validateAssociationEnterPdb();
795 else if (currentView == VIEWS_FROM_FILE)
797 validateAssociationFromFile();
800 btn_newView.setEnabled(btn_add.isEnabled());
803 * enable 'Superpose' option if more than one structure is selected,
804 * or there are view(s) available to add structure(s) to
807 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
811 protected boolean showPopupFor(int selectedRow, int x, int y)
813 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
815 String currentView = selectedFilterOpt.getView();
817 if (currentView == VIEWS_FILTER && data instanceof ThreeDBStructureChooserQuerySource)
820 TDB_FTSData row=((ThreeDBStructureChooserQuerySource)data).getFTSDataFor(getResultTable(), selectedRow, discoveredStructuresSet);
821 String pageUrl = row.getModelViewUrl();
822 JPopupMenu popup = new JPopupMenu("3D Beacons");
823 JMenuItem viewUrl = new JMenuItem("View model web page");
824 viewUrl.addActionListener(
825 new ActionListener() {
827 public void actionPerformed(ActionEvent e)
829 Desktop.showUrl(pageUrl);
834 SwingUtilities.invokeLater(new Runnable() {
835 public void run() { popup.show(getResultTable(), x, y); }
839 // event not handled by us
843 * Validates inputs from the Manual PDB entry panel
845 protected void validateAssociationEnterPdb()
847 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
848 .getCmb_assSeq().getSelectedItem();
849 lbl_pdbManualFetchStatus.setIcon(errorImage);
850 lbl_pdbManualFetchStatus.setToolTipText("");
851 if (txt_search.getText().length() > 0)
853 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
854 MessageManager.formatMessage("info.no_pdb_entry_found_for",
855 txt_search.getText())));
858 if (errorWarning.length() > 0)
860 lbl_pdbManualFetchStatus.setIcon(warningImage);
861 lbl_pdbManualFetchStatus.setToolTipText(
862 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
865 if (selectedSequences.length == 1 || !assSeqOpt.getName()
866 .equalsIgnoreCase("-Select Associated Seq-"))
868 txt_search.setEnabled(true);
871 btn_add.setEnabled(true);
872 lbl_pdbManualFetchStatus.setToolTipText("");
873 lbl_pdbManualFetchStatus.setIcon(goodImage);
878 txt_search.setEnabled(false);
879 lbl_pdbManualFetchStatus.setIcon(errorImage);
884 * Validates inputs for the manual PDB file selection options
886 protected void validateAssociationFromFile()
888 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
889 .getCmb_assSeq().getSelectedItem();
890 lbl_fromFileStatus.setIcon(errorImage);
891 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
892 .getName().equalsIgnoreCase("-Select Associated Seq-")))
894 btn_pdbFromFile.setEnabled(true);
895 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
897 btn_add.setEnabled(true);
898 lbl_fromFileStatus.setIcon(goodImage);
903 btn_pdbFromFile.setEnabled(false);
904 lbl_fromFileStatus.setIcon(errorImage);
909 protected void cmbAssSeqStateChanged()
911 validateSelections();
913 private FilterOption lastSelected=null;
915 * Handles the state change event for the 'filter' combo-box and 'invert'
919 protected void stateChanged(ItemEvent e)
921 if (e.getSource() instanceof JCheckBox)
927 if (e.getStateChange() == ItemEvent.SELECTED)
936 * select structures for viewing by their PDB IDs
939 * @return true if structures were found and marked as selected
941 public boolean selectStructure(String... pdbids)
943 boolean found = false;
945 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
947 String currentView = selectedFilterOpt.getView();
948 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
949 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
951 if (restable == null)
953 // can't select (enter PDB ID, or load file - need to also select which
954 // sequence to associate with)
958 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
959 for (int r = 0; r < restable.getRowCount(); r++)
961 for (int p = 0; p < pdbids.length; p++)
963 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
964 .equalsIgnoreCase(pdbids[p]))
966 restable.setRowSelectionInterval(r, r);
975 * Handles the 'New View' action
978 protected void newView_ActionPerformed()
980 targetView.setSelectedItem(null);
981 showStructures(false);
985 * Handles the 'Add to existing viewer' action
988 protected void add_ActionPerformed()
990 showStructures(false);
994 * structure viewer opened by this dialog, or null
996 private StructureViewer sViewer = null;
998 public void showStructures(boolean waitUntilFinished)
1001 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1003 final int preferredHeight = pnl_filter.getHeight();
1005 Runnable viewStruc = new Runnable()
1010 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1011 .getSelectedItem());
1012 String currentView = selectedFilterOpt.getView();
1013 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1016 if (currentView == VIEWS_FILTER)
1018 int[] selectedRows = restable.getSelectedRows();
1019 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1020 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1021 pdbEntriesToView = data.collectSelectedRows(restable,
1022 selectedRows, selectedSeqsToView);
1024 SequenceI[] selectedSeqs = selectedSeqsToView
1025 .toArray(new SequenceI[selectedSeqsToView.size()]);
1026 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1029 else if (currentView == VIEWS_LOCAL_PDB)
1031 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1032 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1034 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1036 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1038 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1039 for (int row : selectedRows)
1041 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1042 .getModel()).getPDBEntryAt(row).getPdbEntry();
1044 pdbEntriesToView[count++] = pdbEntry;
1045 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1046 .getValueAt(row, refSeqColIndex);
1047 selectedSeqsToView.add(selectedSeq);
1049 SequenceI[] selectedSeqs = selectedSeqsToView
1050 .toArray(new SequenceI[selectedSeqsToView.size()]);
1051 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1054 else if (currentView == VIEWS_ENTER_ID)
1056 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1057 .getCmb_assSeq().getSelectedItem()).getSequence();
1058 if (userSelectedSeq != null)
1060 selectedSequence = userSelectedSeq;
1062 String pdbIdStr = txt_search.getText();
1063 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1064 if (pdbEntry == null)
1066 pdbEntry = new PDBEntry();
1067 if (pdbIdStr.split(":").length > 1)
1069 pdbEntry.setId(pdbIdStr.split(":")[0]);
1070 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1074 pdbEntry.setId(pdbIdStr);
1076 pdbEntry.setType(PDBEntry.Type.PDB);
1077 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1080 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1081 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1083 { selectedSequence });
1085 else if (currentView == VIEWS_FROM_FILE)
1087 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1088 .getCmb_assSeq().getSelectedItem()).getSequence();
1089 if (userSelectedSeq != null)
1091 selectedSequence = userSelectedSeq;
1093 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1094 .associatePdbWithSeq(selectedPdbFileName,
1095 DataSourceType.FILE, selectedSequence, true,
1098 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1100 { selectedSequence });
1102 SwingUtilities.invokeLater(new Runnable()
1107 closeAction(preferredHeight);
1108 mainFrame.dispose();
1113 Thread runner = new Thread(viewStruc);
1115 if (waitUntilFinished)
1117 while (sViewer == null ? runner.isAlive()
1118 : (sViewer.sview == null ? true
1119 : !sViewer.sview.hasMapping()))
1124 } catch (InterruptedException ie)
1133 * Answers a structure viewer (new or existing) configured to superimpose
1134 * added structures or not according to the user's choice
1139 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1141 Object sv = targetView.getSelectedItem();
1143 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1147 * Adds PDB structures to a new or existing structure viewer
1150 * @param pdbEntriesToView
1155 private StructureViewer launchStructureViewer(
1156 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1157 final AlignmentPanel alignPanel, SequenceI[] sequences)
1159 long progressId = sequences.hashCode();
1160 setProgressBar(MessageManager
1161 .getString("status.launching_3d_structure_viewer"), progressId);
1162 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1163 boolean superimpose = chk_superpose.isSelected();
1164 theViewer.setSuperpose(superimpose);
1167 * remember user's choice of superimpose or not
1169 Cache.setProperty(AUTOSUPERIMPOSE,
1170 Boolean.valueOf(superimpose).toString());
1172 setProgressBar(null, progressId);
1173 if (SiftsSettings.isMapWithSifts())
1175 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1177 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1178 // real PDB ID. For moment, we can also safely do this if there is already
1179 // a known mapping between the PDBEntry and the sequence.
1180 for (SequenceI seq : sequences)
1182 PDBEntry pdbe = pdbEntriesToView[p++];
1183 if (pdbe != null && pdbe.getFile() != null)
1185 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1186 if (smm != null && smm.length > 0)
1188 for (StructureMapping sm : smm)
1190 if (sm.getSequence() == seq)
1197 if (seq.getPrimaryDBRefs().isEmpty())
1199 seqsWithoutSourceDBRef.add(seq);
1203 if (!seqsWithoutSourceDBRef.isEmpty())
1205 int y = seqsWithoutSourceDBRef.size();
1206 setProgressBar(MessageManager.formatMessage(
1207 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1209 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1210 .toArray(new SequenceI[y]);
1211 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1212 dbRefFetcher.fetchDBRefs(true);
1214 setProgressBar("Fetch complete.", progressId); // todo i18n
1217 if (pdbEntriesToView.length > 1)
1220 MessageManager.getString(
1221 "status.fetching_3d_structures_for_selected_entries"),
1223 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1227 setProgressBar(MessageManager.formatMessage(
1228 "status.fetching_3d_structures_for",
1229 pdbEntriesToView[0].getId()), progressId);
1230 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1232 setProgressBar(null, progressId);
1233 // remember the last viewer we used...
1234 lastTargetedView = theViewer;
1239 * Populates the combo-box used in associating manually fetched structures to
1240 * a unique sequence when more than one sequence selection is made.
1243 protected void populateCmbAssociateSeqOptions(
1244 JComboBox<AssociateSeqOptions> cmb_assSeq,
1245 JLabel lbl_associateSeq)
1247 cmb_assSeq.removeAllItems();
1249 new AssociateSeqOptions("-Select Associated Seq-", null));
1250 lbl_associateSeq.setVisible(false);
1251 if (selectedSequences.length > 1)
1253 for (SequenceI seq : selectedSequences)
1255 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1260 String seqName = selectedSequence.getDisplayId(false);
1261 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1262 lbl_associateSeq.setText(seqName);
1263 lbl_associateSeq.setVisible(true);
1264 cmb_assSeq.setVisible(false);
1268 protected boolean isStructuresDiscovered()
1270 return discoveredStructuresSet != null
1271 && !discoveredStructuresSet.isEmpty();
1274 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1276 // Doing a search for "1" or "1c" is valuable?
1277 // Those work but are enormously slow.
1280 protected void txt_search_ActionPerformed()
1282 String text = txt_search.getText().trim();
1283 if (text.length() >= PDB_ID_MIN)
1290 errorWarning.setLength(0);
1291 isValidPBDEntry = false;
1292 if (text.length() > 0)
1294 // TODO move this pdb id search into the PDB specific
1296 // for moment, it will work fine as is because it is self-contained
1297 String searchTerm = text.toLowerCase(Locale.ROOT);
1298 searchTerm = searchTerm.split(":")[0];
1299 // System.out.println(">>>>> search term : " + searchTerm);
1300 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1301 FTSRestRequest pdbRequest = new FTSRestRequest();
1302 pdbRequest.setAllowEmptySeq(false);
1303 pdbRequest.setResponseSize(1);
1304 pdbRequest.setFieldToSearchBy("(pdb_id:");
1305 pdbRequest.setWantedFields(wantedFields);
1306 pdbRequest.setSearchTerm(searchTerm + ")");
1307 pdbRequest.setAssociatedSequence(selectedSequence);
1308 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1309 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1310 FTSRestResponse resultList;
1313 resultList = pdbRestClient.executeRequest(pdbRequest);
1314 } catch (Exception e)
1316 errorWarning.append(e.getMessage());
1320 validateSelections();
1322 if (resultList.getSearchSummary() != null
1323 && resultList.getSearchSummary().size() > 0)
1325 isValidPBDEntry = true;
1328 validateSelections();
1334 protected void tabRefresh()
1336 if (selectedSequences != null)
1338 Thread refreshThread = new Thread(new Runnable()
1343 fetchStructuresMetaData();
1344 // populateFilterComboBox(true, cachedPDBExists);
1347 ((FilterOption) cmb_filterOption.getSelectedItem())
1351 refreshThread.start();
1355 public class PDBEntryTableModel extends AbstractTableModel
1357 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1360 private List<CachedPDB> pdbEntries;
1362 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1364 this.pdbEntries = new ArrayList<>(pdbEntries);
1368 public String getColumnName(int columnIndex)
1370 return columns[columnIndex];
1374 public int getRowCount()
1376 return pdbEntries.size();
1380 public int getColumnCount()
1382 return columns.length;
1386 public boolean isCellEditable(int row, int column)
1392 public Object getValueAt(int rowIndex, int columnIndex)
1394 Object value = "??";
1395 CachedPDB entry = pdbEntries.get(rowIndex);
1396 switch (columnIndex)
1399 value = entry.getSequence();
1402 value = entry.getQualifiedId();
1405 value = entry.getPdbEntry().getChainCode() == null ? "_"
1406 : entry.getPdbEntry().getChainCode();
1409 value = entry.getPdbEntry().getType();
1412 value = entry.getPdbEntry().getFile();
1419 public Class<?> getColumnClass(int columnIndex)
1421 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1424 public CachedPDB getPDBEntryAt(int row)
1426 return pdbEntries.get(row);
1431 private class CachedPDB
1433 private SequenceI sequence;
1435 private PDBEntry pdbEntry;
1437 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1439 this.sequence = sequence;
1440 this.pdbEntry = pdbEntry;
1443 public String getQualifiedId()
1445 if (pdbEntry.hasProvider())
1447 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1449 return pdbEntry.toString();
1452 public SequenceI getSequence()
1457 public PDBEntry getPdbEntry()
1464 private IProgressIndicator progressBar;
1467 public void setProgressBar(String message, long id)
1469 progressBar.setProgressBar(message, id);
1473 public void registerHandler(long id, IProgressIndicatorHandler handler)
1475 progressBar.registerHandler(id, handler);
1479 public boolean operationInProgress()
1481 return progressBar.operationInProgress();
1484 public JalviewStructureDisplayI getOpenedStructureViewer()
1486 return sViewer == null ? null : sViewer.sview;
1490 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1492 data.setDocFieldPrefs(newPrefs);
1498 * @return true when all initialisation threads have finished and dialog is
1501 public boolean isDialogVisible()
1503 return mainFrame != null && data != null && cmb_filterOption != null
1504 && mainFrame.isVisible()
1505 && cmb_filterOption.getSelectedItem() != null;
1509 * @return true if the 3D-Beacons query button will/has been displayed
1511 public boolean isCanQueryTDB() {
1515 public boolean isNotQueriedTDBYet()
1517 return notQueriedTDBYet;