JAL-3829 comments on the 3D structure chooser’s initialisation process
[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, 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));
470     cmb_filterOption.addItem(
471             new FilterOption(MessageManager.getString("label.from_file"),
472                     "-", VIEWS_FROM_FILE, false));
473
474     if (cachedPDBExist)
475     {
476       FilterOption cachedOption = new FilterOption(
477               MessageManager.getString("label.cached_structures"), "-",
478               VIEWS_LOCAL_PDB, false);
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       filterResultSet(selectedFilterOpt.getValue());
503     }
504     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
505             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
506     {
507       mainFrame.setTitle(MessageManager
508               .getString("label.structure_chooser_manual_association"));
509       idInputAssSeqPanel.loadCmbAssSeq();
510       fileChooserAssSeqPanel.loadCmbAssSeq();
511     }
512     validateSelections();
513   }
514
515   /**
516    * Validates user selection and enables the 'Add' and 'New View' buttons if
517    * all parameters are correct (the Add button will only be visible if there is
518    * at least one existing structure viewer open). This basically means at least
519    * one structure selected and no error messages.
520    * <p>
521    * The 'Superpose Structures' option is enabled if either more than one
522    * structure is selected, or the 'Add' to existing view option is enabled, and
523    * disabled if the only option is to open a new view of a single structure.
524    */
525   @Override
526   protected void validateSelections()
527   {
528     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
529             .getSelectedItem());
530     btn_add.setEnabled(false);
531     String currentView = selectedFilterOpt.getView();
532     int selectedCount = 0;
533     if (currentView == VIEWS_FILTER)
534     {
535       selectedCount = getResultTable().getSelectedRows().length;
536       if (selectedCount > 0)
537       {
538         btn_add.setEnabled(true);
539       }
540     }
541     else if (currentView == VIEWS_LOCAL_PDB)
542     {
543       selectedCount = tbl_local_pdb.getSelectedRows().length;
544       if (selectedCount > 0)
545       {
546         btn_add.setEnabled(true);
547       }
548     }
549     else if (currentView == VIEWS_ENTER_ID)
550     {
551       validateAssociationEnterPdb();
552     }
553     else if (currentView == VIEWS_FROM_FILE)
554     {
555       validateAssociationFromFile();
556     }
557
558     btn_newView.setEnabled(btn_add.isEnabled());
559
560     /*
561      * enable 'Superpose' option if more than one structure is selected,
562      * or there are view(s) available to add structure(s) to
563      */
564     chk_superpose
565             .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
566   }
567
568   /**
569    * Validates inputs from the Manual PDB entry panel
570    */
571   protected void validateAssociationEnterPdb()
572   {
573     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
574             .getCmb_assSeq().getSelectedItem();
575     lbl_pdbManualFetchStatus.setIcon(errorImage);
576     lbl_pdbManualFetchStatus.setToolTipText("");
577     if (txt_search.getText().length() > 0)
578     {
579       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
580               MessageManager.formatMessage("info.no_pdb_entry_found_for",
581                       txt_search.getText())));
582     }
583
584     if (errorWarning.length() > 0)
585     {
586       lbl_pdbManualFetchStatus.setIcon(warningImage);
587       lbl_pdbManualFetchStatus.setToolTipText(
588               JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
589     }
590
591     if (selectedSequences.length == 1 || !assSeqOpt.getName()
592             .equalsIgnoreCase("-Select Associated Seq-"))
593     {
594       txt_search.setEnabled(true);
595       if (isValidPBDEntry)
596       {
597         btn_add.setEnabled(true);
598         lbl_pdbManualFetchStatus.setToolTipText("");
599         lbl_pdbManualFetchStatus.setIcon(goodImage);
600       }
601     }
602     else
603     {
604       txt_search.setEnabled(false);
605       lbl_pdbManualFetchStatus.setIcon(errorImage);
606     }
607   }
608
609   /**
610    * Validates inputs for the manual PDB file selection options
611    */
612   protected void validateAssociationFromFile()
613   {
614     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
615             .getCmb_assSeq().getSelectedItem();
616     lbl_fromFileStatus.setIcon(errorImage);
617     if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
618             .getName().equalsIgnoreCase("-Select Associated Seq-")))
619     {
620       btn_pdbFromFile.setEnabled(true);
621       if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
622       {
623         btn_add.setEnabled(true);
624         lbl_fromFileStatus.setIcon(goodImage);
625       }
626     }
627     else
628     {
629       btn_pdbFromFile.setEnabled(false);
630       lbl_fromFileStatus.setIcon(errorImage);
631     }
632   }
633
634   @Override
635   protected void cmbAssSeqStateChanged()
636   {
637     validateSelections();
638   }
639
640   /**
641    * Handles the state change event for the 'filter' combo-box and 'invert'
642    * check-box
643    */
644   @Override
645   protected void stateChanged(ItemEvent e)
646   {
647     if (e.getSource() instanceof JCheckBox)
648     {
649       updateCurrentView();
650     }
651     else
652     {
653       if (e.getStateChange() == ItemEvent.SELECTED)
654       {
655         updateCurrentView();
656       }
657     }
658
659   }
660
661   /**
662    * select structures for viewing by their PDB IDs
663    * 
664    * @param pdbids
665    * @return true if structures were found and marked as selected
666    */
667   public boolean selectStructure(String... pdbids)
668   {
669     boolean found = false;
670
671     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
672             .getSelectedItem());
673     String currentView = selectedFilterOpt.getView();
674     JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
675             : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
676
677     if (restable == null)
678     {
679       // can't select (enter PDB ID, or load file - need to also select which
680       // sequence to associate with)
681       return false;
682     }
683
684     int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
685     for (int r = 0; r < restable.getRowCount(); r++)
686     {
687       for (int p = 0; p < pdbids.length; p++)
688       {
689         if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
690                 .equalsIgnoreCase(pdbids[p]))
691         {
692           restable.setRowSelectionInterval(r, r);
693           found = true;
694         }
695       }
696     }
697     return found;
698   }
699
700   /**
701    * Handles the 'New View' action
702    */
703   @Override
704   protected void newView_ActionPerformed()
705   {
706     targetView.setSelectedItem(null);
707     showStructures(false);
708   }
709
710   /**
711    * Handles the 'Add to existing viewer' action
712    */
713   @Override
714   protected void add_ActionPerformed()
715   {
716     showStructures(false);
717   }
718
719   /**
720    * structure viewer opened by this dialog, or null
721    */
722   private StructureViewer sViewer = null;
723
724   public void showStructures(boolean waitUntilFinished)
725   {
726
727     final StructureSelectionManager ssm = ap.getStructureSelectionManager();
728
729     final int preferredHeight = pnl_filter.getHeight();
730
731     Runnable viewStruc = new Runnable()
732     {
733       @Override
734       public void run()
735       {
736         FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
737                 .getSelectedItem());
738         String currentView = selectedFilterOpt.getView();
739         JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
740                 : tbl_local_pdb;
741
742         if (currentView == VIEWS_FILTER)
743         {
744           int[] selectedRows = restable.getSelectedRows();
745           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
746           List<SequenceI> selectedSeqsToView = new ArrayList<>();
747           pdbEntriesToView = data.collectSelectedRows(restable,selectedRows,selectedSeqsToView);
748
749           SequenceI[] selectedSeqs = selectedSeqsToView
750                   .toArray(new SequenceI[selectedSeqsToView.size()]);
751           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
752                   selectedSeqs);
753         }
754         else if (currentView == VIEWS_LOCAL_PDB)
755         {
756           int[] selectedRows = tbl_local_pdb.getSelectedRows();
757           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
758           int count = 0;
759           int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
760                   .getModelIndex();
761           int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
762                   .getModelIndex();
763           List<SequenceI> selectedSeqsToView = new ArrayList<>();
764           for (int row : selectedRows)
765           {
766             PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
767                     pdbIdColIndex);
768             pdbEntriesToView[count++] = pdbEntry;
769             SequenceI selectedSeq = (SequenceI) tbl_local_pdb
770                     .getValueAt(row, refSeqColIndex);
771             selectedSeqsToView.add(selectedSeq);
772           }
773           SequenceI[] selectedSeqs = selectedSeqsToView
774                   .toArray(new SequenceI[selectedSeqsToView.size()]);
775           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
776                   selectedSeqs);
777         }
778         else if (currentView == VIEWS_ENTER_ID)
779         {
780           SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
781                   .getCmb_assSeq().getSelectedItem()).getSequence();
782           if (userSelectedSeq != null)
783           {
784             selectedSequence = userSelectedSeq;
785           }
786           String pdbIdStr = txt_search.getText();
787           PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
788           if (pdbEntry == null)
789           {
790             pdbEntry = new PDBEntry();
791             if (pdbIdStr.split(":").length > 1)
792             {
793               pdbEntry.setId(pdbIdStr.split(":")[0]);
794               pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
795             }
796             else
797             {
798               pdbEntry.setId(pdbIdStr);
799             }
800             pdbEntry.setType(PDBEntry.Type.PDB);
801             selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
802           }
803
804           PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
805           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
806                   new SequenceI[]
807                   { selectedSequence });
808         }
809         else if (currentView == VIEWS_FROM_FILE)
810         {
811           SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
812                   .getCmb_assSeq().getSelectedItem()).getSequence();
813           if (userSelectedSeq != null)
814           {
815             selectedSequence = userSelectedSeq;
816           }
817           PDBEntry fileEntry = new AssociatePdbFileWithSeq()
818                   .associatePdbWithSeq(selectedPdbFileName,
819                           DataSourceType.FILE, selectedSequence, true,
820                           Desktop.instance);
821
822           sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
823                   ap, new SequenceI[]
824                   { selectedSequence });
825         }
826         SwingUtilities.invokeLater(new Runnable()
827         {
828           @Override
829           public void run()
830           {
831             closeAction(preferredHeight);
832             mainFrame.dispose();
833           }
834         });
835       }
836     };
837     Thread runner = new Thread(viewStruc);
838     runner.start();
839     if (waitUntilFinished)
840     {
841       while (sViewer == null ? runner.isAlive()
842               : (sViewer.sview == null ? true
843                       : !sViewer.sview.hasMapping()))
844       {
845         try
846         {
847           Thread.sleep(300);
848         } catch (InterruptedException ie)
849         {
850
851         }
852       }
853     }
854   }
855
856   /**
857    * Answers a structure viewer (new or existing) configured to superimpose
858    * added structures or not according to the user's choice
859    * 
860    * @param ssm
861    * @return
862    */
863   StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
864   {
865     Object sv = targetView.getSelectedItem();
866
867     return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
868   }
869
870   /**
871    * Adds PDB structures to a new or existing structure viewer
872    * 
873    * @param ssm
874    * @param pdbEntriesToView
875    * @param alignPanel
876    * @param sequences
877    * @return
878    */
879   private StructureViewer launchStructureViewer(
880           StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
881           final AlignmentPanel alignPanel, SequenceI[] sequences)
882   {
883     long progressId = sequences.hashCode();
884     setProgressBar(MessageManager
885             .getString("status.launching_3d_structure_viewer"), progressId);
886     final StructureViewer theViewer = getTargetedStructureViewer(ssm);
887     boolean superimpose = chk_superpose.isSelected();
888     theViewer.setSuperpose(superimpose);
889
890     /*
891      * remember user's choice of superimpose or not
892      */
893     Cache.setProperty(AUTOSUPERIMPOSE,
894             Boolean.valueOf(superimpose).toString());
895
896     setProgressBar(null, progressId);
897     if (SiftsSettings.isMapWithSifts())
898     {
899       List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
900       int p = 0;
901       // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
902       // real PDB ID. For moment, we can also safely do this if there is already
903       // a known mapping between the PDBEntry and the sequence.
904       for (SequenceI seq : sequences)
905       {
906         PDBEntry pdbe = pdbEntriesToView[p++];
907         if (pdbe != null && pdbe.getFile() != null)
908         {
909           StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
910           if (smm != null && smm.length > 0)
911           {
912             for (StructureMapping sm : smm)
913             {
914               if (sm.getSequence() == seq)
915               {
916                 continue;
917               }
918             }
919           }
920         }
921         if (seq.getPrimaryDBRefs().isEmpty())
922         {
923           seqsWithoutSourceDBRef.add(seq);
924           continue;
925         }
926       }
927       if (!seqsWithoutSourceDBRef.isEmpty())
928       {
929         int y = seqsWithoutSourceDBRef.size();
930         setProgressBar(MessageManager.formatMessage(
931                 "status.fetching_dbrefs_for_sequences_without_valid_refs",
932                 y), progressId);
933         SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
934                 .toArray(new SequenceI[y]);
935         DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
936         dbRefFetcher.fetchDBRefs(true);
937
938         setProgressBar("Fetch complete.", progressId); // todo i18n
939       }
940     }
941     if (pdbEntriesToView.length > 1)
942     {
943       setProgressBar(
944               MessageManager.getString(
945                       "status.fetching_3d_structures_for_selected_entries"),
946               progressId);
947       theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
948     }
949     else
950     {
951       setProgressBar(MessageManager.formatMessage(
952               "status.fetching_3d_structures_for",
953               pdbEntriesToView[0].getId()), progressId);
954       theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
955     }
956     setProgressBar(null, progressId);
957     // remember the last viewer we used...
958     lastTargetedView = theViewer;
959     return theViewer;
960   }
961
962   /**
963    * Populates the combo-box used in associating manually fetched structures to
964    * a unique sequence when more than one sequence selection is made.
965    */
966   @Override
967   protected void populateCmbAssociateSeqOptions(
968           JComboBox<AssociateSeqOptions> cmb_assSeq,
969           JLabel lbl_associateSeq)
970   {
971     cmb_assSeq.removeAllItems();
972     cmb_assSeq.addItem(
973             new AssociateSeqOptions("-Select Associated Seq-", null));
974     lbl_associateSeq.setVisible(false);
975     if (selectedSequences.length > 1)
976     {
977       for (SequenceI seq : selectedSequences)
978       {
979         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
980       }
981     }
982     else
983     {
984       String seqName = selectedSequence.getDisplayId(false);
985       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
986       lbl_associateSeq.setText(seqName);
987       lbl_associateSeq.setVisible(true);
988       cmb_assSeq.setVisible(false);
989     }
990   }
991
992   protected boolean isStructuresDiscovered()
993   {
994     return discoveredStructuresSet != null
995             && !discoveredStructuresSet.isEmpty();
996   }
997
998   protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
999                                // this.
1000   // Doing a search for "1" or "1c" is valuable?
1001   // Those work but are enormously slow.
1002
1003   @Override
1004   protected void txt_search_ActionPerformed()
1005   {
1006     String text = txt_search.getText().trim();
1007     if (text.length() >= PDB_ID_MIN)
1008       new Thread()
1009       {
1010
1011         @Override
1012         public void run()
1013         {
1014           errorWarning.setLength(0);
1015           isValidPBDEntry = false;
1016           if (text.length() > 0)
1017           {
1018             // TODO move this pdb id search into the PDB specific
1019             // FTSSearchEngine
1020             // for moment, it will work fine as is because it is self-contained
1021             String searchTerm = text.toLowerCase();
1022             searchTerm = searchTerm.split(":")[0];
1023             // System.out.println(">>>>> search term : " + searchTerm);
1024             List<FTSDataColumnI> wantedFields = new ArrayList<>();
1025             FTSRestRequest pdbRequest = new FTSRestRequest();
1026             pdbRequest.setAllowEmptySeq(false);
1027             pdbRequest.setResponseSize(1);
1028             pdbRequest.setFieldToSearchBy("(pdb_id:");
1029             pdbRequest.setWantedFields(wantedFields);
1030             pdbRequest.setSearchTerm(searchTerm + ")");
1031             pdbRequest.setAssociatedSequence(selectedSequence);
1032             FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1033             wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1034             FTSRestResponse resultList;
1035             try
1036             {
1037               resultList = pdbRestClient.executeRequest(pdbRequest);
1038             } catch (Exception e)
1039             {
1040               errorWarning.append(e.getMessage());
1041               return;
1042             } finally
1043             {
1044               validateSelections();
1045             }
1046             if (resultList.getSearchSummary() != null
1047                     && resultList.getSearchSummary().size() > 0)
1048             {
1049               isValidPBDEntry = true;
1050             }
1051           }
1052           validateSelections();
1053         }
1054       }.start();
1055   }
1056
1057   @Override
1058   protected void tabRefresh()
1059   {
1060     if (selectedSequences != null)
1061     {
1062       Thread refreshThread = new Thread(new Runnable()
1063       {
1064         @Override
1065         public void run()
1066         {
1067           fetchStructuresMetaData();
1068           filterResultSet(
1069                   ((FilterOption) cmb_filterOption.getSelectedItem())
1070                           .getValue());
1071         }
1072       });
1073       refreshThread.start();
1074     }
1075   }
1076
1077   public class PDBEntryTableModel extends AbstractTableModel
1078   {
1079     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1080         "File" };
1081
1082     private List<CachedPDB> pdbEntries;
1083
1084     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1085     {
1086       this.pdbEntries = new ArrayList<>(pdbEntries);
1087     }
1088
1089     @Override
1090     public String getColumnName(int columnIndex)
1091     {
1092       return columns[columnIndex];
1093     }
1094
1095     @Override
1096     public int getRowCount()
1097     {
1098       return pdbEntries.size();
1099     }
1100
1101     @Override
1102     public int getColumnCount()
1103     {
1104       return columns.length;
1105     }
1106
1107     @Override
1108     public boolean isCellEditable(int row, int column)
1109     {
1110       return false;
1111     }
1112
1113     @Override
1114     public Object getValueAt(int rowIndex, int columnIndex)
1115     {
1116       Object value = "??";
1117       CachedPDB entry = pdbEntries.get(rowIndex);
1118       switch (columnIndex)
1119       {
1120       case 0:
1121         value = entry.getSequence();
1122         break;
1123       case 1:
1124         value = entry.getPdbEntry();
1125         break;
1126       case 2:
1127         value = entry.getPdbEntry().getChainCode() == null ? "_"
1128                 : entry.getPdbEntry().getChainCode();
1129         break;
1130       case 3:
1131         value = entry.getPdbEntry().getType();
1132         break;
1133       case 4:
1134         value = entry.getPdbEntry().getFile();
1135         break;
1136       }
1137       return value;
1138     }
1139
1140     @Override
1141     public Class<?> getColumnClass(int columnIndex)
1142     {
1143       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1144     }
1145
1146     public CachedPDB getPDBEntryAt(int row)
1147     {
1148       return pdbEntries.get(row);
1149     }
1150
1151   }
1152
1153   private class CachedPDB
1154   {
1155     private SequenceI sequence;
1156
1157     private PDBEntry pdbEntry;
1158
1159     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1160     {
1161       this.sequence = sequence;
1162       this.pdbEntry = pdbEntry;
1163     }
1164
1165     public SequenceI getSequence()
1166     {
1167       return sequence;
1168     }
1169
1170     public PDBEntry getPdbEntry()
1171     {
1172       return pdbEntry;
1173     }
1174
1175   }
1176
1177   private IProgressIndicator progressBar;
1178
1179   @Override
1180   public void setProgressBar(String message, long id)
1181   {
1182     progressBar.setProgressBar(message, id);
1183   }
1184
1185   @Override
1186   public void registerHandler(long id, IProgressIndicatorHandler handler)
1187   {
1188     progressBar.registerHandler(id, handler);
1189   }
1190
1191   @Override
1192   public boolean operationInProgress()
1193   {
1194     return progressBar.operationInProgress();
1195   }
1196
1197   public JalviewStructureDisplayI getOpenedStructureViewer()
1198   {
1199     return sViewer == null ? null : sViewer.sview;
1200   }
1201
1202   @Override
1203   protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1204   {
1205     data.setDocFieldPrefs(newPrefs);
1206     
1207   }
1208 }