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)
194 promptForTDBFetch(false);
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);
246 * raises dialog for Uniprot fetch followed by 3D beacons search
247 * @param ignoreGui - when true, don't ask, just fetch
249 public void promptForTDBFetch(boolean ignoreGui)
251 final long progressId = System.currentTimeMillis();
253 // final action after prompting and discovering db refs
254 final Runnable strucDiscovery = new Runnable()
259 mainFrame.setEnabled(false);
260 cmb_filterOption.setEnabled(false);
261 progressBar.setProgressBar(MessageManager.getString("status.searching_3d_beacons"), progressId);
262 // TODO: warn if no accessions discovered
263 populateSeqsWithoutSourceDBRef();
264 // redo initial discovery - this time with 3d beacons
266 previousWantedFields=null;
267 lastSelected=(FilterOption) cmb_filterOption.getSelectedItem();
268 cmb_filterOption.setSelectedItem(null);
269 cachedPDBExists=false; // reset to initial
270 initialStructureDiscovery();
271 if (!isStructuresDiscovered())
273 progressBar.setProgressBar(MessageManager.getString("status.no_structures_discovered_from_3d_beacons"), progressId);
274 btn_queryTDB.setToolTipText(MessageManager.getString("status.no_structures_discovered_from_3d_beacons"));
275 btn_queryTDB.setEnabled(false);
277 cmb_filterOption.setSelectedIndex(0); // select 'best'
278 btn_queryTDB.setVisible(false);
279 progressBar.setProgressBar(null, progressId);
281 mainFrame.setEnabled(true);
282 cmb_filterOption.setEnabled(true);
286 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
290 public void finished()
292 // filter has been selected, so we set flag to remove ourselves
293 notQueriedTDBYet = false;
294 // new thread to discover structures - via 3d beacons
295 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
300 // fetch db refs if OK pressed
301 final Runnable discoverCanonicalDBrefs = new Runnable()
306 populateSeqsWithoutSourceDBRef();
308 final int y = seqsWithoutSourceDBRef.size();
311 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
312 .toArray(new SequenceI[y]);
313 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
314 progressBar, new DbSourceProxy[]
315 { new jalview.ws.dbsources.Uniprot() }, null, false);
316 dbRefFetcher.addListener(afterDbRefFetch);
317 // ideally this would also gracefully run with callbacks
318 dbRefFetcher.fetchDBRefs(true);
320 // call finished action directly
321 afterDbRefFetch.finished();
326 final Runnable revertview = new Runnable() {
328 if (lastSelected!=null) {
329 cmb_filterOption.setSelectedItem(lastSelected);
335 Executors.defaultThreadFactory().newThread(discoverCanonicalDBrefs).start();
338 // need cancel and no to result in the discoverPDB action - mocked is
339 // 'cancel' TODO: mock should be OK
340 JvOptionPane.newOptionDialog(this)
341 .setResponseHandler(JvOptionPane.OK_OPTION,
342 discoverCanonicalDBrefs)
343 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
344 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
346 MessageManager.formatMessage(
347 "label.fetch_references_for_3dbeacons",
348 seqsWithoutSourceDBRef.size()),
350 .getString("label.3dbeacons"),
351 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
353 { MessageManager.getString("action.ok"),
354 MessageManager.getString("action.cancel") },
355 MessageManager.getString("action.ok"));
359 * Builds a drop-down choice list of existing structure viewers to which new
360 * structures may be added. If this list is empty then it, and the 'Add'
361 * button, are hidden.
363 private void discoverStructureViews()
365 if (Desktop.instance != null)
367 targetView.removeAllItems();
368 if (lastTargetedView != null && !lastTargetedView.isVisible())
370 lastTargetedView = null;
372 int linkedViewsAt = 0;
373 for (StructureViewerBase view : Desktop.instance
374 .getStructureViewers(null, null))
376 StructureViewer viewHandler = (lastTargetedView != null
377 && lastTargetedView.sview == view) ? lastTargetedView
378 : StructureViewer.reconfigure(view);
380 if (view.isLinkedWith(ap))
382 targetView.insertItemAt(viewHandler, linkedViewsAt++);
386 targetView.addItem(viewHandler);
391 * show option to Add to viewer if at least 1 viewer found
393 targetView.setVisible(false);
394 if (targetView.getItemCount() > 0)
396 targetView.setVisible(true);
397 if (lastTargetedView != null)
399 targetView.setSelectedItem(lastTargetedView);
403 targetView.setSelectedIndex(0);
406 btn_add.setVisible(targetView.isVisible());
411 * Updates the progress indicator with the specified message
414 * displayed message for the operation
416 * unique handle for this indicator
418 protected void updateProgressIndicator(String message, long id)
420 if (progressIndicator != null)
422 progressIndicator.setProgressBar(message, id);
427 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
430 void fetchStructuresMetaData()
432 long startTime = System.currentTimeMillis();
433 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
434 .getStructureSummaryFields();
436 discoveredStructuresSet = new LinkedHashSet<>();
437 HashSet<String> errors = new HashSet<>();
439 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
442 for (SequenceI seq : selectedSequences)
445 FTSRestResponse resultList;
448 resultList = data.fetchStructuresMetaData(seq, wantedFields,
449 selectedFilterOpt, !chk_invertFilter.isSelected());
450 // null response means the FTSengine didn't yield a query for this
451 // consider designing a special exception if we really wanted to be
453 if (resultList == null)
457 } catch (Exception e)
460 errors.add(e.getMessage());
463 if (resultList.getSearchSummary() != null
464 && !resultList.getSearchSummary().isEmpty())
466 discoveredStructuresSet.addAll(resultList.getSearchSummary());
470 int noOfStructuresFound = 0;
471 String totalTime = (System.currentTimeMillis() - startTime)
473 if (discoveredStructuresSet != null
474 && !discoveredStructuresSet.isEmpty())
477 .setModel(data.getTableModel(discoveredStructuresSet));
479 noOfStructuresFound = discoveredStructuresSet.size();
480 lastDiscoveredStructuresSet = discoveredStructuresSet;
481 mainFrame.setTitle(MessageManager.formatMessage(
482 "label.structure_chooser_no_of_structures",
483 noOfStructuresFound, totalTime));
487 mainFrame.setTitle(MessageManager
488 .getString("label.structure_chooser_manual_association"));
489 if (errors.size() > 0)
491 StringBuilder errorMsg = new StringBuilder();
492 for (String error : errors)
494 errorMsg.append(error).append("\n");
496 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
497 MessageManager.getString("label.pdb_web-service_error"),
498 JvOptionPane.ERROR_MESSAGE);
503 protected void loadLocalCachedPDBEntries()
505 ArrayList<CachedPDB> entries = new ArrayList<>();
506 for (SequenceI seq : selectedSequences)
508 if (seq.getDatasetSequence() != null
509 && seq.getDatasetSequence().getAllPDBEntries() != null)
511 for (PDBEntry pdbEntry : seq.getDatasetSequence()
514 if (pdbEntry.getFile() != null)
516 entries.add(new CachedPDB(seq, pdbEntry));
521 cachedPDBExists = !entries.isEmpty();
522 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
523 tbl_local_pdb.setModel(tableModelx);
527 * Filters a given list of discovered structures based on supplied argument
529 * @param fieldToFilterBy
530 * the field to filter by
532 void filterResultSet(final String fieldToFilterBy)
534 Thread filterThread = new Thread(new Runnable()
540 long startTime = System.currentTimeMillis();
541 lbl_loading.setVisible(true);
542 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
543 .getStructureSummaryFields();
544 Collection<FTSData> filteredResponse = new HashSet<>();
545 HashSet<String> errors = new HashSet<>();
547 for (SequenceI seq : selectedSequences)
550 FTSRestResponse resultList;
553 resultList = data.selectFirstRankedQuery(seq,
554 discoveredStructuresSet, wantedFields, fieldToFilterBy,
555 !chk_invertFilter.isSelected());
557 } catch (Exception e)
560 errors.add(e.getMessage());
563 if (resultList.getSearchSummary() != null
564 && !resultList.getSearchSummary().isEmpty())
566 filteredResponse.addAll(resultList.getSearchSummary());
570 String totalTime = (System.currentTimeMillis() - startTime)
572 if (!filteredResponse.isEmpty())
574 final int filterResponseCount = filteredResponse.size();
575 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
576 reorderedStructuresSet.addAll(filteredResponse);
577 reorderedStructuresSet.addAll(discoveredStructuresSet);
579 .setModel(data.getTableModel(reorderedStructuresSet));
581 FTSRestResponse.configureTableColumn(getResultTable(),
582 wantedFields, tempUserPrefs);
583 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
584 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
585 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
586 // Update table selection model here
587 getResultTable().addRowSelectionInterval(0,
588 filterResponseCount - 1);
589 mainFrame.setTitle(MessageManager.formatMessage(
590 "label.structure_chooser_filter_time", totalTime));
594 mainFrame.setTitle(MessageManager.formatMessage(
595 "label.structure_chooser_filter_time", totalTime));
596 if (errors.size() > 0)
598 StringBuilder errorMsg = new StringBuilder();
599 for (String error : errors)
601 errorMsg.append(error).append("\n");
603 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
604 MessageManager.getString("label.pdb_web-service_error"),
605 JvOptionPane.ERROR_MESSAGE);
609 lbl_loading.setVisible(false);
611 validateSelections();
614 filterThread.start();
618 * Handles action event for btn_pdbFromFile
621 protected void pdbFromFile_actionPerformed()
623 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
626 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
627 Cache.getProperty("LAST_DIRECTORY"));
628 chooser.setFileView(new jalview.io.JalviewFileView());
629 chooser.setDialogTitle(
630 MessageManager.formatMessage("label.select_pdb_file_for",
631 selectedSequence.getDisplayId(false)));
632 chooser.setToolTipText(MessageManager.formatMessage(
633 "label.load_pdb_file_associate_with_sequence",
634 selectedSequence.getDisplayId(false)));
636 int value = chooser.showOpenDialog(null);
637 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
639 selectedPdbFileName = chooser.getSelectedFile().getPath();
640 Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
641 validateSelections();
646 * Populates the filter combo-box options dynamically depending on discovered
649 protected void populateFilterComboBox(boolean haveData,
650 boolean cachedPDBExist)
652 populateFilterComboBox(haveData, cachedPDBExist, null);
656 * Populates the filter combo-box options dynamically depending on discovered
659 protected void populateFilterComboBox(boolean haveData,
660 boolean cachedPDBExist, FilterOption lastSel)
664 * temporarily suspend the change listener behaviour
666 cmb_filterOption.removeItemListener(this);
668 cmb_filterOption.removeAllItems();
671 List<FilterOption> filters = data
672 .getAvailableFilterOptions(VIEWS_FILTER);
673 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
674 lastDiscoveredStructuresSet);
676 for (FilterOption filter : filters)
678 if (lastSel != null && filter.equals(lastSel))
683 cmb_filterOption.addItem(filter);
687 cmb_filterOption.addItem(
688 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
689 "-", VIEWS_ENTER_ID, false, null));
690 cmb_filterOption.addItem(
691 new FilterOption(MessageManager.getString("label.from_file"),
692 "-", VIEWS_FROM_FILE, false, null));
693 if (canQueryTDB && notQueriedTDBYet)
695 btn_queryTDB.setVisible(true);
700 FilterOption cachedOption = new FilterOption(
701 MessageManager.getString("label.cached_structures"), "-",
702 VIEWS_LOCAL_PDB, false, null);
703 cmb_filterOption.addItem(cachedOption);
706 cmb_filterOption.setSelectedItem(cachedOption);
711 cmb_filterOption.setSelectedIndex(selSet);
713 cmb_filterOption.addItemListener(this);
717 * Updates the displayed view based on the selected filter option
719 protected void updateCurrentView()
721 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
724 if (lastSelected == selectedFilterOpt)
726 // don't need to do anything, probably
729 // otherwise, record selection
730 // and update the layout and dialog accordingly
731 lastSelected = selectedFilterOpt;
733 layout_switchableViews.show(pnl_switchableViews,
734 selectedFilterOpt.getView());
735 String filterTitle = mainFrame.getTitle();
736 mainFrame.setTitle(frameTitle);
737 chk_invertFilter.setVisible(false);
739 if (selectedFilterOpt.getView() == VIEWS_FILTER)
741 mainFrame.setTitle(filterTitle);
742 // TDB Query has no invert as yet
743 chk_invertFilter.setVisible(selectedFilterOpt
744 .getQuerySource() instanceof PDBStructureChooserQuerySource);
746 if (data != selectedFilterOpt.getQuerySource()
747 || data.needsRefetch(selectedFilterOpt))
749 data = selectedFilterOpt.getQuerySource();
750 // rebuild the views completely, since prefs will also change
756 filterResultSet(selectedFilterOpt.getValue());
759 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
760 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
762 mainFrame.setTitle(MessageManager
763 .getString("label.structure_chooser_manual_association"));
764 idInputAssSeqPanel.loadCmbAssSeq();
765 fileChooserAssSeqPanel.loadCmbAssSeq();
767 validateSelections();
771 * Validates user selection and enables the 'Add' and 'New View' buttons if
772 * all parameters are correct (the Add button will only be visible if there is
773 * at least one existing structure viewer open). This basically means at least
774 * one structure selected and no error messages.
776 * The 'Superpose Structures' option is enabled if either more than one
777 * structure is selected, or the 'Add' to existing view option is enabled, and
778 * disabled if the only option is to open a new view of a single structure.
781 protected void validateSelections()
783 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
785 btn_add.setEnabled(false);
786 String currentView = selectedFilterOpt.getView();
787 int selectedCount = 0;
788 if (currentView == VIEWS_FILTER)
790 selectedCount = getResultTable().getSelectedRows().length;
791 if (selectedCount > 0)
793 btn_add.setEnabled(true);
796 else if (currentView == VIEWS_LOCAL_PDB)
798 selectedCount = tbl_local_pdb.getSelectedRows().length;
799 if (selectedCount > 0)
801 btn_add.setEnabled(true);
804 else if (currentView == VIEWS_ENTER_ID)
806 validateAssociationEnterPdb();
808 else if (currentView == VIEWS_FROM_FILE)
810 validateAssociationFromFile();
813 btn_newView.setEnabled(btn_add.isEnabled());
816 * enable 'Superpose' option if more than one structure is selected,
817 * or there are view(s) available to add structure(s) to
820 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
824 protected boolean showPopupFor(int selectedRow, int x, int y)
826 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
828 String currentView = selectedFilterOpt.getView();
830 if (currentView == VIEWS_FILTER && data instanceof ThreeDBStructureChooserQuerySource)
833 TDB_FTSData row=((ThreeDBStructureChooserQuerySource)data).getFTSDataFor(getResultTable(), selectedRow, discoveredStructuresSet);
834 String pageUrl = row.getModelViewUrl();
835 JPopupMenu popup = new JPopupMenu("3D Beacons");
836 JMenuItem viewUrl = new JMenuItem("View model web page");
837 viewUrl.addActionListener(
838 new ActionListener() {
840 public void actionPerformed(ActionEvent e)
842 Desktop.showUrl(pageUrl);
847 SwingUtilities.invokeLater(new Runnable() {
848 public void run() { popup.show(getResultTable(), x, y); }
852 // event not handled by us
856 * Validates inputs from the Manual PDB entry panel
858 protected void validateAssociationEnterPdb()
860 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
861 .getCmb_assSeq().getSelectedItem();
862 lbl_pdbManualFetchStatus.setIcon(errorImage);
863 lbl_pdbManualFetchStatus.setToolTipText("");
864 if (txt_search.getText().length() > 0)
866 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
867 MessageManager.formatMessage("info.no_pdb_entry_found_for",
868 txt_search.getText())));
871 if (errorWarning.length() > 0)
873 lbl_pdbManualFetchStatus.setIcon(warningImage);
874 lbl_pdbManualFetchStatus.setToolTipText(
875 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
878 if (selectedSequences.length == 1 || !assSeqOpt.getName()
879 .equalsIgnoreCase("-Select Associated Seq-"))
881 txt_search.setEnabled(true);
884 btn_add.setEnabled(true);
885 lbl_pdbManualFetchStatus.setToolTipText("");
886 lbl_pdbManualFetchStatus.setIcon(goodImage);
891 txt_search.setEnabled(false);
892 lbl_pdbManualFetchStatus.setIcon(errorImage);
897 * Validates inputs for the manual PDB file selection options
899 protected void validateAssociationFromFile()
901 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
902 .getCmb_assSeq().getSelectedItem();
903 lbl_fromFileStatus.setIcon(errorImage);
904 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
905 .getName().equalsIgnoreCase("-Select Associated Seq-")))
907 btn_pdbFromFile.setEnabled(true);
908 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
910 btn_add.setEnabled(true);
911 lbl_fromFileStatus.setIcon(goodImage);
916 btn_pdbFromFile.setEnabled(false);
917 lbl_fromFileStatus.setIcon(errorImage);
922 protected void cmbAssSeqStateChanged()
924 validateSelections();
926 private FilterOption lastSelected=null;
928 * Handles the state change event for the 'filter' combo-box and 'invert'
932 protected void stateChanged(ItemEvent e)
934 if (e.getSource() instanceof JCheckBox)
940 if (e.getStateChange() == ItemEvent.SELECTED)
949 * select structures for viewing by their PDB IDs
952 * @return true if structures were found and marked as selected
954 public boolean selectStructure(String... pdbids)
956 boolean found = false;
958 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
960 String currentView = selectedFilterOpt.getView();
961 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
962 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
964 if (restable == null)
966 // can't select (enter PDB ID, or load file - need to also select which
967 // sequence to associate with)
971 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
972 for (int r = 0; r < restable.getRowCount(); r++)
974 for (int p = 0; p < pdbids.length; p++)
976 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
977 .equalsIgnoreCase(pdbids[p]))
979 restable.setRowSelectionInterval(r, r);
988 * Handles the 'New View' action
991 protected void newView_ActionPerformed()
993 targetView.setSelectedItem(null);
994 showStructures(false);
998 * Handles the 'Add to existing viewer' action
1001 protected void add_ActionPerformed()
1003 showStructures(false);
1007 * structure viewer opened by this dialog, or null
1009 private StructureViewer sViewer = null;
1011 public void showStructures(boolean waitUntilFinished)
1014 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1016 final int preferredHeight = pnl_filter.getHeight();
1018 Runnable viewStruc = new Runnable()
1023 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1024 .getSelectedItem());
1025 String currentView = selectedFilterOpt.getView();
1026 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1029 if (currentView == VIEWS_FILTER)
1031 int[] selectedRows = restable.getSelectedRows();
1032 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1033 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1034 pdbEntriesToView = data.collectSelectedRows(restable,
1035 selectedRows, selectedSeqsToView);
1037 SequenceI[] selectedSeqs = selectedSeqsToView
1038 .toArray(new SequenceI[selectedSeqsToView.size()]);
1039 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1042 else if (currentView == VIEWS_LOCAL_PDB)
1044 int[] selectedRows = tbl_local_pdb.getSelectedRows();
1045 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1047 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1049 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1051 List<SequenceI> selectedSeqsToView = new ArrayList<>();
1052 for (int row : selectedRows)
1054 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1055 .getModel()).getPDBEntryAt(row).getPdbEntry();
1057 pdbEntriesToView[count++] = pdbEntry;
1058 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1059 .getValueAt(row, refSeqColIndex);
1060 selectedSeqsToView.add(selectedSeq);
1062 SequenceI[] selectedSeqs = selectedSeqsToView
1063 .toArray(new SequenceI[selectedSeqsToView.size()]);
1064 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1067 else if (currentView == VIEWS_ENTER_ID)
1069 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1070 .getCmb_assSeq().getSelectedItem()).getSequence();
1071 if (userSelectedSeq != null)
1073 selectedSequence = userSelectedSeq;
1075 String pdbIdStr = txt_search.getText();
1076 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1077 if (pdbEntry == null)
1079 pdbEntry = new PDBEntry();
1080 if (pdbIdStr.split(":").length > 1)
1082 pdbEntry.setId(pdbIdStr.split(":")[0]);
1083 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1087 pdbEntry.setId(pdbIdStr);
1089 pdbEntry.setType(PDBEntry.Type.PDB);
1090 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1093 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1094 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1096 { selectedSequence });
1098 else if (currentView == VIEWS_FROM_FILE)
1100 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1101 .getCmb_assSeq().getSelectedItem()).getSequence();
1102 if (userSelectedSeq != null)
1104 selectedSequence = userSelectedSeq;
1106 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1107 .associatePdbWithSeq(selectedPdbFileName,
1108 DataSourceType.FILE, selectedSequence, true,
1111 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1113 { selectedSequence });
1115 SwingUtilities.invokeLater(new Runnable()
1120 closeAction(preferredHeight);
1121 mainFrame.dispose();
1126 Thread runner = new Thread(viewStruc);
1128 if (waitUntilFinished)
1130 while (sViewer == null ? runner.isAlive()
1131 : (sViewer.sview == null ? true
1132 : !sViewer.sview.hasMapping()))
1137 } catch (InterruptedException ie)
1146 * Answers a structure viewer (new or existing) configured to superimpose
1147 * added structures or not according to the user's choice
1152 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1154 Object sv = targetView.getSelectedItem();
1156 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1160 * Adds PDB structures to a new or existing structure viewer
1163 * @param pdbEntriesToView
1168 private StructureViewer launchStructureViewer(
1169 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1170 final AlignmentPanel alignPanel, SequenceI[] sequences)
1172 long progressId = sequences.hashCode();
1173 setProgressBar(MessageManager
1174 .getString("status.launching_3d_structure_viewer"), progressId);
1175 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1176 boolean superimpose = chk_superpose.isSelected();
1177 theViewer.setSuperpose(superimpose);
1180 * remember user's choice of superimpose or not
1182 Cache.setProperty(AUTOSUPERIMPOSE,
1183 Boolean.valueOf(superimpose).toString());
1185 setProgressBar(null, progressId);
1186 if (SiftsSettings.isMapWithSifts())
1188 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1190 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1191 // real PDB ID. For moment, we can also safely do this if there is already
1192 // a known mapping between the PDBEntry and the sequence.
1193 for (SequenceI seq : sequences)
1195 PDBEntry pdbe = pdbEntriesToView[p++];
1196 if (pdbe != null && pdbe.getFile() != null)
1198 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1199 if (smm != null && smm.length > 0)
1201 for (StructureMapping sm : smm)
1203 if (sm.getSequence() == seq)
1210 if (seq.getPrimaryDBRefs().isEmpty())
1212 seqsWithoutSourceDBRef.add(seq);
1216 if (!seqsWithoutSourceDBRef.isEmpty())
1218 int y = seqsWithoutSourceDBRef.size();
1219 setProgressBar(MessageManager.formatMessage(
1220 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1222 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1223 .toArray(new SequenceI[y]);
1224 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1225 dbRefFetcher.fetchDBRefs(true);
1227 setProgressBar("Fetch complete.", progressId); // todo i18n
1230 if (pdbEntriesToView.length > 1)
1233 MessageManager.getString(
1234 "status.fetching_3d_structures_for_selected_entries"),
1236 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1240 setProgressBar(MessageManager.formatMessage(
1241 "status.fetching_3d_structures_for",
1242 pdbEntriesToView[0].getId()), progressId);
1243 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1245 setProgressBar(null, progressId);
1246 // remember the last viewer we used...
1247 lastTargetedView = theViewer;
1252 * Populates the combo-box used in associating manually fetched structures to
1253 * a unique sequence when more than one sequence selection is made.
1256 protected void populateCmbAssociateSeqOptions(
1257 JComboBox<AssociateSeqOptions> cmb_assSeq,
1258 JLabel lbl_associateSeq)
1260 cmb_assSeq.removeAllItems();
1262 new AssociateSeqOptions("-Select Associated Seq-", null));
1263 lbl_associateSeq.setVisible(false);
1264 if (selectedSequences.length > 1)
1266 for (SequenceI seq : selectedSequences)
1268 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1273 String seqName = selectedSequence.getDisplayId(false);
1274 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1275 lbl_associateSeq.setText(seqName);
1276 lbl_associateSeq.setVisible(true);
1277 cmb_assSeq.setVisible(false);
1281 protected boolean isStructuresDiscovered()
1283 return discoveredStructuresSet != null
1284 && !discoveredStructuresSet.isEmpty();
1287 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1289 // Doing a search for "1" or "1c" is valuable?
1290 // Those work but are enormously slow.
1293 protected void txt_search_ActionPerformed()
1295 String text = txt_search.getText().trim();
1296 if (text.length() >= PDB_ID_MIN)
1303 errorWarning.setLength(0);
1304 isValidPBDEntry = false;
1305 if (text.length() > 0)
1307 // TODO move this pdb id search into the PDB specific
1309 // for moment, it will work fine as is because it is self-contained
1310 String searchTerm = text.toLowerCase(Locale.ROOT);
1311 searchTerm = searchTerm.split(":")[0];
1312 // System.out.println(">>>>> search term : " + searchTerm);
1313 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1314 FTSRestRequest pdbRequest = new FTSRestRequest();
1315 pdbRequest.setAllowEmptySeq(false);
1316 pdbRequest.setResponseSize(1);
1317 pdbRequest.setFieldToSearchBy("(pdb_id:");
1318 pdbRequest.setWantedFields(wantedFields);
1319 pdbRequest.setSearchTerm(searchTerm + ")");
1320 pdbRequest.setAssociatedSequence(selectedSequence);
1321 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1322 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1323 FTSRestResponse resultList;
1326 resultList = pdbRestClient.executeRequest(pdbRequest);
1327 } catch (Exception e)
1329 errorWarning.append(e.getMessage());
1333 validateSelections();
1335 if (resultList.getSearchSummary() != null
1336 && resultList.getSearchSummary().size() > 0)
1338 isValidPBDEntry = true;
1341 validateSelections();
1347 protected void tabRefresh()
1349 if (selectedSequences != null)
1351 Thread refreshThread = new Thread(new Runnable()
1356 fetchStructuresMetaData();
1357 // populateFilterComboBox(true, cachedPDBExists);
1360 ((FilterOption) cmb_filterOption.getSelectedItem())
1364 refreshThread.start();
1368 public class PDBEntryTableModel extends AbstractTableModel
1370 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1373 private List<CachedPDB> pdbEntries;
1375 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1377 this.pdbEntries = new ArrayList<>(pdbEntries);
1381 public String getColumnName(int columnIndex)
1383 return columns[columnIndex];
1387 public int getRowCount()
1389 return pdbEntries.size();
1393 public int getColumnCount()
1395 return columns.length;
1399 public boolean isCellEditable(int row, int column)
1405 public Object getValueAt(int rowIndex, int columnIndex)
1407 Object value = "??";
1408 CachedPDB entry = pdbEntries.get(rowIndex);
1409 switch (columnIndex)
1412 value = entry.getSequence();
1415 value = entry.getQualifiedId();
1418 value = entry.getPdbEntry().getChainCode() == null ? "_"
1419 : entry.getPdbEntry().getChainCode();
1422 value = entry.getPdbEntry().getType();
1425 value = entry.getPdbEntry().getFile();
1432 public Class<?> getColumnClass(int columnIndex)
1434 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1437 public CachedPDB getPDBEntryAt(int row)
1439 return pdbEntries.get(row);
1444 private class CachedPDB
1446 private SequenceI sequence;
1448 private PDBEntry pdbEntry;
1450 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1452 this.sequence = sequence;
1453 this.pdbEntry = pdbEntry;
1456 public String getQualifiedId()
1458 if (pdbEntry.hasProvider())
1460 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1462 return pdbEntry.toString();
1465 public SequenceI getSequence()
1470 public PDBEntry getPdbEntry()
1477 private IProgressIndicator progressBar;
1480 public void setProgressBar(String message, long id)
1482 progressBar.setProgressBar(message, id);
1486 public void registerHandler(long id, IProgressIndicatorHandler handler)
1488 progressBar.registerHandler(id, handler);
1492 public boolean operationInProgress()
1494 return progressBar.operationInProgress();
1497 public JalviewStructureDisplayI getOpenedStructureViewer()
1499 return sViewer == null ? null : sViewer.sview;
1503 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1505 data.setDocFieldPrefs(newPrefs);
1511 * @return true when all initialisation threads have finished and dialog is
1514 public boolean isDialogVisible()
1516 return mainFrame != null && data != null && cmb_filterOption != null
1517 && mainFrame.isVisible()
1518 && cmb_filterOption.getSelectedItem() != null;
1522 * @return true if the 3D-Beacons query button will/has been displayed
1524 public boolean isCanQueryTDB() {
1528 public boolean isNotQueriedTDBYet()
1530 return notQueriedTDBYet;