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