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