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