JAL-3829 pushed the PDBFTSClient specific code to new ‘StructureChooserQuerySource...
[jalview.git] / src / jalview / gui / StructureChooser.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21
22 package jalview.gui;
23
24 import jalview.api.structures.JalviewStructureDisplayI;
25 import jalview.bin.Cache;
26 import jalview.bin.Jalview;
27 import jalview.datamodel.DBRefEntry;
28 import jalview.datamodel.DBRefSource;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.fts.api.FTSData;
32 import jalview.fts.api.FTSDataColumnI;
33 import jalview.fts.api.FTSRestClientI;
34 import jalview.fts.core.FTSRestRequest;
35 import jalview.fts.core.FTSRestResponse;
36 import jalview.fts.service.pdb.PDBFTSRestClient;
37 import jalview.io.DataSourceType;
38 import jalview.jbgui.GStructureChooser;
39 import jalview.jbgui.GStructureChooser.FilterOption;
40 import jalview.structure.StructureMapping;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.util.MessageManager;
43 import jalview.ws.DBRefFetcher;
44 import jalview.ws.sifts.SiftsSettings;
45
46 import java.awt.event.ItemEvent;
47 import java.util.ArrayList;
48 import java.util.Collection;
49 import java.util.HashSet;
50 import java.util.LinkedHashSet;
51 import java.util.List;
52 import java.util.Objects;
53 import java.util.Set;
54 import java.util.Vector;
55
56 import javax.swing.JCheckBox;
57 import javax.swing.JComboBox;
58 import javax.swing.JLabel;
59 import javax.swing.JTable;
60 import javax.swing.SwingUtilities;
61 import javax.swing.table.AbstractTableModel;
62
63 /**
64  * Provides the behaviors for the Structure chooser Panel
65  * 
66  * @author tcnofoegbu
67  *
68  */
69 @SuppressWarnings("serial")
70 public class StructureChooser extends GStructureChooser
71         implements IProgressIndicator
72 {
73   private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
74
75   private SequenceI selectedSequence;
76
77   private SequenceI[] selectedSequences;
78
79   private IProgressIndicator progressIndicator;
80
81   private Collection<FTSData> discoveredStructuresSet;
82
83   private StructureChooserQuerySource data = StructureChooserQuerySource.getPDBfts();
84
85   private String selectedPdbFileName;
86
87   private boolean isValidPBDEntry;
88
89   private boolean cachedPDBExists;
90
91   private static StructureViewer lastTargetedView = null;
92
93   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
94           AlignmentPanel ap)
95   {
96     this.ap = ap;
97     this.selectedSequence = selectedSeq;
98     this.selectedSequences = selectedSeqs;
99     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
100     init();
101   }
102
103   /**
104    * Initializes parameters used by the Structure Chooser Panel
105    */
106   protected void init()
107   {
108     if (!Jalview.isHeadlessMode())
109     {
110       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
111     }
112
113     chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
114
115     // ensure a filter option is in force for search
116     populateFilterComboBox(true, cachedPDBExists);
117     Thread discoverPDBStructuresThread = new Thread(new Runnable()
118     {
119       @Override
120       public void run()
121       {
122         long startTime = System.currentTimeMillis();
123         updateProgressIndicator(MessageManager
124                 .getString("status.loading_cached_pdb_entries"), startTime);
125         loadLocalCachedPDBEntries();
126         updateProgressIndicator(null, startTime);
127         updateProgressIndicator(MessageManager.getString(
128                 "status.searching_for_pdb_structures"), startTime);
129         fetchStructuresMetaData();
130         // revise filter options if no results were found
131         populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
132         discoverStructureViews();
133         updateProgressIndicator(null, startTime);
134         mainFrame.setVisible(true);
135         updateCurrentView();
136       }
137     });
138     discoverPDBStructuresThread.start();
139   }
140
141   /**
142    * Builds a drop-down choice list of existing structure viewers to which new
143    * structures may be added. If this list is empty then it, and the 'Add'
144    * button, are hidden.
145    */
146   private void discoverStructureViews()
147   {
148     if (Desktop.instance != null)
149     {
150       targetView.removeAllItems();
151       if (lastTargetedView != null && !lastTargetedView.isVisible())
152       {
153         lastTargetedView = null;
154       }
155       int linkedViewsAt = 0;
156       for (StructureViewerBase view : Desktop.instance
157               .getStructureViewers(null, null))
158       {
159         StructureViewer viewHandler = (lastTargetedView != null
160                 && lastTargetedView.sview == view) ? lastTargetedView
161                         : StructureViewer.reconfigure(view);
162
163         if (view.isLinkedWith(ap))
164         {
165           targetView.insertItemAt(viewHandler,
166                   linkedViewsAt++);
167         }
168         else
169         {
170           targetView.addItem(viewHandler);
171         }
172       }
173
174       /*
175        * show option to Add to viewer if at least 1 viewer found
176        */
177       targetView.setVisible(false);
178       if (targetView.getItemCount() > 0)
179       {
180         targetView.setVisible(true);
181         if (lastTargetedView != null)
182         {
183           targetView.setSelectedItem(lastTargetedView);
184         }
185         else
186         {
187           targetView.setSelectedIndex(0);
188         }
189       }
190       btn_add.setVisible(targetView.isVisible());
191     }
192   }
193
194   /**
195    * Updates the progress indicator with the specified message
196    * 
197    * @param message
198    *          displayed message for the operation
199    * @param id
200    *          unique handle for this indicator
201    */
202   protected void updateProgressIndicator(String message, long id)
203   {
204     if (progressIndicator != null)
205     {
206       progressIndicator.setProgressBar(message, id);
207     }
208   }
209
210   /**
211    * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
212    * selection group
213    */
214   void fetchStructuresMetaData()
215   {
216     long startTime = System.currentTimeMillis();
217     Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
218             .getStructureSummaryFields();
219
220     discoveredStructuresSet = new LinkedHashSet<>();
221     HashSet<String> errors = new HashSet<>();
222
223     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
224             .getSelectedItem());
225     
226     for (SequenceI seq : selectedSequences)
227     {
228
229       FTSRestResponse resultList;
230       try
231       {
232         resultList = data.fetchStructuresMetaData(seq, wantedFields, selectedFilterOpt, !chk_invertFilter.isSelected());
233       } catch (Exception e)
234       {
235         e.printStackTrace();
236         errors.add(e.getMessage());
237         continue;
238       }
239       if (resultList.getSearchSummary() != null
240               && !resultList.getSearchSummary().isEmpty())
241       {
242         discoveredStructuresSet.addAll(resultList.getSearchSummary());
243       }
244     }
245
246     int noOfStructuresFound = 0;
247     String totalTime = (System.currentTimeMillis() - startTime)
248             + " milli secs";
249     if (discoveredStructuresSet != null
250             && !discoveredStructuresSet.isEmpty())
251     {
252       getResultTable().setModel(data.getTableModel(discoveredStructuresSet));
253       noOfStructuresFound = discoveredStructuresSet.size();
254       mainFrame.setTitle(MessageManager.formatMessage(
255               "label.structure_chooser_no_of_structures",
256               noOfStructuresFound, totalTime));
257     }
258     else
259     {
260       mainFrame.setTitle(MessageManager
261               .getString("label.structure_chooser_manual_association"));
262       if (errors.size() > 0)
263       {
264         StringBuilder errorMsg = new StringBuilder();
265         for (String error : errors)
266         {
267           errorMsg.append(error).append("\n");
268         }
269         JvOptionPane.showMessageDialog(this, errorMsg.toString(),
270                 MessageManager.getString("label.pdb_web-service_error"),
271                 JvOptionPane.ERROR_MESSAGE);
272       }
273     }
274   }
275
276   protected void loadLocalCachedPDBEntries()
277   {
278     ArrayList<CachedPDB> entries = new ArrayList<>();
279     for (SequenceI seq : selectedSequences)
280     {
281       if (seq.getDatasetSequence() != null
282               && seq.getDatasetSequence().getAllPDBEntries() != null)
283       {
284         for (PDBEntry pdbEntry : seq.getDatasetSequence()
285                 .getAllPDBEntries())
286         {
287           if (pdbEntry.getFile() != null)
288           {
289             entries.add(new CachedPDB(seq, pdbEntry));
290           }
291         }
292       }
293     }
294     cachedPDBExists = !entries.isEmpty();
295     PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
296     tbl_local_pdb.setModel(tableModelx);
297   }
298
299   /**
300    * Filters a given list of discovered structures based on supplied argument
301    * 
302    * @param fieldToFilterBy
303    *          the field to filter by
304    */
305   void filterResultSet(final String fieldToFilterBy)
306   {
307     Thread filterThread = new Thread(new Runnable()
308     {
309       @Override
310       public void run()
311       {
312         long startTime = System.currentTimeMillis();
313         lbl_loading.setVisible(true);
314         Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
315                 .getStructureSummaryFields();
316         Collection<FTSData> filteredResponse = new HashSet<>();
317         HashSet<String> errors = new HashSet<>();
318
319         for (SequenceI seq : selectedSequences)
320         {
321           
322           FTSRestResponse resultList;
323           try
324           {
325             resultList = data.selectFirstRankedQuery(seq, wantedFields, fieldToFilterBy,
326                     !chk_invertFilter.isSelected());
327
328           } catch (Exception e)
329           {
330             e.printStackTrace();
331             errors.add(e.getMessage());
332             continue;
333           }
334           if (resultList.getSearchSummary() != null
335                   && !resultList.getSearchSummary().isEmpty())
336           {
337             filteredResponse.addAll(resultList.getSearchSummary());
338           }
339         }
340
341         String totalTime = (System.currentTimeMillis() - startTime)
342                 + " milli secs";
343         if (!filteredResponse.isEmpty())
344         {
345           final int filterResponseCount = filteredResponse.size();
346           Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
347           reorderedStructuresSet.addAll(filteredResponse);
348           reorderedStructuresSet.addAll(discoveredStructuresSet);
349           getResultTable().setModel(data.getTableModel(reorderedStructuresSet));
350
351           FTSRestResponse.configureTableColumn(getResultTable(),
352                   wantedFields, tempUserPrefs);
353           getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
354           getResultTable().getColumn("Ref Sequence").setMinWidth(100);
355           getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
356           // Update table selection model here
357           getResultTable().addRowSelectionInterval(0,
358                   filterResponseCount - 1);
359           mainFrame.setTitle(MessageManager.formatMessage(
360                   "label.structure_chooser_filter_time", totalTime));
361         }
362         else
363         {
364           mainFrame.setTitle(MessageManager.formatMessage(
365                   "label.structure_chooser_filter_time", totalTime));
366           if (errors.size() > 0)
367           {
368             StringBuilder errorMsg = new StringBuilder();
369             for (String error : errors)
370             {
371               errorMsg.append(error).append("\n");
372             }
373             JvOptionPane.showMessageDialog(null, errorMsg.toString(),
374                     MessageManager.getString("label.pdb_web-service_error"),
375                     JvOptionPane.ERROR_MESSAGE);
376           }
377         }
378
379         lbl_loading.setVisible(false);
380
381         validateSelections();
382       }
383     });
384     filterThread.start();
385   }
386
387   /**
388    * Handles action event for btn_pdbFromFile
389    */
390   @Override
391   protected void pdbFromFile_actionPerformed()
392   {
393     // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and StructureChooser
394     // works
395     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
396             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
397     chooser.setFileView(new jalview.io.JalviewFileView());
398     chooser.setDialogTitle(
399             MessageManager.formatMessage("label.select_pdb_file_for",
400                     selectedSequence.getDisplayId(false)));
401     chooser.setToolTipText(MessageManager.formatMessage(
402             "label.load_pdb_file_associate_with_sequence",
403             selectedSequence.getDisplayId(false)));
404
405     int value = chooser.showOpenDialog(null);
406     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
407     {
408       selectedPdbFileName = chooser.getSelectedFile().getPath();
409       jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
410       validateSelections();
411     }
412   }
413
414   /**
415    * Populates the filter combo-box options dynamically depending on discovered
416    * structures
417    */
418   protected void populateFilterComboBox(boolean haveData,
419           boolean cachedPDBExist)
420   {
421     /*
422      * temporarily suspend the change listener behaviour
423      */
424     cmb_filterOption.removeItemListener(this);
425
426     cmb_filterOption.removeAllItems();
427     if (haveData)
428     {
429       cmb_filterOption.addItem(new FilterOption(
430               MessageManager.getString("label.best_quality"),
431               "overall_quality", VIEWS_FILTER, false));
432       cmb_filterOption.addItem(new FilterOption(
433               MessageManager.getString("label.best_resolution"),
434               "resolution", VIEWS_FILTER, false));
435       cmb_filterOption.addItem(new FilterOption(
436               MessageManager.getString("label.most_protein_chain"),
437               "number_of_protein_chains", VIEWS_FILTER, false));
438       cmb_filterOption.addItem(new FilterOption(
439               MessageManager.getString("label.most_bound_molecules"),
440               "number_of_bound_molecules", VIEWS_FILTER, false));
441       cmb_filterOption.addItem(new FilterOption(
442               MessageManager.getString("label.most_polymer_residues"),
443               "number_of_polymer_residues", VIEWS_FILTER, true));
444     }
445     cmb_filterOption.addItem(
446             new FilterOption(MessageManager.getString("label.enter_pdb_id"),
447                     "-", VIEWS_ENTER_ID, false));
448     cmb_filterOption.addItem(
449             new FilterOption(MessageManager.getString("label.from_file"),
450                     "-", VIEWS_FROM_FILE, false));
451
452     if (cachedPDBExist)
453     {
454       FilterOption cachedOption = new FilterOption(
455               MessageManager.getString("label.cached_structures"),
456               "-", VIEWS_LOCAL_PDB, false);
457       cmb_filterOption.addItem(cachedOption);
458       cmb_filterOption.setSelectedItem(cachedOption);
459     }
460
461     cmb_filterOption.addItemListener(this);
462   }
463
464   /**
465    * Updates the displayed view based on the selected filter option
466    */
467   protected void updateCurrentView()
468   {
469     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
470             .getSelectedItem());
471     layout_switchableViews.show(pnl_switchableViews,
472             selectedFilterOpt.getView());
473     String filterTitle = mainFrame.getTitle();
474     mainFrame.setTitle(frameTitle);
475     chk_invertFilter.setVisible(false);
476     if (selectedFilterOpt.getView() == VIEWS_FILTER)
477     {
478       mainFrame.setTitle(filterTitle);
479       chk_invertFilter.setVisible(true);
480       filterResultSet(selectedFilterOpt.getValue());
481     }
482     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
483             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
484     {
485       mainFrame.setTitle(MessageManager
486               .getString("label.structure_chooser_manual_association"));
487       idInputAssSeqPanel.loadCmbAssSeq();
488       fileChooserAssSeqPanel.loadCmbAssSeq();
489     }
490     validateSelections();
491   }
492
493   /**
494    * Validates user selection and enables the 'Add' and 'New View' buttons if
495    * all parameters are correct (the Add button will only be visible if there is
496    * at least one existing structure viewer open). This basically means at least
497    * one structure selected and no error messages.
498    * <p>
499    * The 'Superpose Structures' option is enabled if either more than one
500    * structure is selected, or the 'Add' to existing view option is enabled, and
501    * disabled if the only option is to open a new view of a single structure.
502    */
503   @Override
504   protected void validateSelections()
505   {
506     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
507             .getSelectedItem());
508     btn_add.setEnabled(false);
509     String currentView = selectedFilterOpt.getView();
510     int selectedCount = 0;
511     if (currentView == VIEWS_FILTER)
512     {
513       selectedCount = getResultTable().getSelectedRows().length;
514       if (selectedCount > 0)
515       {
516         btn_add.setEnabled(true);
517       }
518     }
519     else if (currentView == VIEWS_LOCAL_PDB)
520     {
521       selectedCount = tbl_local_pdb.getSelectedRows().length;
522       if (selectedCount > 0)
523       {
524         btn_add.setEnabled(true);
525       }
526     }
527     else if (currentView == VIEWS_ENTER_ID)
528     {
529       validateAssociationEnterPdb();
530     }
531     else if (currentView == VIEWS_FROM_FILE)
532     {
533       validateAssociationFromFile();
534     }
535
536     btn_newView.setEnabled(btn_add.isEnabled());
537
538     /*
539      * enable 'Superpose' option if more than one structure is selected,
540      * or there are view(s) available to add structure(s) to
541      */
542     chk_superpose
543             .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
544   }
545
546   /**
547    * Validates inputs from the Manual PDB entry panel
548    */
549   protected void validateAssociationEnterPdb()
550   {
551     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
552             .getCmb_assSeq().getSelectedItem();
553     lbl_pdbManualFetchStatus.setIcon(errorImage);
554     lbl_pdbManualFetchStatus.setToolTipText("");
555     if (txt_search.getText().length() > 0)
556     {
557       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
558               MessageManager.formatMessage("info.no_pdb_entry_found_for",
559                       txt_search.getText())));
560     }
561
562     if (errorWarning.length() > 0)
563     {
564       lbl_pdbManualFetchStatus.setIcon(warningImage);
565       lbl_pdbManualFetchStatus.setToolTipText(
566               JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
567     }
568
569     if (selectedSequences.length == 1 || !assSeqOpt.getName()
570             .equalsIgnoreCase("-Select Associated Seq-"))
571     {
572       txt_search.setEnabled(true);
573       if (isValidPBDEntry)
574       {
575         btn_add.setEnabled(true);
576         lbl_pdbManualFetchStatus.setToolTipText("");
577         lbl_pdbManualFetchStatus.setIcon(goodImage);
578       }
579     }
580     else
581     {
582       txt_search.setEnabled(false);
583       lbl_pdbManualFetchStatus.setIcon(errorImage);
584     }
585   }
586
587   /**
588    * Validates inputs for the manual PDB file selection options
589    */
590   protected void validateAssociationFromFile()
591   {
592     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
593             .getCmb_assSeq().getSelectedItem();
594     lbl_fromFileStatus.setIcon(errorImage);
595     if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
596             .getName().equalsIgnoreCase("-Select Associated Seq-")))
597     {
598       btn_pdbFromFile.setEnabled(true);
599       if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
600       {
601         btn_add.setEnabled(true);
602         lbl_fromFileStatus.setIcon(goodImage);
603       }
604     }
605     else
606     {
607       btn_pdbFromFile.setEnabled(false);
608       lbl_fromFileStatus.setIcon(errorImage);
609     }
610   }
611
612   @Override
613   protected void cmbAssSeqStateChanged()
614   {
615     validateSelections();
616   }
617
618   /**
619    * Handles the state change event for the 'filter' combo-box and 'invert'
620    * check-box
621    */
622   @Override
623   protected void stateChanged(ItemEvent e)
624   {
625     if (e.getSource() instanceof JCheckBox)
626     {
627       updateCurrentView();
628     }
629     else
630     {
631       if (e.getStateChange() == ItemEvent.SELECTED)
632       {
633         updateCurrentView();
634       }
635     }
636
637   }
638
639   /**
640    * select structures for viewing by their PDB IDs
641    * 
642    * @param pdbids
643    * @return true if structures were found and marked as selected
644    */
645   public boolean selectStructure(String... pdbids)
646   {
647     boolean found = false;
648
649     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
650             .getSelectedItem());
651     String currentView = selectedFilterOpt.getView();
652     JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
653             : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
654
655     if (restable == null)
656     {
657       // can't select (enter PDB ID, or load file - need to also select which
658       // sequence to associate with)
659       return false;
660     }
661
662     int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
663     for (int r = 0; r < restable.getRowCount(); r++)
664     {
665       for (int p = 0; p < pdbids.length; p++)
666       {
667         if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
668                 .equalsIgnoreCase(pdbids[p]))
669         {
670           restable.setRowSelectionInterval(r, r);
671           found = true;
672         }
673       }
674     }
675     return found;
676   }
677   
678   /**
679    * Handles the 'New View' action
680    */
681   @Override
682   protected void newView_ActionPerformed()
683   {
684     targetView.setSelectedItem(null);
685     showStructures(false);
686   }
687
688   /**
689    * Handles the 'Add to existing viewer' action
690    */
691   @Override
692   protected void add_ActionPerformed()
693   {
694     showStructures(false);
695   }
696
697   /**
698    * structure viewer opened by this dialog, or null
699    */
700   private StructureViewer sViewer = null;
701
702   public void showStructures(boolean waitUntilFinished)
703   {
704
705     final StructureSelectionManager ssm = ap.getStructureSelectionManager();
706
707     final int preferredHeight = pnl_filter.getHeight();
708
709     Runnable viewStruc = new Runnable()
710     {
711       @Override
712       public void run()
713       {
714         FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
715                 .getSelectedItem());
716         String currentView = selectedFilterOpt.getView();
717         JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
718                 : tbl_local_pdb;
719
720         if (currentView == VIEWS_FILTER)
721         {
722           int pdbIdColIndex = restable.getColumn("PDB Id")
723                   .getModelIndex();
724           int refSeqColIndex = restable.getColumn("Ref Sequence")
725                   .getModelIndex();
726           int[] selectedRows = restable.getSelectedRows();
727           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
728           int count = 0;
729           List<SequenceI> selectedSeqsToView = new ArrayList<>();
730           for (int row : selectedRows)
731           {
732             String pdbIdStr = restable
733                     .getValueAt(row, pdbIdColIndex).toString();
734             SequenceI selectedSeq = (SequenceI) restable
735                     .getValueAt(row, refSeqColIndex);
736             selectedSeqsToView.add(selectedSeq);
737             PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
738             if (pdbEntry == null)
739             {
740               pdbEntry = getFindEntry(pdbIdStr,
741                       selectedSeq.getAllPDBEntries());
742             }
743
744             if (pdbEntry == null)
745             {
746               pdbEntry = new PDBEntry();
747               pdbEntry.setId(pdbIdStr);
748               pdbEntry.setType(PDBEntry.Type.PDB);
749               selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
750             }
751             pdbEntriesToView[count++] = pdbEntry;
752           }
753           SequenceI[] selectedSeqs = selectedSeqsToView
754                   .toArray(new SequenceI[selectedSeqsToView.size()]);
755           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
756                   selectedSeqs);
757         }
758         else if (currentView == VIEWS_LOCAL_PDB)
759         {
760           int[] selectedRows = tbl_local_pdb.getSelectedRows();
761           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
762           int count = 0;
763           int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
764                   .getModelIndex();
765           int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
766                   .getModelIndex();
767           List<SequenceI> selectedSeqsToView = new ArrayList<>();
768           for (int row : selectedRows)
769           {
770             PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
771                     pdbIdColIndex);
772             pdbEntriesToView[count++] = pdbEntry;
773             SequenceI selectedSeq = (SequenceI) tbl_local_pdb
774                     .getValueAt(row, refSeqColIndex);
775             selectedSeqsToView.add(selectedSeq);
776           }
777           SequenceI[] selectedSeqs = selectedSeqsToView
778                   .toArray(new SequenceI[selectedSeqsToView.size()]);
779           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
780                   selectedSeqs);
781         }
782         else if (currentView == VIEWS_ENTER_ID)
783         {
784           SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
785                   .getCmb_assSeq().getSelectedItem()).getSequence();
786           if (userSelectedSeq != null)
787           {
788             selectedSequence = userSelectedSeq;
789           }
790           String pdbIdStr = txt_search.getText();
791           PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
792           if (pdbEntry == null)
793           {
794             pdbEntry = new PDBEntry();
795             if (pdbIdStr.split(":").length > 1)
796             {
797               pdbEntry.setId(pdbIdStr.split(":")[0]);
798               pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
799             }
800             else
801             {
802               pdbEntry.setId(pdbIdStr);
803             }
804             pdbEntry.setType(PDBEntry.Type.PDB);
805             selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
806           }
807
808           PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
809           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
810                   new SequenceI[]
811                   { selectedSequence });
812         }
813         else if (currentView == VIEWS_FROM_FILE)
814         {
815           SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
816                   .getCmb_assSeq().getSelectedItem()).getSequence();
817           if (userSelectedSeq != null)
818           {
819             selectedSequence = userSelectedSeq;
820           }
821           PDBEntry fileEntry = new AssociatePdbFileWithSeq()
822                   .associatePdbWithSeq(selectedPdbFileName,
823                           DataSourceType.FILE, selectedSequence, true,
824                           Desktop.instance);
825
826           sViewer = launchStructureViewer(
827                   ssm, new PDBEntry[]
828                   { fileEntry }, ap,
829                   new SequenceI[]
830                   { selectedSequence });
831         }
832         SwingUtilities.invokeLater(new Runnable()
833         {
834           @Override
835           public void run()
836           {
837             closeAction(preferredHeight);
838             mainFrame.dispose();
839           }
840         });
841       }
842     };
843     Thread runner = new Thread(viewStruc);
844     runner.start();
845     if (waitUntilFinished)
846     {
847       while (sViewer == null ? runner.isAlive()
848               : (sViewer.sview == null ? true
849                       : !sViewer.sview.hasMapping()))
850       {
851         try
852         {
853           Thread.sleep(300);
854         } catch (InterruptedException ie)
855         {
856
857         }
858       }
859     }
860   }
861
862   private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
863   {
864     Objects.requireNonNull(id);
865     Objects.requireNonNull(pdbEntries);
866     PDBEntry foundEntry = null;
867     for (PDBEntry entry : pdbEntries)
868     {
869       if (entry.getId().equalsIgnoreCase(id))
870       {
871         return entry;
872       }
873     }
874     return foundEntry;
875   }
876
877   /**
878    * Answers a structure viewer (new or existing) configured to superimpose
879    * added structures or not according to the user's choice
880    * 
881    * @param ssm
882    * @return
883    */
884   StructureViewer getTargetedStructureViewer(
885           StructureSelectionManager ssm)
886   {
887     Object sv = targetView.getSelectedItem();
888
889     return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
890   }
891
892   /**
893    * Adds PDB structures to a new or existing structure viewer
894    * 
895    * @param ssm
896    * @param pdbEntriesToView
897    * @param alignPanel
898    * @param sequences
899    * @return
900    */
901   private StructureViewer launchStructureViewer(
902           StructureSelectionManager ssm,
903           final PDBEntry[] pdbEntriesToView,
904           final AlignmentPanel alignPanel, SequenceI[] sequences)
905   {
906     long progressId = sequences.hashCode();
907     setProgressBar(MessageManager
908             .getString("status.launching_3d_structure_viewer"), progressId);
909     final StructureViewer theViewer = getTargetedStructureViewer(ssm);
910     boolean superimpose = chk_superpose.isSelected();
911     theViewer.setSuperpose(superimpose);
912
913     /*
914      * remember user's choice of superimpose or not
915      */
916     Cache.setProperty(AUTOSUPERIMPOSE,
917             Boolean.valueOf(superimpose).toString());
918
919     setProgressBar(null, progressId);
920     if (SiftsSettings.isMapWithSifts())
921     {
922       List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
923       int p = 0;
924       // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
925       // real PDB ID. For moment, we can also safely do this if there is already
926       // a known mapping between the PDBEntry and the sequence.
927       for (SequenceI seq : sequences)
928       {
929         PDBEntry pdbe = pdbEntriesToView[p++];
930         if (pdbe != null && pdbe.getFile() != null)
931         {
932           StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
933           if (smm != null && smm.length > 0)
934           {
935             for (StructureMapping sm : smm)
936             {
937               if (sm.getSequence() == seq)
938               {
939                 continue;
940               }
941             }
942           }
943         }
944         if (seq.getPrimaryDBRefs().isEmpty())
945         {
946           seqsWithoutSourceDBRef.add(seq);
947           continue;
948         }
949       }
950       if (!seqsWithoutSourceDBRef.isEmpty())
951       {
952         int y = seqsWithoutSourceDBRef.size();
953         setProgressBar(MessageManager.formatMessage(
954                 "status.fetching_dbrefs_for_sequences_without_valid_refs",
955                 y), progressId);
956         SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
957                 .toArray(new SequenceI[y]);
958         DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
959         dbRefFetcher.fetchDBRefs(true);
960
961         setProgressBar("Fetch complete.", progressId); // todo i18n
962       }
963     }
964     if (pdbEntriesToView.length > 1)
965     {
966       setProgressBar(MessageManager.getString(
967               "status.fetching_3d_structures_for_selected_entries"),
968               progressId);
969       theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
970     }
971     else
972     {
973       setProgressBar(MessageManager.formatMessage(
974               "status.fetching_3d_structures_for",
975               pdbEntriesToView[0].getId()),progressId);
976       theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
977     }
978     setProgressBar(null, progressId);
979     // remember the last viewer we used...
980     lastTargetedView = theViewer;
981     return theViewer;
982   }
983
984   /**
985    * Populates the combo-box used in associating manually fetched structures to
986    * a unique sequence when more than one sequence selection is made.
987    */
988   @Override
989   protected void populateCmbAssociateSeqOptions(
990           JComboBox<AssociateSeqOptions> cmb_assSeq,
991           JLabel lbl_associateSeq)
992   {
993     cmb_assSeq.removeAllItems();
994     cmb_assSeq.addItem(
995             new AssociateSeqOptions("-Select Associated Seq-", null));
996     lbl_associateSeq.setVisible(false);
997     if (selectedSequences.length > 1)
998     {
999       for (SequenceI seq : selectedSequences)
1000       {
1001         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1002       }
1003     }
1004     else
1005     {
1006       String seqName = selectedSequence.getDisplayId(false);
1007       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1008       lbl_associateSeq.setText(seqName);
1009       lbl_associateSeq.setVisible(true);
1010       cmb_assSeq.setVisible(false);
1011     }
1012   }
1013
1014   protected boolean isStructuresDiscovered()
1015   {
1016     return discoveredStructuresSet != null
1017             && !discoveredStructuresSet.isEmpty();
1018   }
1019
1020   protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes this. 
1021   // Doing a search for "1" or "1c" is valuable?
1022   // Those work but are enormously slow.
1023
1024   @Override
1025   protected void txt_search_ActionPerformed()
1026   {
1027     String text = txt_search.getText().trim();
1028         if (text.length() >= PDB_ID_MIN) 
1029     new Thread()
1030     {
1031
1032         @Override
1033       public void run()
1034       {
1035         errorWarning.setLength(0);
1036         isValidPBDEntry = false;
1037         if (text.length() > 0)
1038         {
1039           // TODO move this pdb id search into the PDB specific FTSSearchEngine 
1040           // for moment, it will work fine as is because it is self-contained
1041           String searchTerm = text.toLowerCase();
1042           searchTerm = searchTerm.split(":")[0];
1043           // System.out.println(">>>>> search term : " + searchTerm);
1044           List<FTSDataColumnI> wantedFields = new ArrayList<>();
1045           FTSRestRequest pdbRequest = new FTSRestRequest();
1046           pdbRequest.setAllowEmptySeq(false);
1047           pdbRequest.setResponseSize(1);
1048           pdbRequest.setFieldToSearchBy("(pdb_id:");
1049           pdbRequest.setWantedFields(wantedFields);
1050           pdbRequest.setSearchTerm(searchTerm + ")");
1051           pdbRequest.setAssociatedSequence(selectedSequence);
1052           FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1053           wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1054           FTSRestResponse resultList;
1055           try
1056           {
1057             resultList = pdbRestClient.executeRequest(pdbRequest);
1058           } catch (Exception e)
1059           {
1060             errorWarning.append(e.getMessage());
1061             return;
1062           } finally
1063           {
1064             validateSelections();
1065           }
1066           if (resultList.getSearchSummary() != null
1067                   && resultList.getSearchSummary().size() > 0)
1068           {
1069             isValidPBDEntry = true;
1070           }
1071         }
1072         validateSelections();
1073       }
1074     }.start();
1075   }
1076
1077   @Override
1078   protected void tabRefresh()
1079   {
1080     if (selectedSequences != null)
1081     {
1082       Thread refreshThread = new Thread(new Runnable()
1083       {
1084         @Override
1085         public void run()
1086         {
1087           fetchStructuresMetaData();
1088           filterResultSet(
1089                   ((FilterOption) cmb_filterOption.getSelectedItem())
1090                           .getValue());
1091         }
1092       });
1093       refreshThread.start();
1094     }
1095   }
1096
1097   public class PDBEntryTableModel extends AbstractTableModel
1098   {
1099     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1100         "File" };
1101
1102     private List<CachedPDB> pdbEntries;
1103
1104     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1105     {
1106       this.pdbEntries = new ArrayList<>(pdbEntries);
1107     }
1108
1109     @Override
1110     public String getColumnName(int columnIndex)
1111     {
1112       return columns[columnIndex];
1113     }
1114
1115     @Override
1116     public int getRowCount()
1117     {
1118       return pdbEntries.size();
1119     }
1120
1121     @Override
1122     public int getColumnCount()
1123     {
1124       return columns.length;
1125     }
1126
1127     @Override
1128     public boolean isCellEditable(int row, int column)
1129     {
1130       return false;
1131     }
1132
1133     @Override
1134     public Object getValueAt(int rowIndex, int columnIndex)
1135     {
1136       Object value = "??";
1137       CachedPDB entry = pdbEntries.get(rowIndex);
1138       switch (columnIndex)
1139       {
1140       case 0:
1141         value = entry.getSequence();
1142         break;
1143       case 1:
1144         value = entry.getPdbEntry();
1145         break;
1146       case 2:
1147         value = entry.getPdbEntry().getChainCode() == null ? "_"
1148                 : entry.getPdbEntry().getChainCode();
1149         break;
1150       case 3:
1151         value = entry.getPdbEntry().getType();
1152         break;
1153       case 4:
1154         value = entry.getPdbEntry().getFile();
1155         break;
1156       }
1157       return value;
1158     }
1159
1160     @Override
1161     public Class<?> getColumnClass(int columnIndex)
1162     {
1163       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1164     }
1165
1166     public CachedPDB getPDBEntryAt(int row)
1167     {
1168       return pdbEntries.get(row);
1169     }
1170
1171   }
1172
1173   private class CachedPDB
1174   {
1175     private SequenceI sequence;
1176
1177     private PDBEntry pdbEntry;
1178
1179     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1180     {
1181       this.sequence = sequence;
1182       this.pdbEntry = pdbEntry;
1183     }
1184
1185     public SequenceI getSequence()
1186     {
1187       return sequence;
1188     }
1189
1190     public PDBEntry getPdbEntry()
1191     {
1192       return pdbEntry;
1193     }
1194
1195   }
1196
1197   private IProgressIndicator progressBar;
1198
1199   @Override
1200   public void setProgressBar(String message, long id)
1201   {
1202     progressBar.setProgressBar(message, id);
1203   }
1204
1205   @Override
1206   public void registerHandler(long id, IProgressIndicatorHandler handler)
1207   {
1208     progressBar.registerHandler(id, handler);
1209   }
1210
1211   @Override
1212   public boolean operationInProgress()
1213   {
1214     return progressBar.operationInProgress();
1215   }
1216
1217   public JalviewStructureDisplayI getOpenedStructureViewer()
1218   {
1219     return sViewer == null ? null : sViewer.sview;
1220   }
1221 }