JAL-1479 JAL- Fix to eradicate duplicate mapping output and further improvement for...
[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.bin.Jalview;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.DBRefSource;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.fts.api.FTSData;
30 import jalview.fts.api.FTSDataColumnI;
31 import jalview.fts.api.FTSRestClientI;
32 import jalview.fts.core.FTSRestRequest;
33 import jalview.fts.core.FTSRestResponse;
34 import jalview.fts.service.pdb.PDBFTSRestClient;
35 import jalview.jbgui.GStructureChooser;
36 import jalview.structure.StructureSelectionManager;
37 import jalview.util.MessageManager;
38 import jalview.ws.DBRefFetcher;
39 import jalview.ws.sifts.SiftsSettings;
40
41 import java.awt.event.ItemEvent;
42 import java.util.ArrayList;
43 import java.util.Collection;
44 import java.util.HashSet;
45 import java.util.LinkedHashSet;
46 import java.util.List;
47 import java.util.Objects;
48 import java.util.Vector;
49
50 import javax.swing.JCheckBox;
51 import javax.swing.JComboBox;
52 import javax.swing.JLabel;
53 import javax.swing.JOptionPane;
54 import javax.swing.table.AbstractTableModel;
55
56 /**
57  * Provides the behaviors for the Structure chooser Panel
58  * 
59  * @author tcnofoegbu
60  *
61  */
62 @SuppressWarnings("serial")
63 public class StructureChooser extends GStructureChooser implements
64         IProgressIndicator
65 {
66   private boolean structuresDiscovered = false;
67
68   private SequenceI selectedSequence;
69
70   private SequenceI[] selectedSequences;
71
72   private IProgressIndicator progressIndicator;
73
74   private Collection<FTSData> discoveredStructuresSet;
75
76   private FTSRestRequest lastPdbRequest;
77
78   private FTSRestClientI pdbRestCleint;
79
80   private String selectedPdbFileName;
81
82   private boolean isValidPBDEntry;
83
84   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
85           AlignmentPanel ap)
86   {
87     this.ap = ap;
88     this.selectedSequence = selectedSeq;
89     this.selectedSequences = selectedSeqs;
90     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
91     init();
92   }
93
94   /**
95    * Initializes parameters used by the Structure Chooser Panel
96    */
97   public void init()
98   {
99     if (!Jalview.isHeadlessMode())
100     {
101       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
102     }
103
104     Thread discoverPDBStructuresThread = new Thread(new Runnable()
105     {
106       @Override
107       public void run()
108       {
109         long startTime = System.currentTimeMillis();
110         updateProgressIndicator(MessageManager
111                 .getString("status.loading_cached_pdb_entries"), startTime);
112         loadLocalCachedPDBEntries();
113         updateProgressIndicator(null, startTime);
114         updateProgressIndicator(MessageManager
115                 .getString("status.searching_for_pdb_structures"),
116                 startTime);
117         fetchStructuresMetaData();
118         populateFilterComboBox();
119         updateProgressIndicator(null, startTime);
120         mainFrame.setVisible(true);
121         updateCurrentView();
122       }
123     });
124     discoverPDBStructuresThread.start();
125   }
126
127   /**
128    * Updates the progress indicator with the specified message
129    * 
130    * @param message
131    *          displayed message for the operation
132    * @param id
133    *          unique handle for this indicator
134    */
135   public void updateProgressIndicator(String message, long id)
136   {
137     if (progressIndicator != null)
138     {
139       progressIndicator.setProgressBar(message, id);
140     }
141   }
142
143   /**
144    * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
145    * selection group
146    */
147   public void fetchStructuresMetaData()
148   {
149     long startTime = System.currentTimeMillis();
150     pdbRestCleint = PDBFTSRestClient.getInstance();
151     Collection<FTSDataColumnI> wantedFields = pdbRestCleint
152             .getAllDefaulDisplayedDataColumns();
153
154     discoveredStructuresSet = new LinkedHashSet<FTSData>();
155     HashSet<String> errors = new HashSet<String>();
156     for (SequenceI seq : selectedSequences)
157     {
158       FTSRestRequest pdbRequest = new FTSRestRequest();
159       pdbRequest.setAllowEmptySeq(false);
160       pdbRequest.setResponseSize(500);
161       pdbRequest.setFieldToSearchBy("(");
162       pdbRequest.setWantedFields(wantedFields);
163       pdbRequest.setSearchTerm(buildQuery(seq) + ")");
164       pdbRequest.setAssociatedSequence(seq);
165       FTSRestResponse resultList;
166       try
167       {
168         resultList = pdbRestCleint.executeRequest(pdbRequest);
169       } catch (Exception e)
170       {
171         e.printStackTrace();
172         errors.add(e.getMessage());
173         continue;
174       }
175       lastPdbRequest = pdbRequest;
176       if (resultList.getSearchSummary() != null
177               && !resultList.getSearchSummary().isEmpty())
178       {
179         discoveredStructuresSet.addAll(resultList.getSearchSummary());
180       }
181     }
182
183     int noOfStructuresFound = 0;
184     String totalTime = (System.currentTimeMillis() - startTime)
185             + " milli secs";
186     if (discoveredStructuresSet != null
187             && !discoveredStructuresSet.isEmpty())
188     {
189       tbl_summary.setModel(FTSRestResponse.getTableModel(lastPdbRequest,
190               discoveredStructuresSet));
191       structuresDiscovered = true;
192       noOfStructuresFound = discoveredStructuresSet.size();
193       mainFrame.setTitle(MessageManager.formatMessage(
194               "label.structure_chooser_no_of_structures",
195               noOfStructuresFound, totalTime));
196     }
197     else
198     {
199       mainFrame.setTitle(MessageManager
200               .getString("label.structure_chooser_manual_association"));
201       if (errors.size() > 0)
202       {
203         StringBuilder errorMsg = new StringBuilder();
204         for (String error : errors)
205         {
206           errorMsg.append(error).append("\n");
207         }
208         JOptionPane.showMessageDialog(this, errorMsg.toString(),
209                 MessageManager.getString("label.pdb_web-service_error"),
210                 JOptionPane.ERROR_MESSAGE);
211       }
212     }
213   }
214
215   public void loadLocalCachedPDBEntries()
216   {
217     ArrayList<CachedPDB> entries = new ArrayList<CachedPDB>();
218     for (SequenceI seq : selectedSequences)
219     {
220       if (seq.getDatasetSequence() != null
221               && seq.getDatasetSequence().getAllPDBEntries() != null)
222       {
223         for (PDBEntry pdbEntry : seq.getDatasetSequence()
224                 .getAllPDBEntries())
225         {
226           if (pdbEntry.getFile() != null)
227           {
228             entries.add(new CachedPDB(seq, pdbEntry));
229           }
230         }
231       }
232     }
233
234     PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
235     tbl_local_pdb.setModel(tableModelx);
236   }
237
238   /**
239    * Builds a query string for a given sequences using its DBRef entries
240    * 
241    * @param seq
242    *          the sequences to build a query for
243    * @return the built query string
244    */
245
246   public static String buildQuery(SequenceI seq)
247   {
248     boolean isPDBRefsFound = false;
249     boolean isUniProtRefsFound = false;
250     StringBuilder queryBuilder = new StringBuilder();
251     HashSet<String> seqRefs = new LinkedHashSet<String>();
252
253     if (seq.getAllPDBEntries() != null)
254     {
255       for (PDBEntry entry : seq.getAllPDBEntries())
256       {
257         if (isValidSeqName(entry.getId()))
258         {
259           queryBuilder.append("pdb_id")
260                   .append(":")
261 .append(entry.getId().toLowerCase())
262                   .append(" OR ");
263           isPDBRefsFound = true;
264           // seqRefs.add(entry.getId());
265         }
266       }
267     }
268
269     if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
270     {
271       for (DBRefEntry dbRef : seq.getDBRefs())
272       {
273         if (isValidSeqName(getDBRefId(dbRef)))
274         {
275           if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
276           {
277             queryBuilder
278 .append("uniprot_accession").append(":")
279                     .append(getDBRefId(dbRef))
280                     .append(" OR ");
281             queryBuilder
282 .append("uniprot_id")
283                     .append(":")
284                     .append(getDBRefId(dbRef)).append(" OR ");
285             isUniProtRefsFound = true;
286           }
287           else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
288           {
289
290             queryBuilder.append("pdb_id")
291                     .append(":").append(getDBRefId(dbRef).toLowerCase())
292                     .append(" OR ");
293             isPDBRefsFound = true;
294           }
295           else
296           {
297             seqRefs.add(getDBRefId(dbRef));
298           }
299         }
300       }
301     }
302
303     if (!isPDBRefsFound && !isUniProtRefsFound)
304     {
305       String seqName = seq.getName();
306       seqName = sanitizeSeqName(seqName);
307       String[] names = seqName.toLowerCase().split("\\|");
308       for (String name : names)
309       {
310         // System.out.println("Found name : " + name);
311         name.trim();
312         if (isValidSeqName(name))
313         {
314           seqRefs.add(name);
315         }
316       }
317
318       for (String seqRef : seqRefs)
319       {
320         queryBuilder.append("text:").append(seqRef).append(" OR ");
321       }
322     }
323
324     int endIndex = queryBuilder.lastIndexOf(" OR ");
325     if (queryBuilder.toString().length() < 6)
326     {
327       return null;
328     }
329     String query = queryBuilder.toString().substring(0, endIndex);
330     return query;
331   }
332
333   /**
334    * Remove the following special characters from input string +, -, &, !, (, ),
335    * {, }, [, ], ^, ", ~, *, ?, :, \
336    * 
337    * @param seqName
338    * @return
339    */
340   private static String sanitizeSeqName(String seqName)
341   {
342     Objects.requireNonNull(seqName);
343     return seqName.replaceAll("\\[\\d*\\]", "")
344             .replaceAll("[^\\dA-Za-z|_]", "").replaceAll("\\s+", "+");
345   }
346
347
348   /**
349    * Ensures sequence ref names are not less than 3 characters and does not
350    * contain a database name
351    * 
352    * @param seqName
353    * @return
354    */
355   public static boolean isValidSeqName(String seqName)
356   {
357     // System.out.println("seqName : " + seqName);
358     String ignoreList = "pdb,uniprot,swiss-prot";
359     if (seqName.length() < 3)
360     {
361       return false;
362     }
363     if (seqName.contains(":"))
364     {
365       return false;
366     }
367     seqName = seqName.toLowerCase();
368     for (String ignoredEntry : ignoreList.split(","))
369     {
370       if (seqName.contains(ignoredEntry))
371       {
372         return false;
373       }
374     }
375     return true;
376   }
377
378   public static String getDBRefId(DBRefEntry dbRef)
379   {
380     String ref = dbRef.getAccessionId().replaceAll("GO:", "");
381     return ref;
382   }
383
384   /**
385    * Filters a given list of discovered structures based on supplied argument
386    * 
387    * @param fieldToFilterBy
388    *          the field to filter by
389    */
390   public void filterResultSet(final String fieldToFilterBy)
391   {
392     Thread filterThread = new Thread(new Runnable()
393     {
394       @Override
395       public void run()
396       {
397         long startTime = System.currentTimeMillis();
398         pdbRestCleint = PDBFTSRestClient.getInstance();
399         lbl_loading.setVisible(true);
400         Collection<FTSDataColumnI> wantedFields = pdbRestCleint
401                 .getAllDefaulDisplayedDataColumns();
402         Collection<FTSData> filteredResponse = new HashSet<FTSData>();
403         HashSet<String> errors = new HashSet<String>();
404
405         for (SequenceI seq : selectedSequences)
406         {
407           FTSRestRequest pdbRequest = new FTSRestRequest();
408           if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
409           {
410             pdbRequest.setAllowEmptySeq(false);
411             pdbRequest.setResponseSize(1);
412             pdbRequest.setFieldToSearchBy("(");
413             pdbRequest.setSearchTerm(buildQuery(seq) + ")");
414             pdbRequest.setWantedFields(wantedFields);
415             pdbRequest.setAssociatedSequence(seq);
416             pdbRequest.setFacet(true);
417             pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
418             pdbRequest.setFacetPivotMinCount(1);
419           }
420           else
421           {
422             pdbRequest.setAllowEmptySeq(false);
423             pdbRequest.setResponseSize(1);
424             pdbRequest.setFieldToSearchBy("(");
425             pdbRequest.setFieldToSortBy(fieldToFilterBy,
426                     !chk_invertFilter.isSelected());
427             pdbRequest.setSearchTerm(buildQuery(seq) + ")");
428             pdbRequest.setWantedFields(wantedFields);
429             pdbRequest.setAssociatedSequence(seq);
430           }
431           FTSRestResponse resultList;
432           try
433           {
434             resultList = pdbRestCleint.executeRequest(pdbRequest);
435           } catch (Exception e)
436           {
437             e.printStackTrace();
438             errors.add(e.getMessage());
439             continue;
440           }
441           lastPdbRequest = pdbRequest;
442           if (resultList.getSearchSummary() != null
443                   && !resultList.getSearchSummary().isEmpty())
444           {
445             filteredResponse.addAll(resultList.getSearchSummary());
446           }
447         }
448
449         String totalTime = (System.currentTimeMillis() - startTime)
450                 + " milli secs";
451         if (!filteredResponse.isEmpty())
452         {
453           final int filterResponseCount = filteredResponse.size();
454           Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<FTSData>();
455           reorderedStructuresSet.addAll(filteredResponse);
456           reorderedStructuresSet.addAll(discoveredStructuresSet);
457           tbl_summary.setModel(FTSRestResponse.getTableModel(
458                   lastPdbRequest, reorderedStructuresSet));
459
460           FTSRestResponse.configureTableColumn(tbl_summary, wantedFields);
461           tbl_summary.getColumn("Ref Sequence").setPreferredWidth(120);
462           tbl_summary.getColumn("Ref Sequence").setMinWidth(100);
463           tbl_summary.getColumn("Ref Sequence").setMaxWidth(200);
464           // Update table selection model here
465           tbl_summary.addRowSelectionInterval(0, filterResponseCount - 1);
466           mainFrame.setTitle(MessageManager.formatMessage(
467                   "label.structure_chooser_filter_time", totalTime));
468         }
469         else
470         {
471           mainFrame.setTitle(MessageManager.formatMessage(
472                   "label.structure_chooser_filter_time", totalTime));
473           if (errors.size() > 0)
474           {
475             StringBuilder errorMsg = new StringBuilder();
476             for (String error : errors)
477             {
478               errorMsg.append(error).append("\n");
479             }
480             JOptionPane.showMessageDialog(
481                     null,
482                     errorMsg.toString(),
483                     MessageManager.getString("label.pdb_web-service_error"),
484                     JOptionPane.ERROR_MESSAGE);
485           }
486         }
487
488         lbl_loading.setVisible(false);
489
490         validateSelections();
491       }
492     });
493     filterThread.start();
494   }
495
496   /**
497    * Handles action event for btn_pdbFromFile
498    */
499   @Override
500   public void pdbFromFile_actionPerformed()
501   {
502     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
503             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
504     chooser.setFileView(new jalview.io.JalviewFileView());
505     chooser.setDialogTitle(MessageManager.formatMessage(
506             "label.select_pdb_file_for",
507             selectedSequence.getDisplayId(false)));
508     chooser.setToolTipText(MessageManager.formatMessage(
509             "label.load_pdb_file_associate_with_sequence",
510             selectedSequence.getDisplayId(false)));
511
512     int value = chooser.showOpenDialog(null);
513     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
514     {
515       selectedPdbFileName = chooser.getSelectedFile().getPath();
516       jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
517       validateSelections();
518     }
519   }
520
521   /**
522    * Populates the filter combo-box options dynamically depending on discovered
523    * structures
524    */
525   @Override
526   protected void populateFilterComboBox()
527   {
528     if (isStructuresDiscovered())
529     {
530       cmb_filterOption.addItem(new FilterOption("Best Quality",
531               "overall_quality", VIEWS_FILTER));
532       cmb_filterOption.addItem(new FilterOption("Most UniProt Coverage",
533               "uniprot_coverage", VIEWS_FILTER));
534       cmb_filterOption.addItem(new FilterOption("Best Resolution",
535               "resolution", VIEWS_FILTER));
536       cmb_filterOption.addItem(new FilterOption("Most Protein Chain",
537               "number_of_protein_chains", VIEWS_FILTER));
538       cmb_filterOption.addItem(new FilterOption("Most Bound Molecules",
539               "number_of_bound_molecules", VIEWS_FILTER));
540       cmb_filterOption.addItem(new FilterOption("Most Polymer Residues",
541               "number_of_polymer_residues", VIEWS_FILTER));
542     }
543     cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
544             VIEWS_ENTER_ID));
545     cmb_filterOption.addItem(new FilterOption("From File", "-",
546             VIEWS_FROM_FILE));
547     cmb_filterOption.addItem(new FilterOption("Cached PDB Entries", "-",
548             VIEWS_LOCAL_PDB));
549   }
550
551   /**
552    * Updates the displayed view based on the selected filter option
553    */
554   @Override
555   protected void updateCurrentView()
556   {
557     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
558             .getSelectedItem());
559     layout_switchableViews.show(pnl_switchableViews,
560             selectedFilterOpt.getView());
561     String filterTitle = mainFrame.getTitle();
562     mainFrame.setTitle(frameTitle);
563     chk_invertFilter.setVisible(false);
564     if (selectedFilterOpt.getView() == VIEWS_FILTER)
565     {
566       mainFrame.setTitle(filterTitle);
567       chk_invertFilter.setVisible(true);
568       filterResultSet(selectedFilterOpt.getValue());
569     }
570     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
571             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
572     {
573       mainFrame.setTitle(MessageManager
574               .getString("label.structure_chooser_manual_association"));
575       idInputAssSeqPanel.loadCmbAssSeq();
576       fileChooserAssSeqPanel.loadCmbAssSeq();
577     }
578     validateSelections();
579   }
580
581   /**
582    * Validates user selection and activates the view button if all parameters
583    * are correct
584    */
585   @Override
586   public void validateSelections()
587   {
588     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
589             .getSelectedItem());
590     btn_view.setEnabled(false);
591     String currentView = selectedFilterOpt.getView();
592     if (currentView == VIEWS_FILTER)
593     {
594       if (tbl_summary.getSelectedRows().length > 0)
595       {
596         btn_view.setEnabled(true);
597       }
598     }
599     else if (currentView == VIEWS_LOCAL_PDB)
600     {
601       if (tbl_local_pdb.getSelectedRows().length > 0)
602       {
603         btn_view.setEnabled(true);
604       }
605     }
606     else if (currentView == VIEWS_ENTER_ID)
607     {
608       validateAssociationEnterPdb();
609     }
610     else if (currentView == VIEWS_FROM_FILE)
611     {
612       validateAssociationFromFile();
613     }
614   }
615
616   /**
617    * Validates inputs from the Manual PDB entry panel
618    */
619   public void validateAssociationEnterPdb()
620   {
621     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
622             .getCmb_assSeq().getSelectedItem();
623     lbl_pdbManualFetchStatus.setIcon(errorImage);
624     lbl_pdbManualFetchStatus.setToolTipText("");
625     if (txt_search.getText().length() > 0)
626     {
627       lbl_pdbManualFetchStatus
628               .setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager
629                       .formatMessage("info.no_pdb_entry_found_for",
630                               txt_search.getText())));
631     }
632
633     if (errorWarning.length() > 0)
634     {
635       lbl_pdbManualFetchStatus.setIcon(warningImage);
636       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(
637               true, errorWarning.toString()));
638     }
639
640     if (selectedSequences.length == 1
641             || !assSeqOpt.getName().equalsIgnoreCase(
642                     "-Select Associated Seq-"))
643     {
644       txt_search.setEnabled(true);
645       if (isValidPBDEntry)
646       {
647         btn_view.setEnabled(true);
648         lbl_pdbManualFetchStatus.setToolTipText("");
649         lbl_pdbManualFetchStatus.setIcon(goodImage);
650       }
651     }
652     else
653     {
654       txt_search.setEnabled(false);
655       lbl_pdbManualFetchStatus.setIcon(errorImage);
656     }
657   }
658
659   /**
660    * Validates inputs for the manual PDB file selection options
661    */
662   public void validateAssociationFromFile()
663   {
664     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
665             .getCmb_assSeq().getSelectedItem();
666     lbl_fromFileStatus.setIcon(errorImage);
667     if (selectedSequences.length == 1
668             || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
669                     "-Select Associated Seq-")))
670     {
671       btn_pdbFromFile.setEnabled(true);
672       if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
673       {
674         btn_view.setEnabled(true);
675         lbl_fromFileStatus.setIcon(goodImage);
676       }
677     }
678     else
679     {
680       btn_pdbFromFile.setEnabled(false);
681       lbl_fromFileStatus.setIcon(errorImage);
682     }
683   }
684
685   @Override
686   public void cmbAssSeqStateChanged()
687   {
688     validateSelections();
689   }
690
691   /**
692    * Handles the state change event for the 'filter' combo-box and 'invert'
693    * check-box
694    */
695   @Override
696   protected void stateChanged(ItemEvent e)
697   {
698     if (e.getSource() instanceof JCheckBox)
699     {
700       updateCurrentView();
701     }
702     else
703     {
704       if (e.getStateChange() == ItemEvent.SELECTED)
705       {
706         updateCurrentView();
707       }
708     }
709
710   }
711
712   /**
713    * Handles action event for btn_ok
714    */
715   @Override
716   public void ok_ActionPerformed()
717   {
718     final long progressSessionId = System.currentTimeMillis();
719     final StructureSelectionManager ssm = ap.getStructureSelectionManager();
720     ssm.setProgressIndicator(this);
721     ssm.setProgressSessionId(progressSessionId);
722     new Thread(new Runnable()
723     {
724       @Override
725       public void run()
726       {
727     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
728             .getSelectedItem());
729     String currentView = selectedFilterOpt.getView();
730     if (currentView == VIEWS_FILTER)
731     {
732           int pdbIdColIndex = tbl_summary.getColumn("PDB Id")
733                   .getModelIndex();
734           int refSeqColIndex = tbl_summary.getColumn("Ref Sequence")
735               .getModelIndex();
736           int[] selectedRows = tbl_summary.getSelectedRows();
737       PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
738       int count = 0;
739       ArrayList<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
740       for (int row : selectedRows)
741       {
742             String pdbIdStr = tbl_summary.getValueAt(row, pdbIdColIndex)
743                 .toString();
744             SequenceI selectedSeq = (SequenceI) tbl_summary.getValueAt(row,
745                 refSeqColIndex);
746         selectedSeqsToView.add(selectedSeq);
747             PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
748             if (pdbEntry == null)
749             {
750               pdbEntry = getFindEntry(pdbIdStr,
751                       selectedSeq.getAllPDBEntries());
752             }
753         if (pdbEntry == null)
754         {
755           pdbEntry = new PDBEntry();
756           pdbEntry.setId(pdbIdStr);
757           pdbEntry.setType(PDBEntry.Type.PDB);
758           selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
759         }
760         pdbEntriesToView[count++] = pdbEntry;
761       }
762       SequenceI[] selectedSeqs = selectedSeqsToView
763               .toArray(new SequenceI[selectedSeqsToView.size()]);
764           launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
765     }
766     else if (currentView == VIEWS_LOCAL_PDB)
767     {
768       int[] selectedRows = tbl_local_pdb.getSelectedRows();
769       PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
770       int count = 0;
771           int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
772                   .getModelIndex();
773       int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
774               .getModelIndex();
775       ArrayList<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
776       for (int row : selectedRows)
777       {
778         PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
779                 pdbIdColIndex);
780         pdbEntriesToView[count++] = pdbEntry;
781         SequenceI selectedSeq = (SequenceI) tbl_local_pdb.getValueAt(row,
782                 refSeqColIndex);
783         selectedSeqsToView.add(selectedSeq);
784       }
785       SequenceI[] selectedSeqs = selectedSeqsToView
786               .toArray(new SequenceI[selectedSeqsToView.size()]);
787           launchStructureViewer(ssm, pdbEntriesToView, ap, selectedSeqs);
788     }
789     else if (currentView == VIEWS_ENTER_ID)
790     {
791       SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
792               .getCmb_assSeq().getSelectedItem()).getSequence();
793       if (userSelectedSeq != null)
794       {
795         selectedSequence = userSelectedSeq;
796       }
797
798       String pdbIdStr = txt_search.getText();
799       PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
800       if (pdbEntry == null)
801       {
802         pdbEntry = new PDBEntry();
803             if (pdbIdStr.split(":").length > 1)
804             {
805               pdbEntry.setChainCode(pdbIdStr.split(":")[1]);
806             }
807         pdbEntry.setId(pdbIdStr);
808         pdbEntry.setType(PDBEntry.Type.PDB);
809         selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
810       }
811
812       PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
813           launchStructureViewer(ssm, pdbEntriesToView, ap,
814                   new SequenceI[] { selectedSequence });
815     }
816     else if (currentView == VIEWS_FROM_FILE)
817     {
818       SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
819               .getCmb_assSeq().getSelectedItem()).getSequence();
820       if (userSelectedSeq != null)
821       {
822         selectedSequence = userSelectedSeq;
823       }
824       PDBEntry fileEntry = new AssociatePdbFileWithSeq()
825               .associatePdbWithSeq(selectedPdbFileName,
826                       jalview.io.AppletFormatAdapter.FILE,
827                       selectedSequence, true, Desktop.instance);
828
829           launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap,
830                   new SequenceI[] { selectedSequence });
831     }
832     mainFrame.dispose();
833       }
834     }).start();
835   }
836
837   private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
838   {
839     Objects.requireNonNull(id);
840     Objects.requireNonNull(pdbEntries);
841     PDBEntry foundEntry = null;
842     for (PDBEntry entry : pdbEntries)
843     {
844       if (entry.getId().equalsIgnoreCase(id))
845       {
846         return entry;
847       }
848     }
849     return foundEntry;
850   }
851
852   private void launchStructureViewer(StructureSelectionManager ssm,
853           final PDBEntry[] pdbEntriesToView,
854           final AlignmentPanel alignPanel, SequenceI[] sequences)
855   {
856     ssm.setProgressBar("Launching PDB structure viewer..");
857     final StructureViewer sViewer = new StructureViewer(ssm);
858
859     if (SiftsSettings.isMapWithSifts())
860     {
861       ArrayList<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
862       for (SequenceI seq : sequences)
863       {
864         if (seq.getSourceDBRef() == null && seq.getDBRefs() == null)
865         {
866             seqsWithoutSourceDBRef.add(seq);
867             continue;
868           }
869       }
870       if (!seqsWithoutSourceDBRef.isEmpty())
871       {
872         int y = seqsWithoutSourceDBRef.size();
873         ssm.setProgressBar(null);
874         ssm.setProgressBar("Fetching db refs for " + y
875                 + " sequence" + (y > 1 ? "s" : "")
876                 + " without valid db ref required for SIFTS mapping");
877         SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
878         int x = 0;
879         for (SequenceI fSeq : seqsWithoutSourceDBRef)
880         {
881           seqWithoutSrcDBRef[x++] = fSeq;
882         }
883         new DBRefFetcher(seqWithoutSrcDBRef).fetchDBRefs(true);
884       }
885     }
886     if (pdbEntriesToView.length > 1)
887     {
888       ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
889       for (SequenceI seq : sequences)
890       {
891         seqsMap.add(new SequenceI[] { seq });
892       }
893       SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
894       ssm.setProgressBar(null);
895       ssm.setProgressBar("Fetching PDB Structures for selected entries..");
896       sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
897     }
898     else
899     {
900       ssm.setProgressBar(null);
901       ssm.setProgressBar("Fetching PDB Structure for "
902               + pdbEntriesToView[0].getId());
903       sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
904     }
905   }
906
907   /**
908    * Populates the combo-box used in associating manually fetched structures to
909    * a unique sequence when more than one sequence selection is made.
910    */
911   @Override
912   public void populateCmbAssociateSeqOptions(
913           JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
914   {
915     cmb_assSeq.removeAllItems();
916     cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
917             null));
918     lbl_associateSeq.setVisible(false);
919     if (selectedSequences.length > 1)
920     {
921       for (SequenceI seq : selectedSequences)
922       {
923         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
924       }
925     }
926     else
927     {
928       String seqName = selectedSequence.getDisplayId(false);
929       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
930       lbl_associateSeq.setText(seqName);
931       lbl_associateSeq.setVisible(true);
932       cmb_assSeq.setVisible(false);
933     }
934   }
935
936   public boolean isStructuresDiscovered()
937   {
938     return structuresDiscovered;
939   }
940
941   public void setStructuresDiscovered(boolean structuresDiscovered)
942   {
943     this.structuresDiscovered = structuresDiscovered;
944   }
945
946   public Collection<FTSData> getDiscoveredStructuresSet()
947   {
948     return discoveredStructuresSet;
949   }
950
951   @Override
952   protected void txt_search_ActionPerformed()
953   {
954     new Thread()
955     {
956       @Override
957       public void run()
958       {
959         errorWarning.setLength(0);
960         isValidPBDEntry = false;
961         if (txt_search.getText().length() > 0)
962         {
963           String searchTerm = txt_search.getText().toLowerCase();
964           searchTerm = searchTerm.split(":")[0];
965           System.out.println(">>>>> search term : " + searchTerm);
966           List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
967           FTSRestRequest pdbRequest = new FTSRestRequest();
968           pdbRequest.setAllowEmptySeq(false);
969           pdbRequest.setResponseSize(1);
970           pdbRequest.setFieldToSearchBy("(pdb_id:");
971           pdbRequest.setWantedFields(wantedFields);
972           pdbRequest
973 .setSearchTerm(searchTerm + ")");
974           pdbRequest.setAssociatedSequence(selectedSequence);
975           pdbRestCleint = PDBFTSRestClient.getInstance();
976           wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
977           FTSRestResponse resultList;
978           try
979           {
980             resultList = pdbRestCleint.executeRequest(pdbRequest);
981           } catch (Exception e)
982           {
983             errorWarning.append(e.getMessage());
984             return;
985           } finally
986           {
987             validateSelections();
988           }
989           if (resultList.getSearchSummary() != null
990                   && resultList.getSearchSummary().size() > 0)
991           {
992             isValidPBDEntry = true;
993           }
994         }
995         validateSelections();
996       }
997     }.start();
998   }
999
1000   @Override
1001   public void tabRefresh()
1002   {
1003     if (selectedSequences != null)
1004     {
1005       Thread refreshThread = new Thread(new Runnable()
1006       {
1007         @Override
1008         public void run()
1009         {
1010           fetchStructuresMetaData();
1011           filterResultSet(((FilterOption) cmb_filterOption
1012                   .getSelectedItem()).getValue());
1013         }
1014       });
1015       refreshThread.start();
1016     }
1017   }
1018
1019   public class PDBEntryTableModel extends AbstractTableModel
1020   {
1021     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
1022
1023     private List<CachedPDB> pdbEntries;
1024
1025     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1026     {
1027       this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
1028     }
1029
1030     @Override
1031     public String getColumnName(int columnIndex)
1032     {
1033       return columns[columnIndex];
1034     }
1035
1036     @Override
1037     public int getRowCount()
1038     {
1039       return pdbEntries.size();
1040     }
1041
1042     @Override
1043     public int getColumnCount()
1044     {
1045       return columns.length;
1046     }
1047
1048     @Override
1049     public boolean isCellEditable(int row, int column)
1050     {
1051       return false;
1052     }
1053
1054     @Override
1055     public Object getValueAt(int rowIndex, int columnIndex)
1056     {
1057       Object value = "??";
1058       CachedPDB entry = pdbEntries.get(rowIndex);
1059       switch (columnIndex)
1060       {
1061       case 0:
1062         value = entry.getSequence();
1063         break;
1064       case 1:
1065         value = entry.getPdbEntry();
1066         break;
1067       case 2:
1068         value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
1069                 .getPdbEntry().getChainCode();
1070         break;
1071       case 3:
1072         value = entry.getPdbEntry().getType();
1073         break;
1074       case 4:
1075         value = entry.getPdbEntry().getFile();
1076         break;
1077       }
1078       return value;
1079     }
1080
1081     @Override
1082     public Class<?> getColumnClass(int columnIndex)
1083     {
1084       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1085     }
1086
1087     public CachedPDB getPDBEntryAt(int row)
1088     {
1089       return pdbEntries.get(row);
1090     }
1091
1092   }
1093
1094   private class CachedPDB
1095   {
1096     private SequenceI sequence;
1097
1098     private PDBEntry pdbEntry;
1099
1100     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1101     {
1102       this.sequence = sequence;
1103       this.pdbEntry = pdbEntry;
1104     }
1105
1106     public SequenceI getSequence()
1107     {
1108       return sequence;
1109     }
1110
1111     public PDBEntry getPdbEntry()
1112     {
1113       return pdbEntry;
1114     }
1115
1116   }
1117
1118   private IProgressIndicator progressBar;
1119
1120   @Override
1121   public void setProgressBar(String message, long id)
1122   {
1123     progressBar.setProgressBar(message, id);
1124   }
1125
1126   @Override
1127   public void registerHandler(long id, IProgressIndicatorHandler handler)
1128   {
1129     progressBar.registerHandler(id, handler);
1130   }
1131
1132   @Override
1133   public boolean operationInProgress()
1134   {
1135     return progressBar.operationInProgress();
1136   }
1137 }