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.util.Locale;
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.concurrent.Executors;
34 import javax.swing.JCheckBox;
35 import javax.swing.JComboBox;
36 import javax.swing.JLabel;
37 import javax.swing.JTable;
38 import javax.swing.SwingUtilities;
39 import javax.swing.table.AbstractTableModel;
41 import jalview.api.structures.JalviewStructureDisplayI;
42 import jalview.bin.Cache;
43 import jalview.bin.Jalview;
44 import jalview.datamodel.PDBEntry;
45 import jalview.datamodel.SequenceI;
46 import jalview.fts.api.FTSData;
47 import jalview.fts.api.FTSDataColumnI;
48 import jalview.fts.api.FTSRestClientI;
49 import jalview.fts.core.FTSDataColumnPreferences;
50 import jalview.fts.core.FTSRestRequest;
51 import jalview.fts.core.FTSRestResponse;
52 import jalview.fts.service.pdb.PDBFTSRestClient;
53 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
54 import jalview.gui.structurechooser.StructureChooserQuerySource;
55 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
56 import jalview.io.DataSourceType;
57 import jalview.jbgui.FilterOption;
58 import jalview.jbgui.GStructureChooser;
59 import jalview.structure.StructureMapping;
60 import jalview.structure.StructureSelectionManager;
61 import jalview.util.MessageManager;
62 import jalview.ws.DBRefFetcher;
63 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
64 import jalview.ws.seqfetcher.DbSourceProxy;
65 import jalview.ws.sifts.SiftsSettings;
68 * Provides the behaviors for the Structure chooser Panel
73 @SuppressWarnings("serial")
74 public class StructureChooser extends GStructureChooser
75 implements IProgressIndicator
77 private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
80 * transient combo box choice for initiating 3db fetch
82 private static final String VIEWS_QUERYING_TDB = "QUERY_3DB";
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 notQueriedTDBYet = false;
177 * Initializes parameters used by the Structure Chooser Panel
179 protected void init()
181 if (!Jalview.isHeadlessMode())
183 progressBar = new ProgressBar(this.statusPanel, this.statusBar);
186 chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
188 Executors.defaultThreadFactory().newThread(new Runnable()
192 populateSeqsWithoutSourceDBRef();
193 initialStructureDiscovery();
201 private void initialStructureDiscovery()
203 // check which FTS engine to use
204 data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
206 // ensure a filter option is in force for search
207 populateFilterComboBox(true, cachedPDBExists);
209 // looks for any existing structures already loaded
210 // for the sequences (the cached ones)
211 // then queries the StructureChooserQuerySource to
212 // discover more structures.
214 // Possible optimisation is to only begin querying
215 // the structure chooser if there are no cached structures.
217 long startTime = System.currentTimeMillis();
218 updateProgressIndicator(
219 MessageManager.getString("status.loading_cached_pdb_entries"),
221 loadLocalCachedPDBEntries();
222 updateProgressIndicator(null, startTime);
223 updateProgressIndicator(
224 MessageManager.getString("status.searching_for_pdb_structures"),
226 fetchStructuresMetaData();
227 // revise filter options if no results were found
228 populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
229 discoverStructureViews();
230 updateProgressIndicator(null, startTime);
231 mainFrame.setVisible(true);
235 private void promptForTDBFetch()
237 final long progressId = System.currentTimeMillis();
239 // final action after prompting and discovering db refs
240 final Runnable strucDiscovery = new Runnable()
245 progressBar.setProgressBar("status.searching_3d_beacons", progressId);
246 // TODO: warn if no accessions discovered
247 populateSeqsWithoutSourceDBRef();
248 // redo initial discovery - this time with 3d beacons
250 previousWantedFields=null;
251 initialStructureDiscovery();
252 if (!isStructuresDiscovered())
254 progressBar.setProgressBar("status.no_structures_discovered_from_3d_beacons", progressId);
256 progressBar.setProgressBar(null, progressId);
261 final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
265 public void finished()
267 // filter has been selected, so we set flag to remove ourselves
268 notQueriedTDBYet = false;
269 // new thread to discover structures - via 3d beacons
270 Executors.defaultThreadFactory().newThread(strucDiscovery).start();
275 // fetch db refs if OK pressed
276 final Runnable discoverCanonicalDBrefs = new Runnable()
281 populateSeqsWithoutSourceDBRef();
283 final int y = seqsWithoutSourceDBRef.size();
286 final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
287 .toArray(new SequenceI[y]);
288 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
289 progressBar, new DbSourceProxy[]
290 { new jalview.ws.dbsources.Uniprot() }, null, false);
291 dbRefFetcher.addListener(afterDbRefFetch);
292 // ideally this would also gracefully run with callbacks
293 dbRefFetcher.fetchDBRefs(true);
295 // call finished action directly
296 afterDbRefFetch.finished();
301 final Runnable revertview = new Runnable() {
303 if (lastSelected!=null) {
304 cmb_filterOption.setSelectedItem(lastSelected);
308 // need cancel and no to result in the discoverPDB action - mocked is
310 JvOptionPane.newOptionDialog(this)
311 .setResponseHandler(JvOptionPane.OK_OPTION,
312 discoverCanonicalDBrefs)
313 .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
314 .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
316 MessageManager.formatMessage(
317 "label.fetch_references_for_3dbeacons",
318 seqsWithoutSourceDBRef.size()),
320 .getString("label.3dbeacons"),
321 JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
323 { MessageManager.getString("action.ok"),
324 MessageManager.getString("action.cancel") },
325 MessageManager.getString("action.ok"));
329 * Builds a drop-down choice list of existing structure viewers to which new
330 * structures may be added. If this list is empty then it, and the 'Add'
331 * button, are hidden.
333 private void discoverStructureViews()
335 if (Desktop.instance != null)
337 targetView.removeAllItems();
338 if (lastTargetedView != null && !lastTargetedView.isVisible())
340 lastTargetedView = null;
342 int linkedViewsAt = 0;
343 for (StructureViewerBase view : Desktop.instance
344 .getStructureViewers(null, null))
346 StructureViewer viewHandler = (lastTargetedView != null
347 && lastTargetedView.sview == view) ? lastTargetedView
348 : StructureViewer.reconfigure(view);
350 if (view.isLinkedWith(ap))
352 targetView.insertItemAt(viewHandler, linkedViewsAt++);
356 targetView.addItem(viewHandler);
361 * show option to Add to viewer if at least 1 viewer found
363 targetView.setVisible(false);
364 if (targetView.getItemCount() > 0)
366 targetView.setVisible(true);
367 if (lastTargetedView != null)
369 targetView.setSelectedItem(lastTargetedView);
373 targetView.setSelectedIndex(0);
376 btn_add.setVisible(targetView.isVisible());
381 * Updates the progress indicator with the specified message
384 * displayed message for the operation
386 * unique handle for this indicator
388 protected void updateProgressIndicator(String message, long id)
390 if (progressIndicator != null)
392 progressIndicator.setProgressBar(message, id);
397 * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
400 void fetchStructuresMetaData()
402 long startTime = System.currentTimeMillis();
403 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
404 .getStructureSummaryFields();
406 discoveredStructuresSet = new LinkedHashSet<>();
407 HashSet<String> errors = new HashSet<>();
409 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
412 for (SequenceI seq : selectedSequences)
415 FTSRestResponse resultList;
418 resultList = data.fetchStructuresMetaData(seq, wantedFields,
419 selectedFilterOpt, !chk_invertFilter.isSelected());
420 // null response means the FTSengine didn't yield a query for this
421 // consider designing a special exception if we really wanted to be
423 if (resultList == null)
427 } catch (Exception e)
430 errors.add(e.getMessage());
433 if (resultList.getSearchSummary() != null
434 && !resultList.getSearchSummary().isEmpty())
436 discoveredStructuresSet.addAll(resultList.getSearchSummary());
440 int noOfStructuresFound = 0;
441 String totalTime = (System.currentTimeMillis() - startTime)
443 if (discoveredStructuresSet != null
444 && !discoveredStructuresSet.isEmpty())
447 .setModel(data.getTableModel(discoveredStructuresSet));
449 noOfStructuresFound = discoveredStructuresSet.size();
450 lastDiscoveredStructuresSet = discoveredStructuresSet;
451 mainFrame.setTitle(MessageManager.formatMessage(
452 "label.structure_chooser_no_of_structures",
453 noOfStructuresFound, totalTime));
457 mainFrame.setTitle(MessageManager
458 .getString("label.structure_chooser_manual_association"));
459 if (errors.size() > 0)
461 StringBuilder errorMsg = new StringBuilder();
462 for (String error : errors)
464 errorMsg.append(error).append("\n");
466 JvOptionPane.showMessageDialog(this, errorMsg.toString(),
467 MessageManager.getString("label.pdb_web-service_error"),
468 JvOptionPane.ERROR_MESSAGE);
473 protected void loadLocalCachedPDBEntries()
475 ArrayList<CachedPDB> entries = new ArrayList<>();
476 for (SequenceI seq : selectedSequences)
478 if (seq.getDatasetSequence() != null
479 && seq.getDatasetSequence().getAllPDBEntries() != null)
481 for (PDBEntry pdbEntry : seq.getDatasetSequence()
484 if (pdbEntry.getFile() != null)
486 entries.add(new CachedPDB(seq, pdbEntry));
491 cachedPDBExists = !entries.isEmpty();
492 PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
493 tbl_local_pdb.setModel(tableModelx);
497 * Filters a given list of discovered structures based on supplied argument
499 * @param fieldToFilterBy
500 * the field to filter by
502 void filterResultSet(final String fieldToFilterBy)
504 Thread filterThread = new Thread(new Runnable()
510 long startTime = System.currentTimeMillis();
511 lbl_loading.setVisible(true);
512 Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
513 .getStructureSummaryFields();
514 Collection<FTSData> filteredResponse = new HashSet<>();
515 HashSet<String> errors = new HashSet<>();
517 for (SequenceI seq : selectedSequences)
520 FTSRestResponse resultList;
523 resultList = data.selectFirstRankedQuery(seq,
524 discoveredStructuresSet, wantedFields, fieldToFilterBy,
525 !chk_invertFilter.isSelected());
527 } catch (Exception e)
530 errors.add(e.getMessage());
533 if (resultList.getSearchSummary() != null
534 && !resultList.getSearchSummary().isEmpty())
536 filteredResponse.addAll(resultList.getSearchSummary());
540 String totalTime = (System.currentTimeMillis() - startTime)
542 if (!filteredResponse.isEmpty())
544 final int filterResponseCount = filteredResponse.size();
545 Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
546 reorderedStructuresSet.addAll(filteredResponse);
547 reorderedStructuresSet.addAll(discoveredStructuresSet);
549 .setModel(data.getTableModel(reorderedStructuresSet));
551 FTSRestResponse.configureTableColumn(getResultTable(),
552 wantedFields, tempUserPrefs);
553 getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
554 getResultTable().getColumn("Ref Sequence").setMinWidth(100);
555 getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
556 // Update table selection model here
557 getResultTable().addRowSelectionInterval(0,
558 filterResponseCount - 1);
559 mainFrame.setTitle(MessageManager.formatMessage(
560 "label.structure_chooser_filter_time", totalTime));
564 mainFrame.setTitle(MessageManager.formatMessage(
565 "label.structure_chooser_filter_time", totalTime));
566 if (errors.size() > 0)
568 StringBuilder errorMsg = new StringBuilder();
569 for (String error : errors)
571 errorMsg.append(error).append("\n");
573 JvOptionPane.showMessageDialog(null, errorMsg.toString(),
574 MessageManager.getString("label.pdb_web-service_error"),
575 JvOptionPane.ERROR_MESSAGE);
579 lbl_loading.setVisible(false);
581 validateSelections();
584 filterThread.start();
588 * Handles action event for btn_pdbFromFile
591 protected void pdbFromFile_actionPerformed()
593 // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
596 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
597 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
598 chooser.setFileView(new jalview.io.JalviewFileView());
599 chooser.setDialogTitle(
600 MessageManager.formatMessage("label.select_pdb_file_for",
601 selectedSequence.getDisplayId(false)));
602 chooser.setToolTipText(MessageManager.formatMessage(
603 "label.load_pdb_file_associate_with_sequence",
604 selectedSequence.getDisplayId(false)));
606 int value = chooser.showOpenDialog(null);
607 if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
609 selectedPdbFileName = chooser.getSelectedFile().getPath();
610 jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
611 validateSelections();
616 * Populates the filter combo-box options dynamically depending on discovered
619 protected void populateFilterComboBox(boolean haveData,
620 boolean cachedPDBExist)
622 populateFilterComboBox(haveData, cachedPDBExist, null);
626 * Populates the filter combo-box options dynamically depending on discovered
629 protected void populateFilterComboBox(boolean haveData,
630 boolean cachedPDBExist, FilterOption lastSel)
634 * temporarily suspend the change listener behaviour
636 cmb_filterOption.removeItemListener(this);
638 cmb_filterOption.removeAllItems();
641 List<FilterOption> filters = data
642 .getAvailableFilterOptions(VIEWS_FILTER);
643 data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
644 lastDiscoveredStructuresSet);
646 for (FilterOption filter : filters)
648 if (lastSel != null && filter.equals(lastSel))
653 cmb_filterOption.addItem(filter);
657 cmb_filterOption.addItem(
658 new FilterOption(MessageManager.getString("label.enter_pdb_id"),
659 "-", VIEWS_ENTER_ID, false, null));
660 cmb_filterOption.addItem(
661 new FilterOption(MessageManager.getString("label.from_file"),
662 "-", VIEWS_FROM_FILE, false, null));
663 if (canQueryTDB && notQueriedTDBYet)
665 FilterOption queryTDBOption = new FilterOption(
666 MessageManager.getString("label.search_3dbeacons"), "-",
667 VIEWS_QUERYING_TDB, false, null);
668 cmb_filterOption.addItem(queryTDBOption);
673 FilterOption cachedOption = new FilterOption(
674 MessageManager.getString("label.cached_structures"), "-",
675 VIEWS_LOCAL_PDB, false, null);
676 cmb_filterOption.addItem(cachedOption);
679 cmb_filterOption.setSelectedItem(cachedOption);
684 cmb_filterOption.setSelectedIndex(selSet);
686 cmb_filterOption.addItemListener(this);
690 * Updates the displayed view based on the selected filter option
692 protected void updateCurrentView()
694 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
697 // first check if we need to rebuild dialog
698 if (selectedFilterOpt.getView() == VIEWS_QUERYING_TDB)
703 if (lastSelected == selectedFilterOpt)
705 // don't need to do anything, probably
708 // otherwise, record selection
709 // and update the layout and dialog accordingly
710 lastSelected = selectedFilterOpt;
712 layout_switchableViews.show(pnl_switchableViews,
713 selectedFilterOpt.getView());
714 String filterTitle = mainFrame.getTitle();
715 mainFrame.setTitle(frameTitle);
716 chk_invertFilter.setVisible(false);
718 if (selectedFilterOpt.getView() == VIEWS_FILTER)
720 mainFrame.setTitle(filterTitle);
721 // TDB Query has no invert as yet
722 chk_invertFilter.setVisible(selectedFilterOpt
723 .getQuerySource() instanceof PDBStructureChooserQuerySource);
725 if (data != selectedFilterOpt.getQuerySource()
726 || data.needsRefetch(selectedFilterOpt))
728 data = selectedFilterOpt.getQuerySource();
729 // rebuild the views completely, since prefs will also change
735 filterResultSet(selectedFilterOpt.getValue());
738 else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
739 || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
741 mainFrame.setTitle(MessageManager
742 .getString("label.structure_chooser_manual_association"));
743 idInputAssSeqPanel.loadCmbAssSeq();
744 fileChooserAssSeqPanel.loadCmbAssSeq();
746 validateSelections();
750 * Validates user selection and enables the 'Add' and 'New View' buttons if
751 * all parameters are correct (the Add button will only be visible if there is
752 * at least one existing structure viewer open). This basically means at least
753 * one structure selected and no error messages.
755 * The 'Superpose Structures' option is enabled if either more than one
756 * structure is selected, or the 'Add' to existing view option is enabled, and
757 * disabled if the only option is to open a new view of a single structure.
760 protected void validateSelections()
762 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
764 btn_add.setEnabled(false);
765 String currentView = selectedFilterOpt.getView();
766 int selectedCount = 0;
767 if (currentView == VIEWS_FILTER)
769 selectedCount = getResultTable().getSelectedRows().length;
770 if (selectedCount > 0)
772 btn_add.setEnabled(true);
775 else if (currentView == VIEWS_LOCAL_PDB)
777 selectedCount = tbl_local_pdb.getSelectedRows().length;
778 if (selectedCount > 0)
780 btn_add.setEnabled(true);
783 else if (currentView == VIEWS_ENTER_ID)
785 validateAssociationEnterPdb();
787 else if (currentView == VIEWS_FROM_FILE)
789 validateAssociationFromFile();
792 btn_newView.setEnabled(btn_add.isEnabled());
795 * enable 'Superpose' option if more than one structure is selected,
796 * or there are view(s) available to add structure(s) to
799 .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
803 * Validates inputs from the Manual PDB entry panel
805 protected void validateAssociationEnterPdb()
807 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
808 .getCmb_assSeq().getSelectedItem();
809 lbl_pdbManualFetchStatus.setIcon(errorImage);
810 lbl_pdbManualFetchStatus.setToolTipText("");
811 if (txt_search.getText().length() > 0)
813 lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
814 MessageManager.formatMessage("info.no_pdb_entry_found_for",
815 txt_search.getText())));
818 if (errorWarning.length() > 0)
820 lbl_pdbManualFetchStatus.setIcon(warningImage);
821 lbl_pdbManualFetchStatus.setToolTipText(
822 JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
825 if (selectedSequences.length == 1 || !assSeqOpt.getName()
826 .equalsIgnoreCase("-Select Associated Seq-"))
828 txt_search.setEnabled(true);
831 btn_add.setEnabled(true);
832 lbl_pdbManualFetchStatus.setToolTipText("");
833 lbl_pdbManualFetchStatus.setIcon(goodImage);
838 txt_search.setEnabled(false);
839 lbl_pdbManualFetchStatus.setIcon(errorImage);
844 * Validates inputs for the manual PDB file selection options
846 protected void validateAssociationFromFile()
848 AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
849 .getCmb_assSeq().getSelectedItem();
850 lbl_fromFileStatus.setIcon(errorImage);
851 if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
852 .getName().equalsIgnoreCase("-Select Associated Seq-")))
854 btn_pdbFromFile.setEnabled(true);
855 if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
857 btn_add.setEnabled(true);
858 lbl_fromFileStatus.setIcon(goodImage);
863 btn_pdbFromFile.setEnabled(false);
864 lbl_fromFileStatus.setIcon(errorImage);
869 protected void cmbAssSeqStateChanged()
871 validateSelections();
873 private FilterOption lastSelected=null;
875 * Handles the state change event for the 'filter' combo-box and 'invert'
879 protected void stateChanged(ItemEvent e)
881 if (e.getSource() instanceof JCheckBox)
887 if (e.getStateChange() == ItemEvent.SELECTED)
896 * select structures for viewing by their PDB IDs
899 * @return true if structures were found and marked as selected
901 public boolean selectStructure(String... pdbids)
903 boolean found = false;
905 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
907 String currentView = selectedFilterOpt.getView();
908 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
909 : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
911 if (restable == null)
913 // can't select (enter PDB ID, or load file - need to also select which
914 // sequence to associate with)
918 int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
919 for (int r = 0; r < restable.getRowCount(); r++)
921 for (int p = 0; p < pdbids.length; p++)
923 if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
924 .equalsIgnoreCase(pdbids[p]))
926 restable.setRowSelectionInterval(r, r);
935 * Handles the 'New View' action
938 protected void newView_ActionPerformed()
940 targetView.setSelectedItem(null);
941 showStructures(false);
945 * Handles the 'Add to existing viewer' action
948 protected void add_ActionPerformed()
950 showStructures(false);
954 * structure viewer opened by this dialog, or null
956 private StructureViewer sViewer = null;
958 public void showStructures(boolean waitUntilFinished)
961 final StructureSelectionManager ssm = ap.getStructureSelectionManager();
963 final int preferredHeight = pnl_filter.getHeight();
965 Runnable viewStruc = new Runnable()
970 FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
972 String currentView = selectedFilterOpt.getView();
973 JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
976 if (currentView == VIEWS_FILTER)
978 int[] selectedRows = restable.getSelectedRows();
979 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
980 List<SequenceI> selectedSeqsToView = new ArrayList<>();
981 pdbEntriesToView = data.collectSelectedRows(restable,
982 selectedRows, selectedSeqsToView);
984 SequenceI[] selectedSeqs = selectedSeqsToView
985 .toArray(new SequenceI[selectedSeqsToView.size()]);
986 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
989 else if (currentView == VIEWS_LOCAL_PDB)
991 int[] selectedRows = tbl_local_pdb.getSelectedRows();
992 PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
994 int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
996 int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
998 List<SequenceI> selectedSeqsToView = new ArrayList<>();
999 for (int row : selectedRows)
1001 PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1002 .getModel()).getPDBEntryAt(row).getPdbEntry();
1004 pdbEntriesToView[count++] = pdbEntry;
1005 SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1006 .getValueAt(row, refSeqColIndex);
1007 selectedSeqsToView.add(selectedSeq);
1009 SequenceI[] selectedSeqs = selectedSeqsToView
1010 .toArray(new SequenceI[selectedSeqsToView.size()]);
1011 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1014 else if (currentView == VIEWS_ENTER_ID)
1016 SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1017 .getCmb_assSeq().getSelectedItem()).getSequence();
1018 if (userSelectedSeq != null)
1020 selectedSequence = userSelectedSeq;
1022 String pdbIdStr = txt_search.getText();
1023 PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1024 if (pdbEntry == null)
1026 pdbEntry = new PDBEntry();
1027 if (pdbIdStr.split(":").length > 1)
1029 pdbEntry.setId(pdbIdStr.split(":")[0]);
1030 pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1034 pdbEntry.setId(pdbIdStr);
1036 pdbEntry.setType(PDBEntry.Type.PDB);
1037 selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1040 PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1041 sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1043 { selectedSequence });
1045 else if (currentView == VIEWS_FROM_FILE)
1047 SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1048 .getCmb_assSeq().getSelectedItem()).getSequence();
1049 if (userSelectedSeq != null)
1051 selectedSequence = userSelectedSeq;
1053 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1054 .associatePdbWithSeq(selectedPdbFileName,
1055 DataSourceType.FILE, selectedSequence, true,
1058 sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1060 { selectedSequence });
1062 SwingUtilities.invokeLater(new Runnable()
1067 closeAction(preferredHeight);
1068 mainFrame.dispose();
1073 Thread runner = new Thread(viewStruc);
1075 if (waitUntilFinished)
1077 while (sViewer == null ? runner.isAlive()
1078 : (sViewer.sview == null ? true
1079 : !sViewer.sview.hasMapping()))
1084 } catch (InterruptedException ie)
1093 * Answers a structure viewer (new or existing) configured to superimpose
1094 * added structures or not according to the user's choice
1099 StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1101 Object sv = targetView.getSelectedItem();
1103 return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1107 * Adds PDB structures to a new or existing structure viewer
1110 * @param pdbEntriesToView
1115 private StructureViewer launchStructureViewer(
1116 StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1117 final AlignmentPanel alignPanel, SequenceI[] sequences)
1119 long progressId = sequences.hashCode();
1120 setProgressBar(MessageManager
1121 .getString("status.launching_3d_structure_viewer"), progressId);
1122 final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1123 boolean superimpose = chk_superpose.isSelected();
1124 theViewer.setSuperpose(superimpose);
1127 * remember user's choice of superimpose or not
1129 Cache.setProperty(AUTOSUPERIMPOSE,
1130 Boolean.valueOf(superimpose).toString());
1132 setProgressBar(null, progressId);
1133 if (SiftsSettings.isMapWithSifts())
1135 List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1137 // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1138 // real PDB ID. For moment, we can also safely do this if there is already
1139 // a known mapping between the PDBEntry and the sequence.
1140 for (SequenceI seq : sequences)
1142 PDBEntry pdbe = pdbEntriesToView[p++];
1143 if (pdbe != null && pdbe.getFile() != null)
1145 StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1146 if (smm != null && smm.length > 0)
1148 for (StructureMapping sm : smm)
1150 if (sm.getSequence() == seq)
1157 if (seq.getPrimaryDBRefs().isEmpty())
1159 seqsWithoutSourceDBRef.add(seq);
1163 if (!seqsWithoutSourceDBRef.isEmpty())
1165 int y = seqsWithoutSourceDBRef.size();
1166 setProgressBar(MessageManager.formatMessage(
1167 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1169 SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1170 .toArray(new SequenceI[y]);
1171 DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1172 dbRefFetcher.fetchDBRefs(true);
1174 setProgressBar("Fetch complete.", progressId); // todo i18n
1177 if (pdbEntriesToView.length > 1)
1180 MessageManager.getString(
1181 "status.fetching_3d_structures_for_selected_entries"),
1183 theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1187 setProgressBar(MessageManager.formatMessage(
1188 "status.fetching_3d_structures_for",
1189 pdbEntriesToView[0].getId()), progressId);
1190 theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1192 setProgressBar(null, progressId);
1193 // remember the last viewer we used...
1194 lastTargetedView = theViewer;
1199 * Populates the combo-box used in associating manually fetched structures to
1200 * a unique sequence when more than one sequence selection is made.
1203 protected void populateCmbAssociateSeqOptions(
1204 JComboBox<AssociateSeqOptions> cmb_assSeq,
1205 JLabel lbl_associateSeq)
1207 cmb_assSeq.removeAllItems();
1209 new AssociateSeqOptions("-Select Associated Seq-", null));
1210 lbl_associateSeq.setVisible(false);
1211 if (selectedSequences.length > 1)
1213 for (SequenceI seq : selectedSequences)
1215 cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1220 String seqName = selectedSequence.getDisplayId(false);
1221 seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1222 lbl_associateSeq.setText(seqName);
1223 lbl_associateSeq.setVisible(true);
1224 cmb_assSeq.setVisible(false);
1228 protected boolean isStructuresDiscovered()
1230 return discoveredStructuresSet != null
1231 && !discoveredStructuresSet.isEmpty();
1234 protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1236 // Doing a search for "1" or "1c" is valuable?
1237 // Those work but are enormously slow.
1240 protected void txt_search_ActionPerformed()
1242 String text = txt_search.getText().trim();
1243 if (text.length() >= PDB_ID_MIN)
1250 errorWarning.setLength(0);
1251 isValidPBDEntry = false;
1252 if (text.length() > 0)
1254 // TODO move this pdb id search into the PDB specific
1256 // for moment, it will work fine as is because it is self-contained
1257 String searchTerm = text.toLowerCase(Locale.ROOT);
1258 searchTerm = searchTerm.split(":")[0];
1259 // System.out.println(">>>>> search term : " + searchTerm);
1260 List<FTSDataColumnI> wantedFields = new ArrayList<>();
1261 FTSRestRequest pdbRequest = new FTSRestRequest();
1262 pdbRequest.setAllowEmptySeq(false);
1263 pdbRequest.setResponseSize(1);
1264 pdbRequest.setFieldToSearchBy("(pdb_id:");
1265 pdbRequest.setWantedFields(wantedFields);
1266 pdbRequest.setSearchTerm(searchTerm + ")");
1267 pdbRequest.setAssociatedSequence(selectedSequence);
1268 FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1269 wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1270 FTSRestResponse resultList;
1273 resultList = pdbRestClient.executeRequest(pdbRequest);
1274 } catch (Exception e)
1276 errorWarning.append(e.getMessage());
1280 validateSelections();
1282 if (resultList.getSearchSummary() != null
1283 && resultList.getSearchSummary().size() > 0)
1285 isValidPBDEntry = true;
1288 validateSelections();
1294 protected void tabRefresh()
1296 if (selectedSequences != null)
1298 Thread refreshThread = new Thread(new Runnable()
1303 fetchStructuresMetaData();
1304 // populateFilterComboBox(true, cachedPDBExists);
1307 ((FilterOption) cmb_filterOption.getSelectedItem())
1311 refreshThread.start();
1315 public class PDBEntryTableModel extends AbstractTableModel
1317 String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1320 private List<CachedPDB> pdbEntries;
1322 public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1324 this.pdbEntries = new ArrayList<>(pdbEntries);
1328 public String getColumnName(int columnIndex)
1330 return columns[columnIndex];
1334 public int getRowCount()
1336 return pdbEntries.size();
1340 public int getColumnCount()
1342 return columns.length;
1346 public boolean isCellEditable(int row, int column)
1352 public Object getValueAt(int rowIndex, int columnIndex)
1354 Object value = "??";
1355 CachedPDB entry = pdbEntries.get(rowIndex);
1356 switch (columnIndex)
1359 value = entry.getSequence();
1362 value = entry.getQualifiedId();
1365 value = entry.getPdbEntry().getChainCode() == null ? "_"
1366 : entry.getPdbEntry().getChainCode();
1369 value = entry.getPdbEntry().getType();
1372 value = entry.getPdbEntry().getFile();
1379 public Class<?> getColumnClass(int columnIndex)
1381 return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1384 public CachedPDB getPDBEntryAt(int row)
1386 return pdbEntries.get(row);
1391 private class CachedPDB
1393 private SequenceI sequence;
1395 private PDBEntry pdbEntry;
1397 public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1399 this.sequence = sequence;
1400 this.pdbEntry = pdbEntry;
1403 public String getQualifiedId()
1405 if (pdbEntry.hasProvider())
1407 return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1409 return pdbEntry.toString();
1412 public SequenceI getSequence()
1417 public PDBEntry getPdbEntry()
1424 private IProgressIndicator progressBar;
1427 public void setProgressBar(String message, long id)
1429 progressBar.setProgressBar(message, id);
1433 public void registerHandler(long id, IProgressIndicatorHandler handler)
1435 progressBar.registerHandler(id, handler);
1439 public boolean operationInProgress()
1441 return progressBar.operationInProgress();
1444 public JalviewStructureDisplayI getOpenedStructureViewer()
1446 return sViewer == null ? null : sViewer.sview;
1450 protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1452 data.setDocFieldPrefs(newPrefs);
1458 * @return true when all initialisation threads have finished and dialog is
1461 public boolean isDialogVisible()
1463 return mainFrame != null && data != null && cmb_filterOption != null
1464 && mainFrame.isVisible()
1465 && cmb_filterOption.getSelectedItem() != null;