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;
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";
83 private SequenceI selectedSequence;
85 private SequenceI[] selectedSequences;
87 private IProgressIndicator progressIndicator;
89 private Collection<FTSData> discoveredStructuresSet;
91 private StructureChooserQuerySource data;
94 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
96 return data.getDocFieldPrefs();
99 private String selectedPdbFileName;
101 private boolean isValidPBDEntry;
103 private boolean cachedPDBExists;
105 private Collection<FTSData> lastDiscoveredStructuresSet;
107 private boolean canQueryTDB = false;
109 private boolean notQueriedTDBYet = true;
111 List<SequenceI> seqsWithoutSourceDBRef = null;
113 private static StructureViewer lastTargetedView = null;
115 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
118 // which FTS engine to use
119 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
122 this.selectedSequence = selectedSeq;
123 this.selectedSequences = selectedSeqs;
124 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
129 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
130 * least one structure are discovered.
132 private void populateSeqsWithoutSourceDBRef()
134 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
135 boolean needCanonical = false;
136 for (SequenceI seq : selectedSequences)
140 int dbRef = ThreeDBStructureChooserQuerySource
141 .checkUniprotRefs(seq.getDBRefs());
146 // need to retrieve canonicals
147 needCanonical = true;
148 seqsWithoutSourceDBRef.add(seq);
152 // could be a sequence with pdb ref
153 if (seq.getAllPDBEntries() == null
154 || seq.getAllPDBEntries().size() == 0)
156 seqsWithoutSourceDBRef.add(seq);
162 // retrieve database refs for protein sequences
163 if (!seqsWithoutSourceDBRef.isEmpty())
168 // triggers display of the 'Query TDB' button
169 notQueriedTDBYet = true;
175 * Initializes parameters used by the Structure Chooser Panel
177 protected void init()
179 if (!Jalview.isHeadlessMode())
181 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
184 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
185 btn_queryTDB.addActionListener(new ActionListener()
189 public void actionPerformed(ActionEvent e)
191 promptForTDBFetch(false);
195 Executors.defaultThreadFactory().newThread(new Runnable()
199 populateSeqsWithoutSourceDBRef();
200 initialStructureDiscovery();
208 private void initialStructureDiscovery()
210 // check which FTS engine to use
211 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
213 // ensure a filter option is in force for search
214 populateFilterComboBox(true, cachedPDBExists);
215 // looks for any existing structures already loaded
216 // for the sequences (the cached ones)
217 // then queries the StructureChooserQuerySource to
218 // discover more structures.
220 // Possible optimisation is to only begin querying
221 // the structure chooser if there are no cached structures.
223 long startTime = System.currentTimeMillis();
224 updateProgressIndicator(
225 MessageManager.getString("status.loading_cached_pdb_entries"),
227 loadLocalCachedPDBEntries();
228 updateProgressIndicator(null, startTime);
229 updateProgressIndicator(
230 MessageManager.getString("status.searching_for_pdb_structures"),
232 fetchStructuresMetaData();
233 // revise filter options if no results were found
234 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
235 discoverStructureViews();
236 updateProgressIndicator(null, startTime);
237 mainFrame.setVisible(true);
242 * raises dialog for Uniprot fetch followed by 3D beacons search
243 * @param ignoreGui - when true, don't ask, just fetch
245 public void promptForTDBFetch(boolean ignoreGui)
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 lastSelected=(FilterOption) cmb_filterOption.getSelectedItem();
264 cmb_filterOption.setSelectedItem(null);
265 cachedPDBExists=false; // reset to initial
266 initialStructureDiscovery();
267 if (!isStructuresDiscovered())
269 progressBar.setProgressBar(MessageManager.getString("status.no_structures_discovered_from_3d_beacons"), progressId);
270 btn_queryTDB.setToolTipText(MessageManager.getString("status.no_structures_discovered_from_3d_beacons"));
271 btn_queryTDB.setEnabled(false);
273 cmb_filterOption.setSelectedIndex(0); // select 'best'
274 btn_queryTDB.setVisible(false);
275 progressBar.setProgressBar(null, progressId);
277 mainFrame.setEnabled(true);
278 cmb_filterOption.setEnabled(true);
282 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
286 public void finished()
288 // filter has been selected, so we set flag to remove ourselves
289 notQueriedTDBYet = false;
290 // new thread to discover structures - via 3d beacons
291 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
296 // fetch db refs if OK pressed
297 final Runnable discoverCanonicalDBrefs = new Runnable()
302 populateSeqsWithoutSourceDBRef();
304 final int y = seqsWithoutSourceDBRef.size();
307 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
308 .toArray(new SequenceI[y]);
309 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
310 progressBar, new DbSourceProxy[]
311 { new jalview.ws.dbsources.Uniprot() }, null, false);
312 dbRefFetcher.addListener(afterDbRefFetch);
313 // ideally this would also gracefully run with callbacks
314 dbRefFetcher.fetchDBRefs(true);
316 // call finished action directly
317 afterDbRefFetch.finished();
322 final Runnable revertview = new Runnable() {
324 if (lastSelected!=null) {
325 cmb_filterOption.setSelectedItem(lastSelected);
331 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs).start();
334 // need cancel and no to result in the discoverPDB action - mocked is
335 // 'cancel' TODO: mock should be OK
336 JvOptionPane.newOptionDialog(this)
337 .setResponseHandler(JvOptionPane.OK_OPTION,
338 discoverCanonicalDBrefs)
339 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
340 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
342 MessageManager.formatMessage(
343 "label.fetch_references_for_3dbeacons",
344 seqsWithoutSourceDBRef.size()),
346 .getString("label.3dbeacons"),
347 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
349 { MessageManager.getString("action.ok"),
350 MessageManager.getString("action.cancel") },
351 MessageManager.getString("action.ok"));
355 * Builds a drop-down choice list of existing structure viewers to which new
356 * structures may be added. If this list is empty then it, and the 'Add'
357 * button, are hidden.
359 private void discoverStructureViews()
361 if (Desktop.getInstance() != null)
363 targetView.removeAllItems();
364 if (lastTargetedView != null && !lastTargetedView.isVisible())
366 lastTargetedView = null;
368 int linkedViewsAt = 0;
369 for (StructureViewerBase view : Desktop.getInstance()
370 .getStructureViewers(null, null))
372 StructureViewer viewHandler = (lastTargetedView != null
373 && lastTargetedView.sview == view) ? lastTargetedView
374 : StructureViewer.reconfigure(view);
376 if (view.isLinkedWith(ap))
378 targetView.insertItemAt(viewHandler, linkedViewsAt++);
382 targetView.addItem(viewHandler);
387 * show option to Add to viewer if at least 1 viewer found
389 targetView.setVisible(false);
390 if (targetView.getItemCount() > 0)
392 targetView.setVisible(true);
393 if (lastTargetedView != null)
395 targetView.setSelectedItem(lastTargetedView);
399 targetView.setSelectedIndex(0);
402 btn_add.setVisible(targetView.isVisible());
407 * Updates the progress indicator with the specified message
410 * displayed message for the operation
412 * unique handle for this indicator
414 protected void updateProgressIndicator(String message, long id)
416 if (progressIndicator != null)
418 progressIndicator.setProgressBar(message, id);
423 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
426 void fetchStructuresMetaData()
428 long startTime = System.currentTimeMillis();
429 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
430 .getStructureSummaryFields();
432 discoveredStructuresSet = new LinkedHashSet<>();
433 HashSet<String> errors = new HashSet<>();
434 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
436 for (SequenceI seq : selectedSequences)
438 FTSRestResponse resultList;
441 resultList = data.fetchStructuresMetaData(seq, wantedFields,
442 selectedFilterOpt, !chk_invertFilter.isSelected());
443 // null response means the FTSengine didn't yield a query for this
444 // consider designing a special exception if we really wanted to be
446 if (resultList == null)
450 } catch (Exception e)
453 errors.add(e.getMessage());
456 if (resultList.getSearchSummary() != null
457 && !resultList.getSearchSummary().isEmpty())
459 discoveredStructuresSet.addAll(resultList.getSearchSummary());
463 int noOfStructuresFound = 0;
464 String totalTime = (System.currentTimeMillis() - startTime)
466 if (discoveredStructuresSet != null
467 && !discoveredStructuresSet.isEmpty())
470 .setModel(data.getTableModel(discoveredStructuresSet));
471 noOfStructuresFound = discoveredStructuresSet.size();
472 lastDiscoveredStructuresSet = discoveredStructuresSet;
473 mainFrame.setTitle(MessageManager.formatMessage(
474 "label.structure_chooser_no_of_structures",
475 noOfStructuresFound, totalTime));
479 mainFrame.setTitle(MessageManager
480 .getString("label.structure_chooser_manual_association"));
481 if (errors.size() > 0)
483 StringBuilder errorMsg = new StringBuilder();
484 for (String error : errors)
486 errorMsg.append(error).append("\n");
488 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
489 MessageManager.getString("label.pdb_web-service_error"),
490 JvOptionPane.ERROR_MESSAGE);
495 protected void loadLocalCachedPDBEntries()
497 ArrayList<CachedPDB> entries = new ArrayList<>();
498 for (SequenceI seq : selectedSequences)
500 if (seq.getDatasetSequence() != null
501 && seq.getDatasetSequence().getAllPDBEntries() != null)
503 for (PDBEntry pdbEntry : seq.getDatasetSequence()
506 if (pdbEntry.getFile() != null)
508 entries.add(new CachedPDB(seq, pdbEntry));
513 cachedPDBExists = !entries.isEmpty();
514 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
515 tbl_local_pdb.setModel(tableModelx);
519 * Filters a given list of discovered structures based on supplied argument
521 * @param fieldToFilterBy
522 * the field to filter by
524 void filterResultSet(final String fieldToFilterBy)
526 Thread filterThread = new Thread(new Runnable()
531 long startTime = System.currentTimeMillis();
532 lbl_loading.setVisible(true);
533 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
534 .getStructureSummaryFields();
535 Collection<FTSData> filteredResponse = new HashSet<>();
536 HashSet<String> errors = new HashSet<>();
538 for (SequenceI seq : selectedSequences)
540 FTSRestResponse resultList;
543 resultList = data.selectFirstRankedQuery(seq,
544 discoveredStructuresSet, wantedFields, fieldToFilterBy,
545 !chk_invertFilter.isSelected());
546 } catch (Exception e)
549 errors.add(e.getMessage());
552 if (resultList.getSearchSummary() != null
553 && !resultList.getSearchSummary().isEmpty())
555 filteredResponse.addAll(resultList.getSearchSummary());
559 String totalTime = (System.currentTimeMillis() - startTime)
561 if (!filteredResponse.isEmpty())
563 final int filterResponseCount = filteredResponse.size();
564 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
565 reorderedStructuresSet.addAll(filteredResponse);
566 reorderedStructuresSet.addAll(discoveredStructuresSet);
568 .setModel(data.getTableModel(reorderedStructuresSet));
570 FTSRestResponse.configureTableColumn(getResultTable(),
571 wantedFields, tempUserPrefs);
572 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
573 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
574 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
575 // Update table selection model here
576 getResultTable().addRowSelectionInterval(0,
577 filterResponseCount - 1);
578 mainFrame.setTitle(MessageManager.formatMessage(
579 "label.structure_chooser_filter_time", totalTime));
583 mainFrame.setTitle(MessageManager.formatMessage(
584 "label.structure_chooser_filter_time", totalTime));
585 if (errors.size() > 0)
587 StringBuilder errorMsg = new StringBuilder();
588 for (String error : errors)
590 errorMsg.append(error).append("\n");
592 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
593 MessageManager.getString("label.pdb_web-service_error"),
594 JvOptionPane.ERROR_MESSAGE);
598 lbl_loading.setVisible(false);
600 validateSelections();
603 filterThread.start();
607 * Handles action event for btn_pdbFromFile
610 protected void pdbFromFile_actionPerformed()
612 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
615 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
616 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
617 chooser.setFileView(new jalview.io.JalviewFileView());
618 chooser.setDialogTitle(
619 MessageManager.formatMessage("label.select_pdb_file_for",
620 selectedSequence.getDisplayId(false)));
621 chooser.setToolTipText(MessageManager.formatMessage(
622 "label.load_pdb_file_associate_with_sequence",
623 selectedSequence.getDisplayId(false)));
625 int value = chooser.showOpenDialog(null);
626 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
628 selectedPdbFileName = chooser.getSelectedFile().getPath();
629 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
630 validateSelections();
635 * Populates the filter combo-box options dynamically depending on discovered
638 protected void populateFilterComboBox(boolean haveData,
639 boolean cachedPDBExist)
641 populateFilterComboBox(haveData, cachedPDBExist, null);
645 * Populates the filter combo-box options dynamically depending on discovered
648 protected void populateFilterComboBox(boolean haveData,
649 boolean cachedPDBExist, FilterOption lastSel)
652 * temporarily suspend the change listener behaviour
654 cmb_filterOption.removeItemListener(this);
657 cmb_filterOption.removeAllItems();
660 List<FilterOption> filters = data
661 .getAvailableFilterOptions(VIEWS_FILTER);
662 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
663 lastDiscoveredStructuresSet);
665 for (FilterOption filter : filters)
667 if (lastSel != null && filter.equals(lastSel))
672 cmb_filterOption.addItem(filter);
675 cmb_filterOption.addItem(
676 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
677 "-", VIEWS_ENTER_ID, false, null));
678 cmb_filterOption.addItem(
679 new FilterOption(MessageManager.getString("label.from_file"),
680 "-", VIEWS_FROM_FILE, false, null));
681 if (canQueryTDB && notQueriedTDBYet)
683 btn_queryTDB.setVisible(true);
688 FilterOption cachedOption = new FilterOption(
689 MessageManager.getString("label.cached_structures"), "-",
690 VIEWS_LOCAL_PDB, false, null);
691 cmb_filterOption.addItem(cachedOption);
694 cmb_filterOption.setSelectedItem(cachedOption);
700 cmb_filterOption.setSelectedIndex(selSet);
702 cmb_filterOption.addItemListener(this);
706 * Updates the displayed view based on the selected filter option
708 protected void updateCurrentView()
710 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
713 if (lastSelected == selectedFilterOpt)
715 // don't need to do anything, probably
718 // otherwise, record selection
719 // and update the layout and dialog accordingly
720 lastSelected = selectedFilterOpt;
721 layout_switchableViews.show(pnl_switchableViews,
722 selectedFilterOpt.getView());
723 String filterTitle = mainFrame.getTitle();
724 mainFrame.setTitle(frameTitle);
725 chk_invertFilter.setVisible(false);
727 if (selectedFilterOpt.getView() == VIEWS_FILTER)
729 mainFrame.setTitle(filterTitle);
730 // TDB Query has no invert as yet
731 chk_invertFilter.setVisible(selectedFilterOpt
732 .getQuerySource() instanceof PDBStructureChooserQuerySource);
734 if (data != selectedFilterOpt.getQuerySource()
735 || data.needsRefetch(selectedFilterOpt))
737 data = selectedFilterOpt.getQuerySource();
738 // rebuild the views completely, since prefs will also change
744 filterResultSet(selectedFilterOpt.getValue());
747 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
748 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
750 mainFrame.setTitle(MessageManager
751 .getString("label.structure_chooser_manual_association"));
752 idInputAssSeqPanel.loadCmbAssSeq();
753 fileChooserAssSeqPanel.loadCmbAssSeq();
755 validateSelections();
759 * Validates user selection and enables the 'Add' and 'New View' buttons if
760 * all parameters are correct (the Add button will only be visible if there is
761 * at least one existing structure viewer open). This basically means at least
762 * one structure selected and no error messages.
764 * The 'Superpose Structures' option is enabled if either more than one
765 * structure is selected, or the 'Add' to existing view option is enabled, and
766 * disabled if the only option is to open a new view of a single structure.
769 protected void validateSelections()
771 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
773 btn_add.setEnabled(false);
774 String currentView = selectedFilterOpt.getView();
775 int selectedCount = 0;
776 if (currentView == VIEWS_FILTER)
778 selectedCount = getResultTable().getSelectedRows().length;
779 if (selectedCount > 0)
781 btn_add.setEnabled(true);
784 else if (currentView == VIEWS_LOCAL_PDB)
786 selectedCount = tbl_local_pdb.getSelectedRows().length;
787 if (selectedCount > 0)
789 btn_add.setEnabled(true);
792 else if (currentView == VIEWS_ENTER_ID)
794 validateAssociationEnterPdb();
796 else if (currentView == VIEWS_FROM_FILE)
798 validateAssociationFromFile();
801 btn_newView.setEnabled(btn_add.isEnabled());
804 * enable 'Superpose' option if more than one structure is selected,
805 * or there are view(s) available to add structure(s) to
808 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
812 protected boolean showPopupFor(int selectedRow, int x, int y)
814 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
816 String currentView = selectedFilterOpt.getView();
818 if (currentView == VIEWS_FILTER && data instanceof ThreeDBStructureChooserQuerySource)
821 TDB_FTSData row=((ThreeDBStructureChooserQuerySource)data).getFTSDataFor(getResultTable(), selectedRow, discoveredStructuresSet);
822 String pageUrl = row.getModelViewUrl();
823 JPopupMenu popup = new JPopupMenu("3D Beacons");
824 JMenuItem viewUrl = new JMenuItem("View model web page");
825 viewUrl.addActionListener(
826 new ActionListener() {
828 public void actionPerformed(ActionEvent e)
830 Desktop.showUrl(pageUrl);
835 SwingUtilities.invokeLater(new Runnable() {
836 public void run() { popup.show(getResultTable(), x, y); }
840 // event not handled by us
844 * Validates inputs from the Manual PDB entry panel
846 protected void validateAssociationEnterPdb()
848 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
849 .getCmb_assSeq().getSelectedItem();
850 lbl_pdbManualFetchStatus.setIcon(errorImage);
851 lbl_pdbManualFetchStatus.setToolTipText("");
852 if (txt_search.getText().length() > 0)
854 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
855 MessageManager.formatMessage("info.no_pdb_entry_found_for",
856 txt_search.getText())));
859 if (errorWarning.length() > 0)
861 lbl_pdbManualFetchStatus.setIcon(warningImage);
862 lbl_pdbManualFetchStatus.setToolTipText(
863 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
866 if (selectedSequences.length == 1 || !assSeqOpt.getName()
867 .equalsIgnoreCase("-Select Associated Seq-"))
869 txt_search.setEnabled(true);
872 btn_add.setEnabled(true);
873 lbl_pdbManualFetchStatus.setToolTipText("");
874 lbl_pdbManualFetchStatus.setIcon(goodImage);
879 txt_search.setEnabled(false);
880 lbl_pdbManualFetchStatus.setIcon(errorImage);
885 * Validates inputs for the manual PDB file selection options
887 protected void validateAssociationFromFile()
889 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
890 .getCmb_assSeq().getSelectedItem();
891 lbl_fromFileStatus.setIcon(errorImage);
892 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
893 .getName().equalsIgnoreCase("-Select Associated Seq-")))
895 btn_pdbFromFile.setEnabled(true);
896 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
898 btn_add.setEnabled(true);
899 lbl_fromFileStatus.setIcon(goodImage);
904 btn_pdbFromFile.setEnabled(false);
905 lbl_fromFileStatus.setIcon(errorImage);
910 protected void cmbAssSeqStateChanged()
912 validateSelections();
915 private FilterOption lastSelected=null;
917 * Handles the state change event for the 'filter' combo-box and 'invert'
921 protected void stateChanged(ItemEvent e)
923 if (e.getSource() instanceof JCheckBox)
929 if (e.getStateChange() == ItemEvent.SELECTED)
938 * select structures for viewing by their PDB IDs
941 * @return true if structures were found and marked as selected
943 public boolean selectStructure(String... pdbids)
945 boolean found = false;
947 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
949 String currentView = selectedFilterOpt.getView();
950 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
951 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
953 if (restable == null)
955 // can't select (enter PDB ID, or load file - need to also select which
956 // sequence to associate with)
960 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
961 for (int r = 0; r < restable.getRowCount(); r++)
963 for (int p = 0; p < pdbids.length; p++)
965 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
966 .equalsIgnoreCase(pdbids[p]))
968 restable.setRowSelectionInterval(r, r);
976 * Handles the 'New View' action
979 protected void newView_ActionPerformed()
981 targetView.setSelectedItem(null);
982 showStructures(false);
986 * Handles the 'Add to existing viewer' action
989 protected void add_ActionPerformed()
991 showStructures(false);
995 * structure viewer opened by this dialog, or null
997 private StructureViewer sViewer = null;
999 public void showStructures(boolean waitUntilFinished)
1002 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1004 final int preferredHeight = pnl_filter.getHeight();
1006 Runnable viewStruc = new Runnable()
1011 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1012 .getSelectedItem());
1013 String currentView = selectedFilterOpt.getView();
1014 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1017 if (currentView == VIEWS_FILTER)
1019 int[] selectedRows = restable.getSelectedRows();
1020 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1021 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1022 pdbEntriesToView = data.collectSelectedRows(restable,
1023 selectedRows, selectedSeqsToView);
1025 SequenceI[] selectedSeqs = selectedSeqsToView
1026 .toArray(new SequenceI[selectedSeqsToView.size()]);
1027 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1030 else if (currentView == VIEWS_LOCAL_PDB)
1032 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1033 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1035 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1037 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1039 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1040 for (int row : selectedRows)
1042 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1043 .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,
1096 Desktop.getInstance());
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);
1346 ((FilterOption) cmb_filterOption.getSelectedItem())
1350 refreshThread.start();
1354 public class PDBEntryTableModel extends AbstractTableModel
1356 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1359 private List<CachedPDB> pdbEntries;
1361 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1363 this.pdbEntries = new ArrayList<>(pdbEntries);
1367 public String getColumnName(int columnIndex)
1369 return columns[columnIndex];
1373 public int getRowCount()
1375 return pdbEntries.size();
1379 public int getColumnCount()
1381 return columns.length;
1385 public boolean isCellEditable(int row, int column)
1391 public Object getValueAt(int rowIndex, int columnIndex)
1393 Object value = "??";
1394 CachedPDB entry = pdbEntries.get(rowIndex);
1395 switch (columnIndex)
1398 value = entry.getSequence();
1401 value = entry.getQualifiedId();
1404 value = entry.getPdbEntry().getChainCode() == null ? "_"
1405 : entry.getPdbEntry().getChainCode();
1408 value = entry.getPdbEntry().getType();
1411 value = entry.getPdbEntry().getFile();
1418 public Class<?> getColumnClass(int columnIndex)
1420 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1423 public CachedPDB getPDBEntryAt(int row)
1425 return pdbEntries.get(row);
1430 private class CachedPDB
1432 private SequenceI sequence;
1434 private PDBEntry pdbEntry;
1436 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1438 this.sequence = sequence;
1439 this.pdbEntry = pdbEntry;
1442 public String getQualifiedId()
1444 if (pdbEntry.hasProvider())
1446 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1448 return pdbEntry.toString();
1451 public SequenceI getSequence()
1456 public PDBEntry getPdbEntry()
1463 private IProgressIndicator progressBar;
1466 public void setProgressBar(String message, long id)
1468 progressBar.setProgressBar(message, id);
1472 public void removeProgressBar(long id)
1474 progressBar.removeProgressBar(id);
1478 public void registerHandler(long id, IProgressIndicatorHandler handler)
1480 progressBar.registerHandler(id, handler);
1484 public boolean operationInProgress()
1486 return progressBar.operationInProgress();
1489 public JalviewStructureDisplayI getOpenedStructureViewer()
1491 return sViewer == null ? null : sViewer.sview;
1495 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1497 data.setDocFieldPrefs(newPrefs);
1503 * @return true when all initialisation threads have finished and dialog is
1506 public boolean isDialogVisible()
1508 return mainFrame != null && data != null && cmb_filterOption != null
1509 && mainFrame.isVisible()
1510 && cmb_filterOption.getSelectedItem() != null;
1514 * @return true if the 3D-Beacons query button will/has been displayed
1516 public boolean isCanQueryTDB() {
1520 public boolean isNotQueriedTDBYet()
1522 return notQueriedTDBYet;