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