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