JAL-1823 improvement to all chain code specification from manual pdb entry mode
[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.sifts.SiftsSettings;
39
40 import java.awt.event.ItemEvent;
41 import java.util.ArrayList;
42 import java.util.Collection;
43 import java.util.HashSet;
44 import java.util.LinkedHashSet;
45 import java.util.List;
46 import java.util.Objects;
47 import java.util.Vector;
48
49 import javax.swing.JCheckBox;
50 import javax.swing.JComboBox;
51 import javax.swing.JLabel;
52 import javax.swing.JOptionPane;
53 import javax.swing.table.AbstractTableModel;
54
55 /**
56  * Provides the behaviors for the Structure chooser Panel
57  * 
58  * @author tcnofoegbu
59  *
60  */
61 @SuppressWarnings("serial")
62 public class StructureChooser extends GStructureChooser implements
63         IProgressIndicator
64 {
65   private boolean structuresDiscovered = false;
66
67   private SequenceI selectedSequence;
68
69   private SequenceI[] selectedSequences;
70
71   private IProgressIndicator progressIndicator;
72
73   private Collection<FTSData> discoveredStructuresSet;
74
75   private FTSRestRequest lastPdbRequest;
76
77   private FTSRestClientI pdbRestCleint;
78
79   private String selectedPdbFileName;
80
81   private boolean isValidPBDEntry;
82
83   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
84           AlignmentPanel ap)
85   {
86     this.ap = ap;
87     this.selectedSequence = selectedSeq;
88     this.selectedSequences = selectedSeqs;
89     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
90     init();
91   }
92
93   /**
94    * Initializes parameters used by the Structure Chooser Panel
95    */
96   public void init()
97   {
98     if (!Jalview.isHeadlessMode())
99     {
100       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
101     }
102
103     Thread discoverPDBStructuresThread = new Thread(new Runnable()
104     {
105       @Override
106       public void run()
107       {
108         long startTime = System.currentTimeMillis();
109         updateProgressIndicator(MessageManager
110                 .getString("status.loading_cached_pdb_entries"), startTime);
111         loadLocalCachedPDBEntries();
112         updateProgressIndicator(null, startTime);
113         updateProgressIndicator(MessageManager
114                 .getString("status.searching_for_pdb_structures"),
115                 startTime);
116         fetchStructuresMetaData();
117         populateFilterComboBox();
118         updateProgressIndicator(null, startTime);
119         mainFrame.setVisible(true);
120         updateCurrentView();
121       }
122     });
123     discoverPDBStructuresThread.start();
124   }
125
126   /**
127    * Updates the progress indicator with the specified message
128    * 
129    * @param message
130    *          displayed message for the operation
131    * @param id
132    *          unique handle for this indicator
133    */
134   public void updateProgressIndicator(String message, long id)
135   {
136     if (progressIndicator != null)
137     {
138       progressIndicator.setProgressBar(message, id);
139     }
140   }
141
142   /**
143    * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
144    * selection group
145    */
146   public void fetchStructuresMetaData()
147   {
148     long startTime = System.currentTimeMillis();
149     pdbRestCleint = PDBFTSRestClient.getInstance();
150     Collection<FTSDataColumnI> wantedFields = pdbRestCleint
151             .getAllDefaulDisplayedDataColumns();
152
153     discoveredStructuresSet = new LinkedHashSet<FTSData>();
154     HashSet<String> errors = new HashSet<String>();
155     for (SequenceI seq : selectedSequences)
156     {
157       FTSRestRequest pdbRequest = new FTSRestRequest();
158       pdbRequest.setAllowEmptySeq(false);
159       pdbRequest.setResponseSize(500);
160       pdbRequest.setFieldToSearchBy("(");
161       pdbRequest.setWantedFields(wantedFields);
162       pdbRequest.setSearchTerm(buildQuery(seq) + ")");
163       pdbRequest.setAssociatedSequence(seq);
164       FTSRestResponse resultList;
165       try
166       {
167         resultList = pdbRestCleint.executeRequest(pdbRequest);
168       } catch (Exception e)
169       {
170         e.printStackTrace();
171         errors.add(e.getMessage());
172         continue;
173       }
174       lastPdbRequest = pdbRequest;
175       if (resultList.getSearchSummary() != null
176               && !resultList.getSearchSummary().isEmpty())
177       {
178         discoveredStructuresSet.addAll(resultList.getSearchSummary());
179       }
180     }
181
182     int noOfStructuresFound = 0;
183     String totalTime = (System.currentTimeMillis() - startTime)
184             + " milli secs";
185     if (discoveredStructuresSet != null
186             && !discoveredStructuresSet.isEmpty())
187     {
188       tbl_summary.setModel(FTSRestResponse.getTableModel(lastPdbRequest,
189               discoveredStructuresSet));
190       structuresDiscovered = true;
191       noOfStructuresFound = discoveredStructuresSet.size();
192       mainFrame.setTitle(MessageManager.formatMessage(
193               "label.structure_chooser_no_of_structures",
194               noOfStructuresFound, totalTime));
195     }
196     else
197     {
198       mainFrame.setTitle(MessageManager
199               .getString("label.structure_chooser_manual_association"));
200       if (errors.size() > 0)
201       {
202         StringBuilder errorMsg = new StringBuilder();
203         for (String error : errors)
204         {
205           errorMsg.append(error).append("\n");
206         }
207         JOptionPane.showMessageDialog(this, errorMsg.toString(),
208                 MessageManager.getString("label.pdb_web-service_error"),
209                 JOptionPane.ERROR_MESSAGE);
210       }
211     }
212   }
213
214   public void loadLocalCachedPDBEntries()
215   {
216     ArrayList<CachedPDB> entries = new ArrayList<CachedPDB>();
217     for (SequenceI seq : selectedSequences)
218     {
219       if (seq.getDatasetSequence() != null
220               && seq.getDatasetSequence().getAllPDBEntries() != null)
221       {
222         for (PDBEntry pdbEntry : seq.getDatasetSequence()
223                 .getAllPDBEntries())
224         {
225           if (pdbEntry.getFile() != null)
226           {
227             entries.add(new CachedPDB(seq, pdbEntry));
228           }
229         }
230       }
231     }
232
233     PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
234     tbl_local_pdb.setModel(tableModelx);
235   }
236
237   /**
238    * Builds a query string for a given sequences using its DBRef entries
239    * 
240    * @param seq
241    *          the sequences to build a query for
242    * @return the built query string
243    */
244
245   public static String buildQuery(SequenceI seq)
246   {
247     boolean isPDBRefsFound = false;
248     boolean isUniProtRefsFound = false;
249     StringBuilder queryBuilder = new StringBuilder();
250     HashSet<String> seqRefs = new LinkedHashSet<String>();
251
252     if (seq.getAllPDBEntries() != null)
253     {
254       for (PDBEntry entry : seq.getAllPDBEntries())
255       {
256         if (isValidSeqName(entry.getId()))
257         {
258           queryBuilder.append("pdb_id")
259                   .append(":")
260 .append(entry.getId().toLowerCase())
261                   .append(" OR ");
262           isPDBRefsFound = true;
263           // seqRefs.add(entry.getId());
264         }
265       }
266     }
267
268     if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
269     {
270       for (DBRefEntry dbRef : seq.getDBRefs())
271       {
272         if (isValidSeqName(getDBRefId(dbRef)))
273         {
274           if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
275           {
276             queryBuilder
277 .append("uniprot_accession").append(":")
278                     .append(getDBRefId(dbRef))
279                     .append(" OR ");
280             queryBuilder
281 .append("uniprot_id")
282                     .append(":")
283                     .append(getDBRefId(dbRef)).append(" OR ");
284             isUniProtRefsFound = true;
285           }
286           else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
287           {
288
289             queryBuilder.append("pdb_id")
290                     .append(":").append(getDBRefId(dbRef).toLowerCase())
291                     .append(" OR ");
292             isPDBRefsFound = true;
293           }
294           else
295           {
296             seqRefs.add(getDBRefId(dbRef));
297           }
298         }
299       }
300     }
301
302     if (!isPDBRefsFound && !isUniProtRefsFound)
303     {
304       String seqName = seq.getName();
305       seqName = sanitizeSeqName(seqName);
306       String[] names = seqName.toLowerCase().split("\\|");
307       for (String name : names)
308       {
309         // System.out.println("Found name : " + name);
310         name.trim();
311         if (isValidSeqName(name))
312         {
313           seqRefs.add(name);
314         }
315       }
316
317       for (String seqRef : seqRefs)
318       {
319         queryBuilder.append("text:").append(seqRef).append(" OR ");
320       }
321     }
322
323     int endIndex = queryBuilder.lastIndexOf(" OR ");
324     if (queryBuilder.toString().length() < 6)
325     {
326       return null;
327     }
328     String query = queryBuilder.toString().substring(0, endIndex);
329     return query;
330   }
331
332   /**
333    * Remove the following special characters from input string +, -, &, |, !, (,
334    * ), {, }, [, ], ^, ", ~, *, ?, :, \
335    * 
336    * @param seqName
337    * @return
338    */
339   private static String sanitizeSeqName(String seqName)
340   {
341     Objects.requireNonNull(seqName);
342     return seqName.replaceAll("\\[\\d*\\]", "")
343             .replaceAll("[^\\dA-Za-z|]", "").replaceAll("\\s+", "+");
344   }
345
346
347   /**
348    * Ensures sequence ref names are not less than 3 characters and does not
349    * contain a database name
350    * 
351    * @param seqName
352    * @return
353    */
354   public static boolean isValidSeqName(String seqName)
355   {
356     // System.out.println("seqName : " + seqName);
357     String ignoreList = "pdb,uniprot,swiss-prot";
358     if (seqName.length() < 3)
359     {
360       return false;
361     }
362     if (seqName.contains(":"))
363     {
364       return false;
365     }
366     seqName = seqName.toLowerCase();
367     for (String ignoredEntry : ignoreList.split(","))
368     {
369       if (seqName.contains(ignoredEntry))
370       {
371         return false;
372       }
373     }
374     return true;
375   }
376
377   public static String getDBRefId(DBRefEntry dbRef)
378   {
379     String ref = dbRef.getAccessionId().replaceAll("GO:", "");
380     return ref;
381   }
382
383   /**
384    * Filters a given list of discovered structures based on supplied argument
385    * 
386    * @param fieldToFilterBy
387    *          the field to filter by
388    */
389   public void filterResultSet(final String fieldToFilterBy)
390   {
391     Thread filterThread = new Thread(new Runnable()
392     {
393       @Override
394       public void run()
395       {
396         long startTime = System.currentTimeMillis();
397         pdbRestCleint = PDBFTSRestClient.getInstance();
398         lbl_loading.setVisible(true);
399         Collection<FTSDataColumnI> wantedFields = pdbRestCleint
400                 .getAllDefaulDisplayedDataColumns();
401         Collection<FTSData> filteredResponse = new HashSet<FTSData>();
402         HashSet<String> errors = new HashSet<String>();
403
404         for (SequenceI seq : selectedSequences)
405         {
406           FTSRestRequest pdbRequest = new FTSRestRequest();
407           if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
408           {
409             System.out.println(">>>>>> Filtering with uniprot coverate");
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       for (SequenceI seq : sequences)
862       {
863         if (seq.getSourceDBRef() == null)
864         {
865           ssm.setProgressBar(null);
866           ssm.setProgressBar("Fetching Database refs..");
867           new jalview.ws.DBRefFetcher(sequences, null, null, null, false)
868                   .fetchDBRefs(true);
869           break;
870         }
871       }
872     }
873         if (pdbEntriesToView.length > 1)
874         {
875           ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
876           for (SequenceI seq : sequences)
877           {
878             seqsMap.add(new SequenceI[] { seq });
879           }
880           SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
881       ssm.setProgressBar(null);
882       ssm.setProgressBar("Fetching PDB Structures for selected entries..");
883           sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
884         }
885         else
886         {
887       ssm.setProgressBar(null);
888       ssm.setProgressBar("Fetching PDB Structure for "
889               + pdbEntriesToView[0].getId());
890           sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
891         }
892   }
893
894   /**
895    * Populates the combo-box used in associating manually fetched structures to
896    * a unique sequence when more than one sequence selection is made.
897    */
898   @Override
899   public void populateCmbAssociateSeqOptions(
900           JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
901   {
902     cmb_assSeq.removeAllItems();
903     cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
904             null));
905     lbl_associateSeq.setVisible(false);
906     if (selectedSequences.length > 1)
907     {
908       for (SequenceI seq : selectedSequences)
909       {
910         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
911       }
912     }
913     else
914     {
915       String seqName = selectedSequence.getDisplayId(false);
916       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
917       lbl_associateSeq.setText(seqName);
918       lbl_associateSeq.setVisible(true);
919       cmb_assSeq.setVisible(false);
920     }
921   }
922
923   public boolean isStructuresDiscovered()
924   {
925     return structuresDiscovered;
926   }
927
928   public void setStructuresDiscovered(boolean structuresDiscovered)
929   {
930     this.structuresDiscovered = structuresDiscovered;
931   }
932
933   public Collection<FTSData> getDiscoveredStructuresSet()
934   {
935     return discoveredStructuresSet;
936   }
937
938   @Override
939   protected void txt_search_ActionPerformed()
940   {
941     new Thread()
942     {
943       @Override
944       public void run()
945       {
946         errorWarning.setLength(0);
947         isValidPBDEntry = false;
948         if (txt_search.getText().length() > 0)
949         {
950           String searchTerm = txt_search.getText().toLowerCase();
951           searchTerm = searchTerm.split(":")[0];
952           System.out.println(">>>>> search term : " + searchTerm);
953           List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
954           FTSRestRequest pdbRequest = new FTSRestRequest();
955           pdbRequest.setAllowEmptySeq(false);
956           pdbRequest.setResponseSize(1);
957           pdbRequest.setFieldToSearchBy("(pdb_id:");
958           pdbRequest.setWantedFields(wantedFields);
959           pdbRequest
960 .setSearchTerm(searchTerm + ")");
961           pdbRequest.setAssociatedSequence(selectedSequence);
962           pdbRestCleint = PDBFTSRestClient.getInstance();
963           wantedFields.add(pdbRestCleint.getPrimaryKeyColumn());
964           FTSRestResponse resultList;
965           try
966           {
967             resultList = pdbRestCleint.executeRequest(pdbRequest);
968           } catch (Exception e)
969           {
970             errorWarning.append(e.getMessage());
971             return;
972           } finally
973           {
974             validateSelections();
975           }
976           if (resultList.getSearchSummary() != null
977                   && resultList.getSearchSummary().size() > 0)
978           {
979             isValidPBDEntry = true;
980           }
981         }
982         validateSelections();
983       }
984     }.start();
985   }
986
987   @Override
988   public void tabRefresh()
989   {
990     if (selectedSequences != null)
991     {
992       Thread refreshThread = new Thread(new Runnable()
993       {
994         @Override
995         public void run()
996         {
997           fetchStructuresMetaData();
998           filterResultSet(((FilterOption) cmb_filterOption
999                   .getSelectedItem()).getValue());
1000         }
1001       });
1002       refreshThread.start();
1003     }
1004   }
1005
1006   public class PDBEntryTableModel extends AbstractTableModel
1007   {
1008     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
1009
1010     private List<CachedPDB> pdbEntries;
1011
1012     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1013     {
1014       this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
1015     }
1016
1017     @Override
1018     public String getColumnName(int columnIndex)
1019     {
1020       return columns[columnIndex];
1021     }
1022
1023     @Override
1024     public int getRowCount()
1025     {
1026       return pdbEntries.size();
1027     }
1028
1029     @Override
1030     public int getColumnCount()
1031     {
1032       return columns.length;
1033     }
1034
1035     @Override
1036     public boolean isCellEditable(int row, int column)
1037     {
1038       return false;
1039     }
1040
1041     @Override
1042     public Object getValueAt(int rowIndex, int columnIndex)
1043     {
1044       Object value = "??";
1045       CachedPDB entry = pdbEntries.get(rowIndex);
1046       switch (columnIndex)
1047       {
1048       case 0:
1049         value = entry.getSequence();
1050         break;
1051       case 1:
1052         value = entry.getPdbEntry();
1053         break;
1054       case 2:
1055         value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
1056                 .getPdbEntry().getChainCode();
1057         break;
1058       case 3:
1059         value = entry.getPdbEntry().getType();
1060         break;
1061       case 4:
1062         value = entry.getPdbEntry().getFile();
1063         break;
1064       }
1065       return value;
1066     }
1067
1068     @Override
1069     public Class<?> getColumnClass(int columnIndex)
1070     {
1071       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1072     }
1073
1074     public CachedPDB getPDBEntryAt(int row)
1075     {
1076       return pdbEntries.get(row);
1077     }
1078
1079   }
1080
1081   private class CachedPDB
1082   {
1083     private SequenceI sequence;
1084
1085     private PDBEntry pdbEntry;
1086
1087     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1088     {
1089       this.sequence = sequence;
1090       this.pdbEntry = pdbEntry;
1091     }
1092
1093     public SequenceI getSequence()
1094     {
1095       return sequence;
1096     }
1097
1098     public PDBEntry getPdbEntry()
1099     {
1100       return pdbEntry;
1101     }
1102
1103   }
1104
1105   private IProgressIndicator progressBar;
1106
1107   @Override
1108   public void setProgressBar(String message, long id)
1109   {
1110     progressBar.setProgressBar(message, id);
1111   }
1112
1113   @Override
1114   public void registerHandler(long id, IProgressIndicatorHandler handler)
1115   {
1116     progressBar.registerHandler(id, handler);
1117   }
1118
1119   @Override
1120   public boolean operationInProgress()
1121   {
1122     return progressBar.operationInProgress();
1123   }
1124 }