JAL-2237 apply default filter as sort in initial search
[jalview.git] / src / jalview / gui / StructureChooser.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21
22 package jalview.gui;
23
24 import jalview.bin.Jalview;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.DBRefSource;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.fts.api.FTSData;
30 import jalview.fts.api.FTSDataColumnI;
31 import jalview.fts.api.FTSRestClientI;
32 import jalview.fts.core.FTSRestRequest;
33 import jalview.fts.core.FTSRestResponse;
34 import jalview.fts.service.pdb.PDBFTSRestClient;
35 import jalview.jbgui.GStructureChooser;
36 import jalview.structure.StructureMapping;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.MessageManager;
39 import jalview.ws.DBRefFetcher;
40 import jalview.ws.sifts.SiftsSettings;
41
42 import java.awt.event.ItemEvent;
43 import java.util.ArrayList;
44 import java.util.Collection;
45 import java.util.HashSet;
46 import java.util.LinkedHashSet;
47 import java.util.List;
48 import java.util.Objects;
49 import java.util.Set;
50 import java.util.Vector;
51
52 import javax.swing.JCheckBox;
53 import javax.swing.JComboBox;
54 import javax.swing.JLabel;
55 import javax.swing.JOptionPane;
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 SequenceI selectedSequence;
69
70   private SequenceI[] selectedSequences;
71
72   private IProgressIndicator progressIndicator;
73
74   private Collection<FTSData> discoveredStructuresSet;
75
76   private FTSRestRequest lastPdbRequest;
77
78   private FTSRestClientI pdbRestCleint;
79
80   private String selectedPdbFileName;
81
82   private boolean isValidPBDEntry;
83
84   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
85           AlignmentPanel ap)
86   {
87     this.ap = ap;
88     this.selectedSequence = selectedSeq;
89     this.selectedSequences = selectedSeqs;
90     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
91     init();
92   }
93
94   /**
95    * Initializes parameters used by the Structure Chooser Panel
96    */
97   public void init()
98   {
99     if (!Jalview.isHeadlessMode())
100     {
101       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
102     }
103
104     // ensure a filter option is in force for search
105     populateFilterComboBox(true);
106     Thread discoverPDBStructuresThread = new Thread(new Runnable()
107     {
108       @Override
109       public void run()
110       {
111         long startTime = System.currentTimeMillis();
112         updateProgressIndicator(MessageManager
113                 .getString("status.loading_cached_pdb_entries"), startTime);
114         loadLocalCachedPDBEntries();
115         updateProgressIndicator(null, startTime);
116         updateProgressIndicator(MessageManager
117                 .getString("status.searching_for_pdb_structures"),
118                 startTime);
119         fetchStructuresMetaData();
120         // revise filter options if no results were found
121         populateFilterComboBox(isStructuresDiscovered());
122         updateProgressIndicator(null, startTime);
123         mainFrame.setVisible(true);
124         updateCurrentView();
125       }
126     });
127     discoverPDBStructuresThread.start();
128   }
129
130   /**
131    * Updates the progress indicator with the specified message
132    * 
133    * @param message
134    *          displayed message for the operation
135    * @param id
136    *          unique handle for this indicator
137    */
138   public void updateProgressIndicator(String message, long id)
139   {
140     if (progressIndicator != null)
141     {
142       progressIndicator.setProgressBar(message, id);
143     }
144   }
145
146   /**
147    * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
148    * selection group
149    */
150   public void fetchStructuresMetaData()
151   {
152     long startTime = System.currentTimeMillis();
153     pdbRestCleint = PDBFTSRestClient.getInstance();
154     Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
155             .getStructureSummaryFields();
156
157     discoveredStructuresSet = new LinkedHashSet<FTSData>();
158     HashSet<String> errors = new HashSet<String>();
159     for (SequenceI seq : selectedSequences)
160     {
161       FTSRestRequest pdbRequest = new FTSRestRequest();
162       pdbRequest.setAllowEmptySeq(false);
163       pdbRequest.setResponseSize(500);
164       pdbRequest.setFieldToSearchBy("(");
165       FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
166               .getSelectedItem());
167       pdbRequest.setFieldToSortBy(selectedFilterOpt.getValue(),
168               !chk_invertFilter.isSelected());
169       pdbRequest.setWantedFields(wantedFields);
170       pdbRequest.setSearchTerm(buildQuery(seq) + ")");
171       pdbRequest.setAssociatedSequence(seq);
172       FTSRestResponse resultList;
173       try
174       {
175         resultList = pdbRestCleint.executeRequest(pdbRequest);
176       } catch (Exception e)
177       {
178         e.printStackTrace();
179         errors.add(e.getMessage());
180         continue;
181       }
182       lastPdbRequest = pdbRequest;
183       if (resultList.getSearchSummary() != null
184               && !resultList.getSearchSummary().isEmpty())
185       {
186         discoveredStructuresSet.addAll(resultList.getSearchSummary());
187       }
188     }
189
190     int noOfStructuresFound = 0;
191     String totalTime = (System.currentTimeMillis() - startTime)
192             + " milli secs";
193     if (discoveredStructuresSet != null
194             && !discoveredStructuresSet.isEmpty())
195     {
196       getResultTable().setModel(
197               FTSRestResponse.getTableModel(lastPdbRequest,
198               discoveredStructuresSet));
199       noOfStructuresFound = discoveredStructuresSet.size();
200       mainFrame.setTitle(MessageManager.formatMessage(
201               "label.structure_chooser_no_of_structures",
202               noOfStructuresFound, totalTime));
203     }
204     else
205     {
206       mainFrame.setTitle(MessageManager
207               .getString("label.structure_chooser_manual_association"));
208       if (errors.size() > 0)
209       {
210         StringBuilder errorMsg = new StringBuilder();
211         for (String error : errors)
212         {
213           errorMsg.append(error).append("\n");
214         }
215         JOptionPane.showMessageDialog(this, errorMsg.toString(),
216                 MessageManager.getString("label.pdb_web-service_error"),
217                 JOptionPane.ERROR_MESSAGE);
218       }
219     }
220   }
221
222   public void loadLocalCachedPDBEntries()
223   {
224     ArrayList<CachedPDB> entries = new ArrayList<CachedPDB>();
225     for (SequenceI seq : selectedSequences)
226     {
227       if (seq.getDatasetSequence() != null
228               && seq.getDatasetSequence().getAllPDBEntries() != null)
229       {
230         for (PDBEntry pdbEntry : seq.getDatasetSequence()
231                 .getAllPDBEntries())
232         {
233           if (pdbEntry.getFile() != null)
234           {
235             entries.add(new CachedPDB(seq, pdbEntry));
236           }
237         }
238       }
239     }
240
241     PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
242     tbl_local_pdb.setModel(tableModelx);
243   }
244
245   /**
246    * Builds a query string for a given sequences using its DBRef entries
247    * 
248    * @param seq
249    *          the sequences to build a query for
250    * @return the built query string
251    */
252
253   public static String buildQuery(SequenceI seq)
254   {
255     boolean isPDBRefsFound = false;
256     boolean isUniProtRefsFound = false;
257     StringBuilder queryBuilder = new StringBuilder();
258     Set<String> seqRefs = new LinkedHashSet<String>();
259
260     if (seq.getAllPDBEntries() != null)
261     {
262       for (PDBEntry entry : seq.getAllPDBEntries())
263       {
264         if (isValidSeqName(entry.getId()))
265         {
266           queryBuilder.append("pdb_id:")
267                   .append(entry.getId().toLowerCase())
268                   .append(" OR ");
269           isPDBRefsFound = true;
270           // seqRefs.add(entry.getId());
271         }
272       }
273     }
274
275     if (seq.getDBRefs() != null && seq.getDBRefs().length != 0)
276     {
277       for (DBRefEntry dbRef : seq.getDBRefs())
278       {
279         if (isValidSeqName(getDBRefId(dbRef)))
280         {
281           if (dbRef.getSource().equalsIgnoreCase(DBRefSource.UNIPROT))
282           {
283             queryBuilder.append("uniprot_accession:")
284                     .append(getDBRefId(dbRef))
285                     .append(" OR ");
286             queryBuilder.append("uniprot_id:").append(getDBRefId(dbRef))
287                     .append(" OR ");
288             isUniProtRefsFound = true;
289           }
290           else if (dbRef.getSource().equalsIgnoreCase(DBRefSource.PDB))
291           {
292
293             queryBuilder.append("pdb_id:")
294                     .append(getDBRefId(dbRef).toLowerCase())
295                     .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   /**
352    * Ensures sequence ref names are not less than 3 characters and does not
353    * contain a database name
354    * 
355    * @param seqName
356    * @return
357    */
358   public static boolean isValidSeqName(String seqName)
359   {
360     // System.out.println("seqName : " + seqName);
361     String ignoreList = "pdb,uniprot,swiss-prot";
362     if (seqName.length() < 3)
363     {
364       return false;
365     }
366     if (seqName.contains(":"))
367     {
368       return false;
369     }
370     seqName = seqName.toLowerCase();
371     for (String ignoredEntry : ignoreList.split(","))
372     {
373       if (seqName.contains(ignoredEntry))
374       {
375         return false;
376       }
377     }
378     return true;
379   }
380
381   public static String getDBRefId(DBRefEntry dbRef)
382   {
383     String ref = dbRef.getAccessionId().replaceAll("GO:", "");
384     return ref;
385   }
386
387   /**
388    * Filters a given list of discovered structures based on supplied argument
389    * 
390    * @param fieldToFilterBy
391    *          the field to filter by
392    */
393   public void filterResultSet(final String fieldToFilterBy)
394   {
395     Thread filterThread = new Thread(new Runnable()
396     {
397       @Override
398       public void run()
399       {
400         long startTime = System.currentTimeMillis();
401         pdbRestCleint = PDBFTSRestClient.getInstance();
402         lbl_loading.setVisible(true);
403         Collection<FTSDataColumnI> wantedFields = pdbDocFieldPrefs
404                 .getStructureSummaryFields();
405         Collection<FTSData> filteredResponse = new HashSet<FTSData>();
406         HashSet<String> errors = new HashSet<String>();
407
408         for (SequenceI seq : selectedSequences)
409         {
410           FTSRestRequest pdbRequest = new FTSRestRequest();
411           if (fieldToFilterBy.equalsIgnoreCase("uniprot_coverage"))
412           {
413             pdbRequest.setAllowEmptySeq(false);
414             pdbRequest.setResponseSize(1);
415             pdbRequest.setFieldToSearchBy("(");
416             pdbRequest.setSearchTerm(buildQuery(seq) + ")");
417             pdbRequest.setWantedFields(wantedFields);
418             pdbRequest.setAssociatedSequence(seq);
419             pdbRequest.setFacet(true);
420             pdbRequest.setFacetPivot(fieldToFilterBy + ",entry_entity");
421             pdbRequest.setFacetPivotMinCount(1);
422           }
423           else
424           {
425             pdbRequest.setAllowEmptySeq(false);
426             pdbRequest.setResponseSize(1);
427             pdbRequest.setFieldToSearchBy("(");
428             pdbRequest.setFieldToSortBy(fieldToFilterBy,
429                     !chk_invertFilter.isSelected());
430             pdbRequest.setSearchTerm(buildQuery(seq) + ")");
431             pdbRequest.setWantedFields(wantedFields);
432             pdbRequest.setAssociatedSequence(seq);
433           }
434           FTSRestResponse resultList;
435           try
436           {
437             resultList = pdbRestCleint.executeRequest(pdbRequest);
438           } catch (Exception e)
439           {
440             e.printStackTrace();
441             errors.add(e.getMessage());
442             continue;
443           }
444           lastPdbRequest = pdbRequest;
445           if (resultList.getSearchSummary() != null
446                   && !resultList.getSearchSummary().isEmpty())
447           {
448             filteredResponse.addAll(resultList.getSearchSummary());
449           }
450         }
451
452         String totalTime = (System.currentTimeMillis() - startTime)
453                 + " milli secs";
454         if (!filteredResponse.isEmpty())
455         {
456           final int filterResponseCount = filteredResponse.size();
457           Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<FTSData>();
458           reorderedStructuresSet.addAll(filteredResponse);
459           reorderedStructuresSet.addAll(discoveredStructuresSet);
460           getResultTable().setModel(
461                   FTSRestResponse.getTableModel(
462                   lastPdbRequest, reorderedStructuresSet));
463
464           FTSRestResponse.configureTableColumn(getResultTable(),
465                   wantedFields, tempUserPrefs);
466           getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
467           getResultTable().getColumn("Ref Sequence").setMinWidth(100);
468           getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
469           // Update table selection model here
470           getResultTable().addRowSelectionInterval(0,
471                   filterResponseCount - 1);
472           mainFrame.setTitle(MessageManager.formatMessage(
473                   "label.structure_chooser_filter_time", totalTime));
474         }
475         else
476         {
477           mainFrame.setTitle(MessageManager.formatMessage(
478                   "label.structure_chooser_filter_time", totalTime));
479           if (errors.size() > 0)
480           {
481             StringBuilder errorMsg = new StringBuilder();
482             for (String error : errors)
483             {
484               errorMsg.append(error).append("\n");
485             }
486             JOptionPane.showMessageDialog(
487                     null,
488                     errorMsg.toString(),
489                     MessageManager.getString("label.pdb_web-service_error"),
490                     JOptionPane.ERROR_MESSAGE);
491           }
492         }
493
494         lbl_loading.setVisible(false);
495
496         validateSelections();
497       }
498     });
499     filterThread.start();
500   }
501
502   /**
503    * Handles action event for btn_pdbFromFile
504    */
505   @Override
506   public void pdbFromFile_actionPerformed()
507   {
508     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
509             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
510     chooser.setFileView(new jalview.io.JalviewFileView());
511     chooser.setDialogTitle(MessageManager.formatMessage(
512             "label.select_pdb_file_for",
513             selectedSequence.getDisplayId(false)));
514     chooser.setToolTipText(MessageManager.formatMessage(
515             "label.load_pdb_file_associate_with_sequence",
516             selectedSequence.getDisplayId(false)));
517
518     int value = chooser.showOpenDialog(null);
519     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
520     {
521       selectedPdbFileName = chooser.getSelectedFile().getPath();
522       jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
523       validateSelections();
524     }
525   }
526
527   /**
528    * Populates the filter combo-box options dynamically depending on discovered
529    * structures
530    */
531   protected void populateFilterComboBox(boolean haveData)
532   {
533     /*
534      * temporarily suspend the change listener behaviour
535      */
536     cmb_filterOption.removeItemListener(this);
537
538     cmb_filterOption.removeAllItems();
539     if (haveData)
540     {
541       cmb_filterOption.addItem(new FilterOption("Best Quality",
542               "overall_quality", VIEWS_FILTER));
543       cmb_filterOption.addItem(new FilterOption("Best Resolution",
544               "resolution", VIEWS_FILTER));
545       cmb_filterOption.addItem(new FilterOption("Most Protein Chain",
546               "number_of_protein_chains", VIEWS_FILTER));
547       cmb_filterOption.addItem(new FilterOption("Most Bound Molecules",
548               "number_of_bound_molecules", VIEWS_FILTER));
549       cmb_filterOption.addItem(new FilterOption("Most Polymer Residues",
550               "number_of_polymer_residues", VIEWS_FILTER));
551     }
552     cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
553             VIEWS_ENTER_ID));
554     cmb_filterOption.addItem(new FilterOption("From File", "-",
555             VIEWS_FROM_FILE));
556     cmb_filterOption.addItem(new FilterOption("Cached PDB Entries", "-",
557             VIEWS_LOCAL_PDB));
558
559     cmb_filterOption.addItemListener(this);
560   }
561
562   /**
563    * Updates the displayed view based on the selected filter option
564    */
565   protected void updateCurrentView()
566   {
567     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
568             .getSelectedItem());
569     layout_switchableViews.show(pnl_switchableViews,
570             selectedFilterOpt.getView());
571     String filterTitle = mainFrame.getTitle();
572     mainFrame.setTitle(frameTitle);
573     chk_invertFilter.setVisible(false);
574     if (selectedFilterOpt.getView() == VIEWS_FILTER)
575     {
576       mainFrame.setTitle(filterTitle);
577       chk_invertFilter.setVisible(true);
578       filterResultSet(selectedFilterOpt.getValue());
579     }
580     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
581             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
582     {
583       mainFrame.setTitle(MessageManager
584               .getString("label.structure_chooser_manual_association"));
585       idInputAssSeqPanel.loadCmbAssSeq();
586       fileChooserAssSeqPanel.loadCmbAssSeq();
587     }
588     validateSelections();
589   }
590
591   /**
592    * Validates user selection and activates the view button if all parameters
593    * are correct
594    */
595   @Override
596   public void validateSelections()
597   {
598     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
599             .getSelectedItem());
600     btn_view.setEnabled(false);
601     String currentView = selectedFilterOpt.getView();
602     if (currentView == VIEWS_FILTER)
603     {
604       if (getResultTable().getSelectedRows().length > 0)
605       {
606         btn_view.setEnabled(true);
607       }
608     }
609     else if (currentView == VIEWS_LOCAL_PDB)
610     {
611       if (tbl_local_pdb.getSelectedRows().length > 0)
612       {
613         btn_view.setEnabled(true);
614       }
615     }
616     else if (currentView == VIEWS_ENTER_ID)
617     {
618       validateAssociationEnterPdb();
619     }
620     else if (currentView == VIEWS_FROM_FILE)
621     {
622       validateAssociationFromFile();
623     }
624   }
625
626   /**
627    * Validates inputs from the Manual PDB entry panel
628    */
629   public void validateAssociationEnterPdb()
630   {
631     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
632             .getCmb_assSeq().getSelectedItem();
633     lbl_pdbManualFetchStatus.setIcon(errorImage);
634     lbl_pdbManualFetchStatus.setToolTipText("");
635     if (txt_search.getText().length() > 0)
636     {
637       lbl_pdbManualFetchStatus
638               .setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager
639                       .formatMessage("info.no_pdb_entry_found_for",
640                               txt_search.getText())));
641     }
642
643     if (errorWarning.length() > 0)
644     {
645       lbl_pdbManualFetchStatus.setIcon(warningImage);
646       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(
647               true, errorWarning.toString()));
648     }
649
650     if (selectedSequences.length == 1
651             || !assSeqOpt.getName().equalsIgnoreCase(
652                     "-Select Associated Seq-"))
653     {
654       txt_search.setEnabled(true);
655       if (isValidPBDEntry)
656       {
657         btn_view.setEnabled(true);
658         lbl_pdbManualFetchStatus.setToolTipText("");
659         lbl_pdbManualFetchStatus.setIcon(goodImage);
660       }
661     }
662     else
663     {
664       txt_search.setEnabled(false);
665       lbl_pdbManualFetchStatus.setIcon(errorImage);
666     }
667   }
668
669   /**
670    * Validates inputs for the manual PDB file selection options
671    */
672   public void validateAssociationFromFile()
673   {
674     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
675             .getCmb_assSeq().getSelectedItem();
676     lbl_fromFileStatus.setIcon(errorImage);
677     if (selectedSequences.length == 1
678             || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
679                     "-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 long progressSessionId = System.currentTimeMillis();
729     final StructureSelectionManager ssm = ap.getStructureSelectionManager();
730     final int preferredHeight = pnl_filter.getHeight();
731     ssm.setProgressIndicator(this);
732     ssm.setProgressSessionId(progressSessionId);
733     new Thread(new Runnable()
734     {
735       @Override
736       public void run()
737       {
738         FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
739                 .getSelectedItem());
740         String currentView = selectedFilterOpt.getView();
741         if (currentView == VIEWS_FILTER)
742         {
743           int pdbIdColIndex = getResultTable().getColumn("PDB Id")
744                   .getModelIndex();
745           int refSeqColIndex = getResultTable().getColumn("Ref Sequence")
746                   .getModelIndex();
747           int[] selectedRows = getResultTable().getSelectedRows();
748           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
749           int count = 0;
750           ArrayList<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
751           for (int row : selectedRows)
752           {
753             String pdbIdStr = getResultTable().getValueAt(row,
754                     pdbIdColIndex).toString();
755             SequenceI selectedSeq = (SequenceI) getResultTable()
756                     .getValueAt(row, refSeqColIndex);
757             selectedSeqsToView.add(selectedSeq);
758             PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
759             if (pdbEntry == null)
760             {
761               pdbEntry = getFindEntry(pdbIdStr,
762                       selectedSeq.getAllPDBEntries());
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           ArrayList<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
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.getValueAt(
793                     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
809           String pdbIdStr = txt_search.getText();
810           PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
811           if (pdbEntry == null)
812           {
813             pdbEntry = new PDBEntry();
814             if (pdbIdStr.split(":").length > 1)
815             {
816               pdbEntry.setId(pdbIdStr.split(":")[0]);
817               pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
818             }
819             else
820             {
821               pdbEntry.setId(pdbIdStr);
822             }
823             pdbEntry.setType(PDBEntry.Type.PDB);
824             selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
825           }
826
827           PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
828           launchStructureViewer(ssm, pdbEntriesToView, ap,
829                   new SequenceI[] { 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                           jalview.io.AppletFormatAdapter.FILE,
842                           selectedSequence, true, Desktop.instance);
843
844           launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap,
845                   new SequenceI[] { selectedSequence });
846         }
847         closeAction(preferredHeight);
848       }
849     }).start();
850   }
851
852   private PDBEntry getFindEntry(String id, Vector<PDBEntry> pdbEntries)
853   {
854     Objects.requireNonNull(id);
855     Objects.requireNonNull(pdbEntries);
856     PDBEntry foundEntry = null;
857     for (PDBEntry entry : pdbEntries)
858     {
859       if (entry.getId().equalsIgnoreCase(id))
860       {
861         return entry;
862       }
863     }
864     return foundEntry;
865   }
866
867   private void launchStructureViewer(StructureSelectionManager ssm,
868           final PDBEntry[] pdbEntriesToView,
869           final AlignmentPanel alignPanel, SequenceI[] sequences)
870   {
871     ssm.setProgressBar(MessageManager
872             .getString("status.launching_3d_structure_viewer"));
873     final StructureViewer sViewer = new StructureViewer(ssm);
874
875     if (SiftsSettings.isMapWithSifts())
876     {
877       List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
878       int p = 0;
879       // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
880       // real PDB ID. For moment, we can also safely do this if there is already
881       // a known mapping between the PDBEntry and the sequence.
882       for (SequenceI seq : sequences)
883       {
884         PDBEntry pdbe = pdbEntriesToView[p++];
885         if (pdbe != null && pdbe.getFile() != null)
886         {
887           StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
888           if (smm != null && smm.length > 0)
889           {
890             for (StructureMapping sm : smm)
891             {
892               if (sm.getSequence() == seq)
893               {
894                 continue;
895               }
896             }
897           }
898         }
899         if (seq.getPrimaryDBRefs().size() == 0)
900         {
901             seqsWithoutSourceDBRef.add(seq);
902             continue;
903           }
904       }
905       if (!seqsWithoutSourceDBRef.isEmpty())
906       {
907         int y = seqsWithoutSourceDBRef.size();
908         ssm.setProgressBar(null);
909         ssm.setProgressBar(MessageManager.formatMessage(
910                 "status.fetching_dbrefs_for_sequences_without_valid_refs",
911                 y));
912         SequenceI[] seqWithoutSrcDBRef = new SequenceI[y];
913         int x = 0;
914         for (SequenceI fSeq : seqsWithoutSourceDBRef)
915         {
916           seqWithoutSrcDBRef[x++] = fSeq;
917         }
918         DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
919         dbRefFetcher.fetchDBRefs(true);
920       }
921     }
922     if (pdbEntriesToView.length > 1)
923     {
924       ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
925       for (SequenceI seq : sequences)
926       {
927         seqsMap.add(new SequenceI[] { seq });
928       }
929       SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
930       ssm.setProgressBar(null);
931       ssm.setProgressBar(MessageManager
932               .getString("status.fetching_3d_structures_for_selected_entries"));
933       sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
934     }
935     else
936     {
937       ssm.setProgressBar(null);
938       ssm.setProgressBar(MessageManager.formatMessage(
939               "status.fetching_3d_structures_for",
940               pdbEntriesToView[0].getId()));
941       sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
942     }
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, JLabel lbl_associateSeq)
952   {
953     cmb_assSeq.removeAllItems();
954     cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
955             null));
956     lbl_associateSeq.setVisible(false);
957     if (selectedSequences.length > 1)
958     {
959       for (SequenceI seq : selectedSequences)
960       {
961         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
962       }
963     }
964     else
965     {
966       String seqName = selectedSequence.getDisplayId(false);
967       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
968       lbl_associateSeq.setText(seqName);
969       lbl_associateSeq.setVisible(true);
970       cmb_assSeq.setVisible(false);
971     }
972   }
973
974   public boolean isStructuresDiscovered()
975   {
976     return discoveredStructuresSet != null
977             && !discoveredStructuresSet.isEmpty();
978   }
979
980   public Collection<FTSData> getDiscoveredStructuresSet()
981   {
982     return discoveredStructuresSet;
983   }
984
985   @Override
986   protected void txt_search_ActionPerformed()
987   {
988     new Thread()
989     {
990       @Override
991       public void run()
992       {
993         errorWarning.setLength(0);
994         isValidPBDEntry = false;
995         if (txt_search.getText().length() > 0)
996         {
997           String searchTerm = txt_search.getText().toLowerCase();
998           searchTerm = searchTerm.split(":")[0];
999           // System.out.println(">>>>> search term : " + searchTerm);
1000           List<FTSDataColumnI> wantedFields = new ArrayList<FTSDataColumnI>();
1001           FTSRestRequest pdbRequest = new FTSRestRequest();
1002           pdbRequest.setAllowEmptySeq(false);
1003           pdbRequest.setResponseSize(1);
1004           pdbRequest.setFieldToSearchBy("(pdb_id:");
1005           pdbRequest.setWantedFields(wantedFields);
1006           pdbRequest
1007 .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(((FilterOption) cmb_filterOption
1046                   .getSelectedItem()).getValue());
1047         }
1048       });
1049       refreshThread.start();
1050     }
1051   }
1052
1053   public class PDBEntryTableModel extends AbstractTableModel
1054   {
1055     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
1056
1057     private List<CachedPDB> pdbEntries;
1058
1059     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1060     {
1061       this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
1062     }
1063
1064     @Override
1065     public String getColumnName(int columnIndex)
1066     {
1067       return columns[columnIndex];
1068     }
1069
1070     @Override
1071     public int getRowCount()
1072     {
1073       return pdbEntries.size();
1074     }
1075
1076     @Override
1077     public int getColumnCount()
1078     {
1079       return columns.length;
1080     }
1081
1082     @Override
1083     public boolean isCellEditable(int row, int column)
1084     {
1085       return false;
1086     }
1087
1088     @Override
1089     public Object getValueAt(int rowIndex, int columnIndex)
1090     {
1091       Object value = "??";
1092       CachedPDB entry = pdbEntries.get(rowIndex);
1093       switch (columnIndex)
1094       {
1095       case 0:
1096         value = entry.getSequence();
1097         break;
1098       case 1:
1099         value = entry.getPdbEntry();
1100         break;
1101       case 2:
1102         value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
1103                 .getPdbEntry().getChainCode();
1104         break;
1105       case 3:
1106         value = entry.getPdbEntry().getType();
1107         break;
1108       case 4:
1109         value = entry.getPdbEntry().getFile();
1110         break;
1111       }
1112       return value;
1113     }
1114
1115     @Override
1116     public Class<?> getColumnClass(int columnIndex)
1117     {
1118       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1119     }
1120
1121     public CachedPDB getPDBEntryAt(int row)
1122     {
1123       return pdbEntries.get(row);
1124     }
1125
1126   }
1127
1128   private class CachedPDB
1129   {
1130     private SequenceI sequence;
1131
1132     private PDBEntry pdbEntry;
1133
1134     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1135     {
1136       this.sequence = sequence;
1137       this.pdbEntry = pdbEntry;
1138     }
1139
1140     public SequenceI getSequence()
1141     {
1142       return sequence;
1143     }
1144
1145     public PDBEntry getPdbEntry()
1146     {
1147       return pdbEntry;
1148     }
1149
1150   }
1151
1152   private IProgressIndicator progressBar;
1153
1154   @Override
1155   public void setProgressBar(String message, long id)
1156   {
1157     progressBar.setProgressBar(message, id);
1158   }
1159
1160   @Override
1161   public void registerHandler(long id, IProgressIndicatorHandler handler)
1162   {
1163     progressBar.registerHandler(id, handler);
1164   }
1165
1166   @Override
1167   public boolean operationInProgress()
1168   {
1169     return progressBar.operationInProgress();
1170   }
1171 }