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