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";
85 * transient combo box choice for initiating 3db fetch
87 private static final String VIEWS_QUERYING_TDB = "QUERY_3DB";
89 private SequenceI selectedSequence;
91 private SequenceI[] selectedSequences;
93 private IProgressIndicator progressIndicator;
95 private Collection<FTSData> discoveredStructuresSet;
97 private StructureChooserQuerySource data;
100 protected FTSDataColumnPreferences getFTSDocFieldPrefs()
102 return data.getDocFieldPrefs();
105 private String selectedPdbFileName;
107 private boolean isValidPBDEntry;
109 private boolean cachedPDBExists;
111 private Collection<FTSData> lastDiscoveredStructuresSet;
113 private boolean canQueryTDB = false;
115 private boolean notQueriedTDBYet = true;
117 List<SequenceI> seqsWithoutSourceDBRef = null;
119 private static StructureViewer lastTargetedView = null;
121 public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
124 // which FTS engine to use
125 data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
129 this.selectedSequence = selectedSeq;
130 this.selectedSequences = selectedSeqs;
131 this.progressIndicator = (ap == null) ? null : ap.alignFrame;
137 * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
138 * least one structure are discovered.
140 private void populateSeqsWithoutSourceDBRef()
142 seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
143 boolean needCanonical = false;
144 for (SequenceI seq : selectedSequences)
148 int dbRef = ThreeDBStructureChooserQuerySource
149 .checkUniprotRefs(seq.getDBRefs());
154 // need to retrieve canonicals
155 needCanonical = true;
156 seqsWithoutSourceDBRef.add(seq);
160 // could be a sequence with pdb ref
161 if (seq.getAllPDBEntries() == null
162 || seq.getAllPDBEntries().size() == 0)
164 seqsWithoutSourceDBRef.add(seq);
170 // retrieve database refs for protein sequences
171 if (!seqsWithoutSourceDBRef.isEmpty())
176 notQueriedTDBYet = false;
182 * Initializes parameters used by the Structure Chooser Panel
184 protected void init()
186 if (!Jalview.isHeadlessMode())
188 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
191 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
193 Executors.defaultThreadFactory().newThread(new Runnable()
197 populateSeqsWithoutSourceDBRef();
198 initialStructureDiscovery();
206 private void initialStructureDiscovery()
208 // check which FTS engine to use
209 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
211 // ensure a filter option is in force for search
212 populateFilterComboBox(true, cachedPDBExists);
214 // looks for any existing structures already loaded
215 // for the sequences (the cached ones)
216 // then queries the StructureChooserQuerySource to
217 // discover more structures.
219 // Possible optimisation is to only begin querying
220 // the structure chooser if there are no cached structures.
222 long startTime = System.currentTimeMillis();
223 updateProgressIndicator(
224 MessageManager.getString("status.loading_cached_pdb_entries"),
226 loadLocalCachedPDBEntries();
227 updateProgressIndicator(null, startTime);
228 updateProgressIndicator(
229 MessageManager.getString("status.searching_for_pdb_structures"),
231 fetchStructuresMetaData();
232 // revise filter options if no results were found
233 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
234 discoverStructureViews();
235 updateProgressIndicator(null, startTime);
236 mainFrame.setVisible(true);
240 private void promptForTDBFetch()
242 final long progressId = System.currentTimeMillis();
244 // final action after prompting and discovering db refs
245 final Runnable strucDiscovery = new Runnable()
250 progressBar.setProgressBar("status.searching_3d_beacons", progressId);
251 // TODO: warn if no accessions discovered
252 populateSeqsWithoutSourceDBRef();
253 // redo initial discovery - this time with 3d beacons
255 previousWantedFields=null;
256 initialStructureDiscovery();
257 if (!isStructuresDiscovered())
259 progressBar.setProgressBar("status.no_structures_discovered_from_3d_beacons", progressId);
261 progressBar.setProgressBar(null, progressId);
266 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
270 public void finished()
272 // filter has been selected, so we set flag to remove ourselves
273 notQueriedTDBYet = false;
274 // new thread to discover structures - via 3d beacons
275 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
280 // fetch db refs if OK pressed
281 final Runnable discoverCanonicalDBrefs = new Runnable()
286 populateSeqsWithoutSourceDBRef();
288 final int y = seqsWithoutSourceDBRef.size();
291 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
292 .toArray(new SequenceI[y]);
293 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
294 progressBar, new DbSourceProxy[]
295 { new jalview.ws.dbsources.Uniprot() }, null, false);
296 dbRefFetcher.addListener(afterDbRefFetch);
297 // ideally this would also gracefully run with callbacks
298 dbRefFetcher.fetchDBRefs(true);
300 // call finished action directly
301 afterDbRefFetch.finished();
306 final Runnable revertview = new Runnable() {
308 if (lastSelected!=null) {
309 cmb_filterOption.setSelectedItem(lastSelected);
313 // need cancel and no to result in the discoverPDB action - mocked is
315 JvOptionPane.newOptionDialog(this)
316 .setResponseHandler(JvOptionPane.OK_OPTION,
317 discoverCanonicalDBrefs)
318 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
319 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
321 MessageManager.formatMessage(
322 "label.fetch_references_for_3dbeacons",
323 seqsWithoutSourceDBRef.size()),
325 .getString("label.3dbeacons"),
326 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
328 { MessageManager.getString("action.ok"),
329 MessageManager.getString("action.cancel") },
330 MessageManager.getString("action.ok"));
334 * Builds a drop-down choice list of existing structure viewers to which new
335 * structures may be added. If this list is empty then it, and the 'Add'
336 * button, are hidden.
338 private void discoverStructureViews()
340 if (Desktop.instance != null)
342 targetView.removeAllItems();
343 if (lastTargetedView != null && !lastTargetedView.isVisible())
345 lastTargetedView = null;
347 int linkedViewsAt = 0;
348 for (StructureViewerBase view : Desktop.instance
349 .getStructureViewers(null, null))
351 StructureViewer viewHandler = (lastTargetedView != null
352 && lastTargetedView.sview == view) ? lastTargetedView
353 : StructureViewer.reconfigure(view);
355 if (view.isLinkedWith(ap))
357 targetView.insertItemAt(viewHandler, linkedViewsAt++);
361 targetView.addItem(viewHandler);
366 * show option to Add to viewer if at least 1 viewer found
368 targetView.setVisible(false);
369 if (targetView.getItemCount() > 0)
371 targetView.setVisible(true);
372 if (lastTargetedView != null)
374 targetView.setSelectedItem(lastTargetedView);
378 targetView.setSelectedIndex(0);
381 btn_add.setVisible(targetView.isVisible());
386 * Updates the progress indicator with the specified message
389 * displayed message for the operation
391 * unique handle for this indicator
393 protected void updateProgressIndicator(String message, long id)
395 if (progressIndicator != null)
397 progressIndicator.setProgressBar(message, id);
402 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
405 void fetchStructuresMetaData()
407 long startTime = System.currentTimeMillis();
408 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
409 .getStructureSummaryFields();
411 discoveredStructuresSet = new LinkedHashSet<>();
412 HashSet<String> errors = new HashSet<>();
414 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
417 for (SequenceI seq : selectedSequences)
420 FTSRestResponse resultList;
423 resultList = data.fetchStructuresMetaData(seq, wantedFields,
424 selectedFilterOpt, !chk_invertFilter.isSelected());
425 // null response means the FTSengine didn't yield a query for this
426 // consider designing a special exception if we really wanted to be
428 if (resultList == null)
432 } catch (Exception e)
435 errors.add(e.getMessage());
438 if (resultList.getSearchSummary() != null
439 && !resultList.getSearchSummary().isEmpty())
441 discoveredStructuresSet.addAll(resultList.getSearchSummary());
445 int noOfStructuresFound = 0;
446 String totalTime = (System.currentTimeMillis() - startTime)
448 if (discoveredStructuresSet != null
449 && !discoveredStructuresSet.isEmpty())
452 .setModel(data.getTableModel(discoveredStructuresSet));
454 noOfStructuresFound = discoveredStructuresSet.size();
455 lastDiscoveredStructuresSet = discoveredStructuresSet;
456 mainFrame.setTitle(MessageManager.formatMessage(
457 "label.structure_chooser_no_of_structures",
458 noOfStructuresFound, totalTime));
462 mainFrame.setTitle(MessageManager
463 .getString("label.structure_chooser_manual_association"));
464 if (errors.size() > 0)
466 StringBuilder errorMsg = new StringBuilder();
467 for (String error : errors)
469 errorMsg.append(error).append("\n");
471 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
472 MessageManager.getString("label.pdb_web-service_error"),
473 JvOptionPane.ERROR_MESSAGE);
478 protected void loadLocalCachedPDBEntries()
480 ArrayList<CachedPDB> entries = new ArrayList<>();
481 for (SequenceI seq : selectedSequences)
483 if (seq.getDatasetSequence() != null
484 && seq.getDatasetSequence().getAllPDBEntries() != null)
486 for (PDBEntry pdbEntry : seq.getDatasetSequence()
489 if (pdbEntry.getFile() != null)
491 entries.add(new CachedPDB(seq, pdbEntry));
496 cachedPDBExists = !entries.isEmpty();
497 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
498 tbl_local_pdb.setModel(tableModelx);
502 * Filters a given list of discovered structures based on supplied argument
504 * @param fieldToFilterBy
505 * the field to filter by
507 void filterResultSet(final String fieldToFilterBy)
509 Thread filterThread = new Thread(new Runnable()
515 long startTime = System.currentTimeMillis();
516 lbl_loading.setVisible(true);
517 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
518 .getStructureSummaryFields();
519 Collection<FTSData> filteredResponse = new HashSet<>();
520 HashSet<String> errors = new HashSet<>();
522 for (SequenceI seq : selectedSequences)
525 FTSRestResponse resultList;
528 resultList = data.selectFirstRankedQuery(seq,
529 discoveredStructuresSet, wantedFields, fieldToFilterBy,
530 !chk_invertFilter.isSelected());
532 } catch (Exception e)
535 errors.add(e.getMessage());
538 if (resultList.getSearchSummary() != null
539 && !resultList.getSearchSummary().isEmpty())
541 filteredResponse.addAll(resultList.getSearchSummary());
545 String totalTime = (System.currentTimeMillis() - startTime)
547 if (!filteredResponse.isEmpty())
549 final int filterResponseCount = filteredResponse.size();
550 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
551 reorderedStructuresSet.addAll(filteredResponse);
552 reorderedStructuresSet.addAll(discoveredStructuresSet);
554 .setModel(data.getTableModel(reorderedStructuresSet));
556 FTSRestResponse.configureTableColumn(getResultTable(),
557 wantedFields, tempUserPrefs);
558 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
559 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
560 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
561 // Update table selection model here
562 getResultTable().addRowSelectionInterval(0,
563 filterResponseCount - 1);
564 mainFrame.setTitle(MessageManager.formatMessage(
565 "label.structure_chooser_filter_time", totalTime));
569 mainFrame.setTitle(MessageManager.formatMessage(
570 "label.structure_chooser_filter_time", totalTime));
571 if (errors.size() > 0)
573 StringBuilder errorMsg = new StringBuilder();
574 for (String error : errors)
576 errorMsg.append(error).append("\n");
578 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
579 MessageManager.getString("label.pdb_web-service_error"),
580 JvOptionPane.ERROR_MESSAGE);
584 lbl_loading.setVisible(false);
586 validateSelections();
589 filterThread.start();
593 * Handles action event for btn_pdbFromFile
596 protected void pdbFromFile_actionPerformed()
598 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
601 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
602 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
603 chooser.setFileView(new jalview.io.JalviewFileView());
604 chooser.setDialogTitle(
605 MessageManager.formatMessage("label.select_pdb_file_for",
606 selectedSequence.getDisplayId(false)));
607 chooser.setToolTipText(MessageManager.formatMessage(
608 "label.load_pdb_file_associate_with_sequence",
609 selectedSequence.getDisplayId(false)));
611 int value = chooser.showOpenDialog(null);
612 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
614 selectedPdbFileName = chooser.getSelectedFile().getPath();
615 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
616 validateSelections();
621 * Populates the filter combo-box options dynamically depending on discovered
624 protected void populateFilterComboBox(boolean haveData,
625 boolean cachedPDBExist)
627 populateFilterComboBox(haveData, cachedPDBExist, null);
631 * Populates the filter combo-box options dynamically depending on discovered
634 protected void populateFilterComboBox(boolean haveData,
635 boolean cachedPDBExist, FilterOption lastSel)
639 * temporarily suspend the change listener behaviour
641 cmb_filterOption.removeItemListener(this);
643 cmb_filterOption.removeAllItems();
646 List<FilterOption> filters = data
647 .getAvailableFilterOptions(VIEWS_FILTER);
648 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
649 lastDiscoveredStructuresSet);
651 for (FilterOption filter : filters)
653 if (lastSel != null && filter.equals(lastSel))
658 cmb_filterOption.addItem(filter);
662 cmb_filterOption.addItem(
663 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
664 "-", VIEWS_ENTER_ID, false, null));
665 cmb_filterOption.addItem(
666 new FilterOption(MessageManager.getString("label.from_file"),
667 "-", VIEWS_FROM_FILE, false, null));
668 if (canQueryTDB && notQueriedTDBYet)
670 FilterOption queryTDBOption = new FilterOption(
671 MessageManager.getString("label.search_3dbeacons"), "-",
672 VIEWS_QUERYING_TDB, false, null);
673 cmb_filterOption.addItem(queryTDBOption);
678 FilterOption cachedOption = new FilterOption(
679 MessageManager.getString("label.cached_structures"), "-",
680 VIEWS_LOCAL_PDB, false, null);
681 cmb_filterOption.addItem(cachedOption);
684 cmb_filterOption.setSelectedItem(cachedOption);
689 cmb_filterOption.setSelectedIndex(selSet);
691 cmb_filterOption.addItemListener(this);
695 * Updates the displayed view based on the selected filter option
697 protected void updateCurrentView()
699 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
702 // first check if we need to rebuild dialog
703 if (selectedFilterOpt.getView() == VIEWS_QUERYING_TDB)
708 if (lastSelected == selectedFilterOpt)
710 // don't need to do anything, probably
713 // otherwise, record selection
714 // and update the layout and dialog accordingly
715 lastSelected = selectedFilterOpt;
717 layout_switchableViews.show(pnl_switchableViews,
718 selectedFilterOpt.getView());
719 String filterTitle = mainFrame.getTitle();
720 mainFrame.setTitle(frameTitle);
721 chk_invertFilter.setVisible(false);
723 if (selectedFilterOpt.getView() == VIEWS_FILTER)
725 mainFrame.setTitle(filterTitle);
726 // TDB Query has no invert as yet
727 chk_invertFilter.setVisible(selectedFilterOpt
728 .getQuerySource() instanceof PDBStructureChooserQuerySource);
730 if (data != selectedFilterOpt.getQuerySource()
731 || data.needsRefetch(selectedFilterOpt))
733 data = selectedFilterOpt.getQuerySource();
734 // rebuild the views completely, since prefs will also change
740 filterResultSet(selectedFilterOpt.getValue());
743 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
744 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
746 mainFrame.setTitle(MessageManager
747 .getString("label.structure_chooser_manual_association"));
748 idInputAssSeqPanel.loadCmbAssSeq();
749 fileChooserAssSeqPanel.loadCmbAssSeq();
751 validateSelections();
755 * Validates user selection and enables the 'Add' and 'New View' buttons if
756 * all parameters are correct (the Add button will only be visible if there is
757 * at least one existing structure viewer open). This basically means at least
758 * one structure selected and no error messages.
760 * The 'Superpose Structures' option is enabled if either more than one
761 * structure is selected, or the 'Add' to existing view option is enabled, and
762 * disabled if the only option is to open a new view of a single structure.
765 protected void validateSelections()
767 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
769 btn_add.setEnabled(false);
770 String currentView = selectedFilterOpt.getView();
771 int selectedCount = 0;
772 if (currentView == VIEWS_FILTER)
774 selectedCount = getResultTable().getSelectedRows().length;
775 if (selectedCount > 0)
777 btn_add.setEnabled(true);
780 else if (currentView == VIEWS_LOCAL_PDB)
782 selectedCount = tbl_local_pdb.getSelectedRows().length;
783 if (selectedCount > 0)
785 btn_add.setEnabled(true);
788 else if (currentView == VIEWS_ENTER_ID)
790 validateAssociationEnterPdb();
792 else if (currentView == VIEWS_FROM_FILE)
794 validateAssociationFromFile();
797 btn_newView.setEnabled(btn_add.isEnabled());
800 * enable 'Superpose' option if more than one structure is selected,
801 * or there are view(s) available to add structure(s) to
804 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
808 protected boolean showPopupFor(int selectedRow, int x, int y)
810 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
812 String currentView = selectedFilterOpt.getView();
814 if (currentView == VIEWS_FILTER && data instanceof ThreeDBStructureChooserQuerySource)
817 TDB_FTSData row=((ThreeDBStructureChooserQuerySource)data).getFTSDataFor(getResultTable(), selectedRow, discoveredStructuresSet);
818 String pageUrl = row.getModelViewUrl();
819 JPopupMenu popup = new JPopupMenu("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.show(getResultTable(), x, y); }
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;