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