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