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.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.Jalview;
47 import jalview.datamodel.PDBEntry;
48 import jalview.datamodel.SequenceI;
49 import jalview.fts.api.FTSData;
50 import jalview.fts.api.FTSDataColumnI;
51 import jalview.fts.api.FTSRestClientI;
52 import jalview.fts.core.FTSDataColumnPreferences;
53 import jalview.fts.core.FTSRestRequest;
54 import jalview.fts.core.FTSRestResponse;
55 import jalview.fts.service.pdb.PDBFTSRestClient;
56 import jalview.fts.service.threedbeacons.TDB_FTSData;
57 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
58 import jalview.gui.structurechooser.StructureChooserQuerySource;
59 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
60 import jalview.io.DataSourceType;
61 import jalview.jbgui.FilterOption;
62 import jalview.jbgui.GStructureChooser;
63 import jalview.structure.StructureMapping;
64 import jalview.structure.StructureSelectionManager;
65 import jalview.util.MessageManager;
66 import jalview.ws.DBRefFetcher;
67 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
68 import jalview.ws.seqfetcher.DbSourceProxy;
69 import jalview.ws.sifts.SiftsSettings;
72 * Provides the behaviors for the Structure chooser Panel
77 @SuppressWarnings("serial")
78 public class StructureChooser extends GStructureChooser
79 implements IProgressIndicator
81 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
84 * transient combo box choice for initiating 3db fetch
86 private static final String VIEWS_QUERYING_TDB = "QUERY_3DB";
88 private SequenceI selectedSequence;
90 private SequenceI[] selectedSequences;
92 private IProgressIndicator progressIndicator;
94 private Collection<FTSData> discoveredStructuresSet;
96 private StructureChooserQuerySource data;
99 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
101 return data.getDocFieldPrefs();
104 private String selectedPdbFileName;
106 private boolean isValidPBDEntry;
108 private boolean cachedPDBExists;
110 private Collection<FTSData> lastDiscoveredStructuresSet;
112 private boolean canQueryTDB = false;
114 private boolean notQueriedTDBYet = true;
116 List<SequenceI> seqsWithoutSourceDBRef = null;
118 private static StructureViewer lastTargetedView = null;
120 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
123 // which FTS engine to use
124 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
128 this.selectedSequence = selectedSeq;
129 this.selectedSequences = selectedSeqs;
130 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
136 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
137 * least one structure are discovered.
139 private void populateSeqsWithoutSourceDBRef()
141 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
142 boolean needCanonical = false;
143 for (SequenceI seq : selectedSequences)
147 int dbRef = ThreeDBStructureChooserQuerySource
148 .checkUniprotRefs(seq.getDBRefs());
153 // need to retrieve canonicals
154 needCanonical = true;
155 seqsWithoutSourceDBRef.add(seq);
159 // could be a sequence with pdb ref
160 if (seq.getAllPDBEntries() == null
161 || seq.getAllPDBEntries().size() == 0)
163 seqsWithoutSourceDBRef.add(seq);
169 // retrieve database refs for protein sequences
170 if (!seqsWithoutSourceDBRef.isEmpty())
175 notQueriedTDBYet = false;
181 * Initializes parameters used by the Structure Chooser Panel
183 protected void init()
185 if (!Jalview.isHeadlessMode())
187 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
190 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
192 Executors.defaultThreadFactory().newThread(new Runnable()
196 populateSeqsWithoutSourceDBRef();
197 initialStructureDiscovery();
205 private void initialStructureDiscovery()
207 // check which FTS engine to use
208 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
210 // ensure a filter option is in force for search
211 populateFilterComboBox(true, cachedPDBExists);
213 // looks for any existing structures already loaded
214 // for the sequences (the cached ones)
215 // then queries the StructureChooserQuerySource to
216 // discover more structures.
218 // Possible optimisation is to only begin querying
219 // the structure chooser if there are no cached structures.
221 long startTime = System.currentTimeMillis();
222 updateProgressIndicator(
223 MessageManager.getString("status.loading_cached_pdb_entries"),
225 loadLocalCachedPDBEntries();
226 updateProgressIndicator(null, startTime);
227 updateProgressIndicator(
228 MessageManager.getString("status.searching_for_pdb_structures"),
230 fetchStructuresMetaData();
231 // revise filter options if no results were found
232 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
233 discoverStructureViews();
234 updateProgressIndicator(null, startTime);
235 mainFrame.setVisible(true);
239 private void promptForTDBFetch()
241 final long progressId = System.currentTimeMillis();
243 // final action after prompting and discovering db refs
244 final Runnable strucDiscovery = new Runnable()
249 // TODO: warn if no accessions discovered
250 populateSeqsWithoutSourceDBRef();
251 // redo initial discovery - this time with 3d beacons
253 previousWantedFields=null;
255 initialStructureDiscovery();
259 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
263 public void finished()
265 // filter has been selected, so we set flag to remove ourselves
266 notQueriedTDBYet = false;
267 // new thread to discover structures - via 3d beacons
268 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
273 // fetch db refs if OK pressed
274 final Runnable discoverCanonicalDBrefs = new Runnable()
279 populateSeqsWithoutSourceDBRef();
281 final int y = seqsWithoutSourceDBRef.size();
284 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
285 .toArray(new SequenceI[y]);
286 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
287 progressBar, new DbSourceProxy[]
288 { new jalview.ws.dbsources.Uniprot() }, null, false);
289 dbRefFetcher.addListener(afterDbRefFetch);
290 // ideally this would also gracefully run with callbacks
291 dbRefFetcher.fetchDBRefs(true);
293 // call finished action directly
294 afterDbRefFetch.finished();
299 final Runnable revertview = new Runnable() {
301 if (lastSelected!=null) {
302 cmb_filterOption.setSelectedItem(lastSelected);
306 // need cancel and no to result in the discoverPDB action - mocked is
308 JvOptionPane.newOptionDialog(this)
309 .setResponseHandler(JvOptionPane.OK_OPTION,
310 discoverCanonicalDBrefs)
311 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
312 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
314 MessageManager.formatMessage(
315 "label.fetch_references_for_3dbeacons",
316 seqsWithoutSourceDBRef.size()),
318 .getString("label.3dbeacons"),
319 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
321 { MessageManager.getString("action.ok"),
322 MessageManager.getString("action.cancel") },
323 MessageManager.getString("action.ok"));
327 * Builds a drop-down choice list of existing structure viewers to which new
328 * structures may be added. If this list is empty then it, and the 'Add'
329 * button, are hidden.
331 private void discoverStructureViews()
333 if (Desktop.instance != null)
335 targetView.removeAllItems();
336 if (lastTargetedView != null && !lastTargetedView.isVisible())
338 lastTargetedView = null;
340 int linkedViewsAt = 0;
341 for (StructureViewerBase view : Desktop.instance
342 .getStructureViewers(null, null))
344 StructureViewer viewHandler = (lastTargetedView != null
345 && lastTargetedView.sview == view) ? lastTargetedView
346 : StructureViewer.reconfigure(view);
348 if (view.isLinkedWith(ap))
350 targetView.insertItemAt(viewHandler, linkedViewsAt++);
354 targetView.addItem(viewHandler);
359 * show option to Add to viewer if at least 1 viewer found
361 targetView.setVisible(false);
362 if (targetView.getItemCount() > 0)
364 targetView.setVisible(true);
365 if (lastTargetedView != null)
367 targetView.setSelectedItem(lastTargetedView);
371 targetView.setSelectedIndex(0);
374 btn_add.setVisible(targetView.isVisible());
379 * Updates the progress indicator with the specified message
382 * displayed message for the operation
384 * unique handle for this indicator
386 protected void updateProgressIndicator(String message, long id)
388 if (progressIndicator != null)
390 progressIndicator.setProgressBar(message, id);
395 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
398 void fetchStructuresMetaData()
400 long startTime = System.currentTimeMillis();
401 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
402 .getStructureSummaryFields();
404 discoveredStructuresSet = new LinkedHashSet<>();
405 HashSet<String> errors = new HashSet<>();
407 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
410 for (SequenceI seq : selectedSequences)
413 FTSRestResponse resultList;
416 resultList = data.fetchStructuresMetaData(seq, wantedFields,
417 selectedFilterOpt, !chk_invertFilter.isSelected());
418 // null response means the FTSengine didn't yield a query for this
419 // consider designing a special exception if we really wanted to be
421 if (resultList == null)
425 } catch (Exception e)
428 errors.add(e.getMessage());
431 if (resultList.getSearchSummary() != null
432 && !resultList.getSearchSummary().isEmpty())
434 discoveredStructuresSet.addAll(resultList.getSearchSummary());
438 int noOfStructuresFound = 0;
439 String totalTime = (System.currentTimeMillis() - startTime)
441 if (discoveredStructuresSet != null
442 && !discoveredStructuresSet.isEmpty())
445 .setModel(data.getTableModel(discoveredStructuresSet));
447 noOfStructuresFound = discoveredStructuresSet.size();
448 lastDiscoveredStructuresSet = discoveredStructuresSet;
449 mainFrame.setTitle(MessageManager.formatMessage(
450 "label.structure_chooser_no_of_structures",
451 noOfStructuresFound, totalTime));
455 mainFrame.setTitle(MessageManager
456 .getString("label.structure_chooser_manual_association"));
457 if (errors.size() > 0)
459 StringBuilder errorMsg = new StringBuilder();
460 for (String error : errors)
462 errorMsg.append(error).append("\n");
464 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
465 MessageManager.getString("label.pdb_web-service_error"),
466 JvOptionPane.ERROR_MESSAGE);
471 protected void loadLocalCachedPDBEntries()
473 ArrayList<CachedPDB> entries = new ArrayList<>();
474 for (SequenceI seq : selectedSequences)
476 if (seq.getDatasetSequence() != null
477 && seq.getDatasetSequence().getAllPDBEntries() != null)
479 for (PDBEntry pdbEntry : seq.getDatasetSequence()
482 if (pdbEntry.getFile() != null)
484 entries.add(new CachedPDB(seq, pdbEntry));
489 cachedPDBExists = !entries.isEmpty();
490 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
491 tbl_local_pdb.setModel(tableModelx);
495 * Filters a given list of discovered structures based on supplied argument
497 * @param fieldToFilterBy
498 * the field to filter by
500 void filterResultSet(final String fieldToFilterBy)
502 Thread filterThread = new Thread(new Runnable()
508 long startTime = System.currentTimeMillis();
509 lbl_loading.setVisible(true);
510 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
511 .getStructureSummaryFields();
512 Collection<FTSData> filteredResponse = new HashSet<>();
513 HashSet<String> errors = new HashSet<>();
515 for (SequenceI seq : selectedSequences)
518 FTSRestResponse resultList;
521 resultList = data.selectFirstRankedQuery(seq,
522 discoveredStructuresSet, wantedFields, fieldToFilterBy,
523 !chk_invertFilter.isSelected());
525 } catch (Exception e)
528 errors.add(e.getMessage());
531 if (resultList.getSearchSummary() != null
532 && !resultList.getSearchSummary().isEmpty())
534 filteredResponse.addAll(resultList.getSearchSummary());
538 String totalTime = (System.currentTimeMillis() - startTime)
540 if (!filteredResponse.isEmpty())
542 final int filterResponseCount = filteredResponse.size();
543 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
544 reorderedStructuresSet.addAll(filteredResponse);
545 reorderedStructuresSet.addAll(discoveredStructuresSet);
547 .setModel(data.getTableModel(reorderedStructuresSet));
549 FTSRestResponse.configureTableColumn(getResultTable(),
550 wantedFields, tempUserPrefs);
551 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
552 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
553 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
554 // Update table selection model here
555 getResultTable().addRowSelectionInterval(0,
556 filterResponseCount - 1);
557 mainFrame.setTitle(MessageManager.formatMessage(
558 "label.structure_chooser_filter_time", totalTime));
562 mainFrame.setTitle(MessageManager.formatMessage(
563 "label.structure_chooser_filter_time", totalTime));
564 if (errors.size() > 0)
566 StringBuilder errorMsg = new StringBuilder();
567 for (String error : errors)
569 errorMsg.append(error).append("\n");
571 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
572 MessageManager.getString("label.pdb_web-service_error"),
573 JvOptionPane.ERROR_MESSAGE);
577 lbl_loading.setVisible(false);
579 validateSelections();
582 filterThread.start();
586 * Handles action event for btn_pdbFromFile
589 protected void pdbFromFile_actionPerformed()
591 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
594 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
595 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
596 chooser.setFileView(new jalview.io.JalviewFileView());
597 chooser.setDialogTitle(
598 MessageManager.formatMessage("label.select_pdb_file_for",
599 selectedSequence.getDisplayId(false)));
600 chooser.setToolTipText(MessageManager.formatMessage(
601 "label.load_pdb_file_associate_with_sequence",
602 selectedSequence.getDisplayId(false)));
604 int value = chooser.showOpenDialog(null);
605 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
607 selectedPdbFileName = chooser.getSelectedFile().getPath();
608 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
609 validateSelections();
614 * Populates the filter combo-box options dynamically depending on discovered
617 protected void populateFilterComboBox(boolean haveData,
618 boolean cachedPDBExist)
620 populateFilterComboBox(haveData, cachedPDBExist, null);
624 * Populates the filter combo-box options dynamically depending on discovered
627 protected void populateFilterComboBox(boolean haveData,
628 boolean cachedPDBExist, FilterOption lastSel)
632 * temporarily suspend the change listener behaviour
634 cmb_filterOption.removeItemListener(this);
636 cmb_filterOption.removeAllItems();
639 List<FilterOption> filters = data
640 .getAvailableFilterOptions(VIEWS_FILTER);
641 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
642 lastDiscoveredStructuresSet);
644 for (FilterOption filter : filters)
646 if (lastSel != null && filter.equals(lastSel))
651 cmb_filterOption.addItem(filter);
655 cmb_filterOption.addItem(
656 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
657 "-", VIEWS_ENTER_ID, false, null));
658 cmb_filterOption.addItem(
659 new FilterOption(MessageManager.getString("label.from_file"),
660 "-", VIEWS_FROM_FILE, false, null));
661 if (canQueryTDB && notQueriedTDBYet)
663 FilterOption queryTDBOption = new FilterOption(
664 MessageManager.getString("label.search_3dbeacons"), "-",
665 VIEWS_QUERYING_TDB, false, null);
666 cmb_filterOption.addItem(queryTDBOption);
671 FilterOption cachedOption = new FilterOption(
672 MessageManager.getString("label.cached_structures"), "-",
673 VIEWS_LOCAL_PDB, false, null);
674 cmb_filterOption.addItem(cachedOption);
677 cmb_filterOption.setSelectedItem(cachedOption);
682 cmb_filterOption.setSelectedIndex(selSet);
684 cmb_filterOption.addItemListener(this);
688 * Updates the displayed view based on the selected filter option
690 protected void updateCurrentView()
692 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
695 // first check if we need to rebuild dialog
696 if (selectedFilterOpt.getView() == VIEWS_QUERYING_TDB)
701 if (lastSelected == selectedFilterOpt)
703 // don't need to do anything, probably
706 // otherwise, record selection
707 // and update the layout and dialog accordingly
708 lastSelected = selectedFilterOpt;
710 layout_switchableViews.show(pnl_switchableViews,
711 selectedFilterOpt.getView());
712 String filterTitle = mainFrame.getTitle();
713 mainFrame.setTitle(frameTitle);
714 chk_invertFilter.setVisible(false);
716 if (selectedFilterOpt.getView() == VIEWS_FILTER)
718 mainFrame.setTitle(filterTitle);
719 // TDB Query has no invert as yet
720 chk_invertFilter.setVisible(selectedFilterOpt
721 .getQuerySource() instanceof PDBStructureChooserQuerySource);
723 if (data != selectedFilterOpt.getQuerySource()
724 || data.needsRefetch(selectedFilterOpt))
726 data = selectedFilterOpt.getQuerySource();
727 // rebuild the views completely, since prefs will also change
733 filterResultSet(selectedFilterOpt.getValue());
736 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
737 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
739 mainFrame.setTitle(MessageManager
740 .getString("label.structure_chooser_manual_association"));
741 idInputAssSeqPanel.loadCmbAssSeq();
742 fileChooserAssSeqPanel.loadCmbAssSeq();
744 validateSelections();
748 * Validates user selection and enables the 'Add' and 'New View' buttons if
749 * all parameters are correct (the Add button will only be visible if there is
750 * at least one existing structure viewer open). This basically means at least
751 * one structure selected and no error messages.
753 * The 'Superpose Structures' option is enabled if either more than one
754 * structure is selected, or the 'Add' to existing view option is enabled, and
755 * disabled if the only option is to open a new view of a single structure.
758 protected void validateSelections()
760 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
762 btn_add.setEnabled(false);
763 String currentView = selectedFilterOpt.getView();
764 int selectedCount = 0;
765 if (currentView == VIEWS_FILTER)
767 selectedCount = getResultTable().getSelectedRows().length;
768 if (selectedCount > 0)
770 btn_add.setEnabled(true);
773 else if (currentView == VIEWS_LOCAL_PDB)
775 selectedCount = tbl_local_pdb.getSelectedRows().length;
776 if (selectedCount > 0)
778 btn_add.setEnabled(true);
781 else if (currentView == VIEWS_ENTER_ID)
783 validateAssociationEnterPdb();
785 else if (currentView == VIEWS_FROM_FILE)
787 validateAssociationFromFile();
790 btn_newView.setEnabled(btn_add.isEnabled());
793 * enable 'Superpose' option if more than one structure is selected,
794 * or there are view(s) available to add structure(s) to
797 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
801 protected boolean showPopupFor(int selectedRow)
803 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
805 String currentView = selectedFilterOpt.getView();
806 if (currentView == VIEWS_FILTER && data instanceof ThreeDBStructureChooserQuerySource)
808 TDB_FTSData row=null;
811 for (FTSData el:discoveredStructuresSet) {
812 if (i==selectedRow) {
813 row = (TDB_FTSData) el;
818 String pageUrl = row.getModelViewUrl();
819 JMenu popup = new JMenu("3D Beacons");
820 JMenuItem viewUrl = new JMenuItem("View model web page");
821 viewUrl.addActionListener(
822 new ActionListener() {
824 public void actionPerformed(ActionEvent e)
826 Desktop.showUrl(pageUrl);
831 SwingUtilities.invokeLater(new Runnable() {
832 public void run() { popup.setVisible(true); }
836 // event not handled by us
840 * Validates inputs from the Manual PDB entry panel
842 protected void validateAssociationEnterPdb()
844 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
845 .getCmb_assSeq().getSelectedItem();
846 lbl_pdbManualFetchStatus.setIcon(errorImage);
847 lbl_pdbManualFetchStatus.setToolTipText("");
848 if (txt_search.getText().length() > 0)
850 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
851 MessageManager.formatMessage("info.no_pdb_entry_found_for",
852 txt_search.getText())));
855 if (errorWarning.length() > 0)
857 lbl_pdbManualFetchStatus.setIcon(warningImage);
858 lbl_pdbManualFetchStatus.setToolTipText(
859 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
862 if (selectedSequences.length == 1 || !assSeqOpt.getName()
863 .equalsIgnoreCase("-Select Associated Seq-"))
865 txt_search.setEnabled(true);
868 btn_add.setEnabled(true);
869 lbl_pdbManualFetchStatus.setToolTipText("");
870 lbl_pdbManualFetchStatus.setIcon(goodImage);
875 txt_search.setEnabled(false);
876 lbl_pdbManualFetchStatus.setIcon(errorImage);
881 * Validates inputs for the manual PDB file selection options
883 protected void validateAssociationFromFile()
885 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
886 .getCmb_assSeq().getSelectedItem();
887 lbl_fromFileStatus.setIcon(errorImage);
888 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
889 .getName().equalsIgnoreCase("-Select Associated Seq-")))
891 btn_pdbFromFile.setEnabled(true);
892 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
894 btn_add.setEnabled(true);
895 lbl_fromFileStatus.setIcon(goodImage);
900 btn_pdbFromFile.setEnabled(false);
901 lbl_fromFileStatus.setIcon(errorImage);
906 protected void cmbAssSeqStateChanged()
908 validateSelections();
910 private FilterOption lastSelected=null;
912 * Handles the state change event for the 'filter' combo-box and 'invert'
916 protected void stateChanged(ItemEvent e)
918 if (e.getSource() instanceof JCheckBox)
924 if (e.getStateChange() == ItemEvent.SELECTED)
933 * select structures for viewing by their PDB IDs
936 * @return true if structures were found and marked as selected
938 public boolean selectStructure(String... pdbids)
940 boolean found = false;
942 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
944 String currentView = selectedFilterOpt.getView();
945 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
946 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
948 if (restable == null)
950 // can't select (enter PDB ID, or load file - need to also select which
951 // sequence to associate with)
955 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
956 for (int r = 0; r < restable.getRowCount(); r++)
958 for (int p = 0; p < pdbids.length; p++)
960 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
961 .equalsIgnoreCase(pdbids[p]))
963 restable.setRowSelectionInterval(r, r);
972 * Handles the 'New View' action
975 protected void newView_ActionPerformed()
977 targetView.setSelectedItem(null);
978 showStructures(false);
982 * Handles the 'Add to existing viewer' action
985 protected void add_ActionPerformed()
987 showStructures(false);
991 * structure viewer opened by this dialog, or null
993 private StructureViewer sViewer = null;
995 public void showStructures(boolean waitUntilFinished)
998 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1000 final int preferredHeight = pnl_filter.getHeight();
1002 Runnable viewStruc = new Runnable()
1007 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1008 .getSelectedItem());
1009 String currentView = selectedFilterOpt.getView();
1010 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1013 if (currentView == VIEWS_FILTER)
1015 int[] selectedRows = restable.getSelectedRows();
1016 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1017 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1018 pdbEntriesToView = data.collectSelectedRows(restable,
1019 selectedRows, selectedSeqsToView);
1021 SequenceI[] selectedSeqs = selectedSeqsToView
1022 .toArray(new SequenceI[selectedSeqsToView.size()]);
1023 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1026 else if (currentView == VIEWS_LOCAL_PDB)
1028 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1029 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1031 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1033 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1035 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1036 for (int row : selectedRows)
1038 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1039 .getModel()).getPDBEntryAt(row).getPdbEntry();
1041 pdbEntriesToView[count++] = pdbEntry;
1042 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1043 .getValueAt(row, refSeqColIndex);
1044 selectedSeqsToView.add(selectedSeq);
1046 SequenceI[] selectedSeqs = selectedSeqsToView
1047 .toArray(new SequenceI[selectedSeqsToView.size()]);
1048 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1051 else if (currentView == VIEWS_ENTER_ID)
1053 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1054 .getCmb_assSeq().getSelectedItem()).getSequence();
1055 if (userSelectedSeq != null)
1057 selectedSequence = userSelectedSeq;
1059 String pdbIdStr = txt_search.getText();
1060 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1061 if (pdbEntry == null)
1063 pdbEntry = new PDBEntry();
1064 if (pdbIdStr.split(":").length > 1)
1066 pdbEntry.setId(pdbIdStr.split(":")[0]);
1067 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1071 pdbEntry.setId(pdbIdStr);
1073 pdbEntry.setType(PDBEntry.Type.PDB);
1074 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1077 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1078 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1080 { selectedSequence });
1082 else if (currentView == VIEWS_FROM_FILE)
1084 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1085 .getCmb_assSeq().getSelectedItem()).getSequence();
1086 if (userSelectedSeq != null)
1088 selectedSequence = userSelectedSeq;
1090 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1091 .associatePdbWithSeq(selectedPdbFileName,
1092 DataSourceType.FILE, selectedSequence, true,
1095 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1097 { selectedSequence });
1099 SwingUtilities.invokeLater(new Runnable()
1104 closeAction(preferredHeight);
1105 mainFrame.dispose();
1110 Thread runner = new Thread(viewStruc);
1112 if (waitUntilFinished)
1114 while (sViewer == null ? runner.isAlive()
1115 : (sViewer.sview == null ? true
1116 : !sViewer.sview.hasMapping()))
1121 } catch (InterruptedException ie)
1130 * Answers a structure viewer (new or existing) configured to superimpose
1131 * added structures or not according to the user's choice
1136 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1138 Object sv = targetView.getSelectedItem();
1140 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1144 * Adds PDB structures to a new or existing structure viewer
1147 * @param pdbEntriesToView
1152 private StructureViewer launchStructureViewer(
1153 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1154 final AlignmentPanel alignPanel, SequenceI[] sequences)
1156 long progressId = sequences.hashCode();
1157 setProgressBar(MessageManager
1158 .getString("status.launching_3d_structure_viewer"), progressId);
1159 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1160 boolean superimpose = chk_superpose.isSelected();
1161 theViewer.setSuperpose(superimpose);
1164 * remember user's choice of superimpose or not
1166 Cache.setProperty(AUTOSUPERIMPOSE,
1167 Boolean.valueOf(superimpose).toString());
1169 setProgressBar(null, progressId);
1170 if (SiftsSettings.isMapWithSifts())
1172 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1174 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1175 // real PDB ID. For moment, we can also safely do this if there is already
1176 // a known mapping between the PDBEntry and the sequence.
1177 for (SequenceI seq : sequences)
1179 PDBEntry pdbe = pdbEntriesToView[p++];
1180 if (pdbe != null && pdbe.getFile() != null)
1182 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1183 if (smm != null && smm.length > 0)
1185 for (StructureMapping sm : smm)
1187 if (sm.getSequence() == seq)
1194 if (seq.getPrimaryDBRefs().isEmpty())
1196 seqsWithoutSourceDBRef.add(seq);
1200 if (!seqsWithoutSourceDBRef.isEmpty())
1202 int y = seqsWithoutSourceDBRef.size();
1203 setProgressBar(MessageManager.formatMessage(
1204 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1206 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1207 .toArray(new SequenceI[y]);
1208 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1209 dbRefFetcher.fetchDBRefs(true);
1211 setProgressBar("Fetch complete.", progressId); // todo i18n
1214 if (pdbEntriesToView.length > 1)
1217 MessageManager.getString(
1218 "status.fetching_3d_structures_for_selected_entries"),
1220 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1224 setProgressBar(MessageManager.formatMessage(
1225 "status.fetching_3d_structures_for",
1226 pdbEntriesToView[0].getId()), progressId);
1227 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1229 setProgressBar(null, progressId);
1230 // remember the last viewer we used...
1231 lastTargetedView = theViewer;
1236 * Populates the combo-box used in associating manually fetched structures to
1237 * a unique sequence when more than one sequence selection is made.
1240 protected void populateCmbAssociateSeqOptions(
1241 JComboBox<AssociateSeqOptions> cmb_assSeq,
1242 JLabel lbl_associateSeq)
1244 cmb_assSeq.removeAllItems();
1246 new AssociateSeqOptions("-Select Associated Seq-", null));
1247 lbl_associateSeq.setVisible(false);
1248 if (selectedSequences.length > 1)
1250 for (SequenceI seq : selectedSequences)
1252 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1257 String seqName = selectedSequence.getDisplayId(false);
1258 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1259 lbl_associateSeq.setText(seqName);
1260 lbl_associateSeq.setVisible(true);
1261 cmb_assSeq.setVisible(false);
1265 protected boolean isStructuresDiscovered()
1267 return discoveredStructuresSet != null
1268 && !discoveredStructuresSet.isEmpty();
1271 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1273 // Doing a search for "1" or "1c" is valuable?
1274 // Those work but are enormously slow.
1277 protected void txt_search_ActionPerformed()
1279 String text = txt_search.getText().trim();
1280 if (text.length() >= PDB_ID_MIN)
1287 errorWarning.setLength(0);
1288 isValidPBDEntry = false;
1289 if (text.length() > 0)
1291 // TODO move this pdb id search into the PDB specific
1293 // for moment, it will work fine as is because it is self-contained
1294 String searchTerm = text.toLowerCase(Locale.ROOT);
1295 searchTerm = searchTerm.split(":")[0];
1296 // System.out.println(">>>>> search term : " + searchTerm);
1297 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1298 FTSRestRequest pdbRequest = new FTSRestRequest();
1299 pdbRequest.setAllowEmptySeq(false);
1300 pdbRequest.setResponseSize(1);
1301 pdbRequest.setFieldToSearchBy("(pdb_id:");
1302 pdbRequest.setWantedFields(wantedFields);
1303 pdbRequest.setSearchTerm(searchTerm + ")");
1304 pdbRequest.setAssociatedSequence(selectedSequence);
1305 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1306 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1307 FTSRestResponse resultList;
1310 resultList = pdbRestClient.executeRequest(pdbRequest);
1311 } catch (Exception e)
1313 errorWarning.append(e.getMessage());
1317 validateSelections();
1319 if (resultList.getSearchSummary() != null
1320 && resultList.getSearchSummary().size() > 0)
1322 isValidPBDEntry = true;
1325 validateSelections();
1331 protected void tabRefresh()
1333 if (selectedSequences != null)
1335 Thread refreshThread = new Thread(new Runnable()
1340 fetchStructuresMetaData();
1341 // populateFilterComboBox(true, cachedPDBExists);
1344 ((FilterOption) cmb_filterOption.getSelectedItem())
1348 refreshThread.start();
1352 public class PDBEntryTableModel extends AbstractTableModel
1354 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1357 private List<CachedPDB> pdbEntries;
1359 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1361 this.pdbEntries = new ArrayList<>(pdbEntries);
1365 public String getColumnName(int columnIndex)
1367 return columns[columnIndex];
1371 public int getRowCount()
1373 return pdbEntries.size();
1377 public int getColumnCount()
1379 return columns.length;
1383 public boolean isCellEditable(int row, int column)
1389 public Object getValueAt(int rowIndex, int columnIndex)
1391 Object value = "??";
1392 CachedPDB entry = pdbEntries.get(rowIndex);
1393 switch (columnIndex)
1396 value = entry.getSequence();
1399 value = entry.getQualifiedId();
1402 value = entry.getPdbEntry().getChainCode() == null ? "_"
1403 : entry.getPdbEntry().getChainCode();
1406 value = entry.getPdbEntry().getType();
1409 value = entry.getPdbEntry().getFile();
1416 public Class<?> getColumnClass(int columnIndex)
1418 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1421 public CachedPDB getPDBEntryAt(int row)
1423 return pdbEntries.get(row);
1428 private class CachedPDB
1430 private SequenceI sequence;
1432 private PDBEntry pdbEntry;
1434 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1436 this.sequence = sequence;
1437 this.pdbEntry = pdbEntry;
1440 public String getQualifiedId()
1442 if (pdbEntry.hasProvider())
1444 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1446 return pdbEntry.toString();
1449 public SequenceI getSequence()
1454 public PDBEntry getPdbEntry()
1461 private IProgressIndicator progressBar;
1464 public void setProgressBar(String message, long id)
1466 progressBar.setProgressBar(message, id);
1470 public void registerHandler(long id, IProgressIndicatorHandler handler)
1472 progressBar.registerHandler(id, handler);
1476 public boolean operationInProgress()
1478 return progressBar.operationInProgress();
1481 public JalviewStructureDisplayI getOpenedStructureViewer()
1483 return sViewer == null ? null : sViewer.sview;
1487 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1489 data.setDocFieldPrefs(newPrefs);
1495 * @return true when all initialisation threads have finished and dialog is
1498 public boolean isDialogVisible()
1500 return mainFrame != null && data != null && cmb_filterOption != null
1501 && mainFrame.isVisible()
1502 && cmb_filterOption.getSelectedItem() != null;