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