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