JAL-1668 house keeping
[jalview.git] / src / jalview / gui / StructureChooser.java
1 /*
2
3  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
4  * Copyright (C) 2014 The Jalview Authors
5  * 
6  * This file is part of Jalview.
7  * 
8  * Jalview is free software: you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License 
10  * as published by the Free Software Foundation, either version 3
11  * of the License, or (at your option) any later version.
12  *  
13  * Jalview is distributed in the hope that it will be useful, but 
14  * WITHOUT ANY WARRANTY; without even the implied warranty 
15  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
16  * PURPOSE.  See the GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
20  * The Jalview Authors are detailed in the 'AUTHORS' file.
21  */
22
23 package jalview.gui;
24
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.PDBEntry;
27 import jalview.datamodel.SequenceI;
28 import jalview.jbgui.GStructureChooser;
29 import jalview.jbgui.PDBDocFieldPreferences;
30 import jalview.structure.StructureSelectionManager;
31 import jalview.util.MessageManager;
32 import jalview.ws.dbsources.PDBRestClient;
33 import jalview.ws.dbsources.PDBRestClient.PDBDocField;
34 import jalview.ws.uimodel.PDBRestRequest;
35 import jalview.ws.uimodel.PDBRestResponse;
36 import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary;
37
38 import java.awt.event.ItemEvent;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.HashSet;
42 import java.util.LinkedHashSet;
43 import java.util.List;
44
45 import javax.swing.JCheckBox;
46 import javax.swing.JComboBox;
47 import javax.swing.JLabel;
48 import javax.swing.JOptionPane;
49 import javax.swing.table.AbstractTableModel;
50
51 /**
52  * Provides the behaviors for the Structure chooser Panel
53  * 
54  * @author tcnofoegbu
55  *
56  */
57 @SuppressWarnings("serial")
58 public class StructureChooser extends GStructureChooser
59 {
60   private boolean structuresDiscovered = false;
61
62   private SequenceI selectedSequence;
63
64   private SequenceI[] selectedSequences;
65
66   private IProgressIndicator progressIndicator;
67
68   private Collection<PDBResponseSummary> discoveredStructuresSet;
69
70   private PDBRestRequest lastPdbRequest;
71
72   private PDBRestClient pdbRestCleint;
73
74   private String selectedPdbFileName;
75
76   private boolean isValidPBDEntry;
77
78
79   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
80           AlignmentPanel ap)
81   {
82     this.ap = ap;
83     this.selectedSequence = selectedSeq;
84     this.selectedSequences = selectedSeqs;
85     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
86     init();
87   }
88
89   /**
90    * Initializes parameters used by the Structure Chooser Panel
91    */
92   public void init()
93   {
94     Thread discoverPDBStructuresThread = new Thread(new Runnable()
95     {
96       @Override
97       public void run()
98       {
99         long startTime = System.currentTimeMillis();
100         updateProgressIndicator(MessageManager
101                 .getString("status.loading_cached_pdb_entries"), startTime);
102         loadLocalCachedPDBEntries();
103         updateProgressIndicator(null, startTime);
104         updateProgressIndicator(MessageManager
105                 .getString("status.searching_for_pdb_structures"),
106                 startTime);
107         fetchStructuresMetaData();
108         populateFilterComboBox();
109         updateProgressIndicator(null, startTime);
110         mainFrame.setVisible(true);
111         updateCurrentView();
112       }
113     });
114     discoverPDBStructuresThread.start();
115   }
116
117   /**
118    * Updates the progress indicator with the specified message
119    * 
120    * @param message
121    *          displayed message for the operation
122    * @param id
123    *          unique handle for this indicator
124    */
125   public void updateProgressIndicator(String message, long id)
126   {
127     if (progressIndicator != null)
128     {
129       progressIndicator.setProgressBar(message, id);
130     }
131   }
132
133   /**
134    * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
135    * selection group
136    */
137   public void fetchStructuresMetaData()
138   {
139     long startTime = System.currentTimeMillis();
140     Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
141             .getStructureSummaryFields();
142
143     discoveredStructuresSet = new LinkedHashSet<PDBResponseSummary>();
144     HashSet<String> errors = new HashSet<String>();
145     for (SequenceI seq : selectedSequences)
146     {
147       PDBRestRequest pdbRequest = new PDBRestRequest();
148       pdbRequest.setAllowEmptySeq(false);
149       pdbRequest.setResponseSize(500);
150       pdbRequest.setFieldToSearchBy("(text:");
151       pdbRequest.setWantedFields(wantedFields);
152       pdbRequest.setSearchTerm(buildQuery(seq) + ")");
153       pdbRequest.setAssociatedSequence(seq);
154       pdbRestCleint = new PDBRestClient();
155       PDBRestResponse resultList;
156       try
157       {
158         resultList = pdbRestCleint.executeRequest(pdbRequest);
159       } catch (Exception e)
160       {
161         e.printStackTrace();
162         errors.add(e.getMessage());
163         continue;
164       }
165       lastPdbRequest = pdbRequest;
166       if (resultList.getSearchSummary() != null
167               && !resultList.getSearchSummary().isEmpty())
168       {
169         discoveredStructuresSet.addAll(resultList.getSearchSummary());
170       }
171     }
172
173     int noOfStructuresFound = 0;
174     String totalTime = (System.currentTimeMillis() - startTime)
175             + " milli secs";
176     if (discoveredStructuresSet != null
177             && !discoveredStructuresSet.isEmpty())
178     {
179       tbl_summary.setModel(PDBRestResponse.getTableModel(lastPdbRequest,
180               discoveredStructuresSet));
181       structuresDiscovered = true;
182       noOfStructuresFound = discoveredStructuresSet.size();
183       mainFrame.setTitle(MessageManager.formatMessage(
184               "label.structure_chooser_no_of_structures",
185               noOfStructuresFound, totalTime));
186     }
187     else
188     {
189       mainFrame.setTitle(MessageManager
190               .getString("label.structure_chooser_manual_association"));
191       if (errors.size() > 0)
192       {
193         StringBuilder errorMsg = new StringBuilder();
194         for (String error : errors)
195         {
196           errorMsg.append(error).append("\n");
197         }
198         JOptionPane.showMessageDialog(this, errorMsg.toString(),
199                 MessageManager.getString("label.pdb_web-service_error"),
200                 JOptionPane.ERROR_MESSAGE);
201       }
202     }
203   }
204
205   public void loadLocalCachedPDBEntries()
206   {
207     ArrayList<CachedPDB> entries = new ArrayList<CachedPDB>();
208     for (SequenceI seq : selectedSequences)
209     {
210       if (seq.getDatasetSequence() != null
211               && seq.getDatasetSequence().getAllPDBEntries() != null)
212       {
213         for (PDBEntry pdbEntry : seq.getDatasetSequence().getAllPDBEntries())
214         {
215           if (pdbEntry.getFile() != null)
216           {
217             entries.add(new CachedPDB(seq, pdbEntry));
218           }
219         }
220       }
221     }
222
223     PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
224     tbl_local_pdb.setModel(tableModelx);
225   }
226
227
228   /**
229    * Builds a query string for a given sequences using its DBRef entries
230    * 
231    * @param seq
232    *          the sequences to build a query for
233    * @return the built query string
234    */
235
236   public static String buildQuery(SequenceI seq)
237   {
238     HashSet<String> seqRefs = new LinkedHashSet<String>();
239     String seqName = seq.getName();
240     String[] names = seqName.toLowerCase().split("\\|");
241     for (String name : names)
242     {
243       // System.out.println("Found name : " + name);
244       name.trim();
245       if (isValidSeqName(name))
246       {
247         seqRefs.add(name);
248       }
249     }
250
251     if (seq.getAllPDBEntries() != null)
252     {
253       for (PDBEntry entry : seq.getAllPDBEntries())
254       {
255         if (isValidSeqName(entry.getId()))
256         {
257           seqRefs.add(entry.getId());
258         }
259       }
260     }
261
262     if (seq.getDBRef() != null && seq.getDBRef().length != 0)
263     {
264       int count = 0;
265       for (DBRefEntry dbRef : seq.getDBRef())
266       {
267         if (isValidSeqName(getDBRefId(dbRef)))
268         {
269           seqRefs.add(getDBRefId(dbRef));
270         }
271         ++count;
272         if (count > 10)
273         {
274           break;
275         }
276       }
277     }
278
279     StringBuilder queryBuilder = new StringBuilder();
280     for (String seqRef : seqRefs)
281     {
282       queryBuilder.append("text:").append(seqRef).append(" OR ");
283     }
284     int endIndex = queryBuilder.lastIndexOf(" OR ");
285
286     if (queryBuilder.toString().length() < 6)
287     {
288       return null;
289     }
290     String query = queryBuilder.toString().substring(5, endIndex);
291     return query;
292   }
293
294   /**
295    * Ensures sequence ref names are not less than 3 characters and does not
296    * contain a database name
297    * 
298    * @param seqName
299    * @return
300    */
301   public static boolean isValidSeqName(String seqName)
302   {
303     // System.out.println("seqName : " + seqName);
304     String ignoreList = "pdb,uniprot,swiss-prot";
305     if (seqName.length() < 3)
306     {
307       return false;
308     }
309     if (seqName.contains(":"))
310     {
311       return false;
312     }
313     seqName = seqName.toLowerCase();
314     for (String ignoredEntry : ignoreList.split(","))
315     {
316       if (seqName.contains(ignoredEntry))
317       {
318         return false;
319       }
320     }
321     return true;
322   }
323
324   public static String getDBRefId(DBRefEntry dbRef)
325   {
326     String ref = dbRef.getAccessionId().replaceAll("GO:", "");
327     return ref;
328   }
329
330   /**
331    * Filters a given list of discovered structures based on supplied argument
332    * 
333    * @param fieldToFilterBy
334    *          the field to filter by
335    */
336   public void filterResultSet(final String fieldToFilterBy)
337   {
338     Thread filterThread = new Thread(new Runnable()
339     {
340       @Override
341       public void run()
342       {
343         long startTime = System.currentTimeMillis();
344         lbl_loading.setVisible(true);
345         Collection<PDBDocField> wantedFields = PDBDocFieldPreferences
346                 .getStructureSummaryFields();
347         Collection<PDBResponseSummary> filteredResponse = new HashSet<PDBResponseSummary>();
348         HashSet<String> errors = new HashSet<String>();
349         for (SequenceI seq : selectedSequences)
350         {
351           PDBRestRequest pdbRequest = new PDBRestRequest();
352           pdbRequest.setAllowEmptySeq(false);
353           pdbRequest.setResponseSize(1);
354           pdbRequest.setFieldToSearchBy("(text:");
355           pdbRequest.setFieldToSortBy(fieldToFilterBy,
356                   !chk_invertFilter.isSelected());
357           pdbRequest.setSearchTerm(buildQuery(seq) + ")");
358           pdbRequest.setWantedFields(wantedFields);
359           pdbRequest.setAssociatedSequence(seq);
360           pdbRestCleint = new PDBRestClient();
361           PDBRestResponse resultList;
362           try
363           {
364             resultList = pdbRestCleint.executeRequest(pdbRequest);
365           } catch (Exception e)
366           {
367             e.printStackTrace();
368             errors.add(e.getMessage());
369             continue;
370           }
371           lastPdbRequest = pdbRequest;
372           if (resultList.getSearchSummary() != null
373                   && !resultList.getSearchSummary().isEmpty())
374           {
375             filteredResponse.addAll(resultList.getSearchSummary());
376           }
377         }
378
379         String totalTime = (System.currentTimeMillis() - startTime)
380                 + " milli secs";
381         if (!filteredResponse.isEmpty())
382         {
383           final int filterResponseCount = filteredResponse.size();
384           Collection<PDBResponseSummary> reorderedStructuresSet = new LinkedHashSet<PDBResponseSummary>();
385           reorderedStructuresSet.addAll(filteredResponse);
386           reorderedStructuresSet.addAll(discoveredStructuresSet);
387           tbl_summary.setModel(PDBRestResponse.getTableModel(
388                   lastPdbRequest, reorderedStructuresSet));
389
390           // Update table selection model here
391           tbl_summary.addRowSelectionInterval(0, filterResponseCount - 1);
392           mainFrame.setTitle(MessageManager.formatMessage(
393                   "label.structure_chooser_filter_time",
394  totalTime));
395         }
396         else
397         {
398           mainFrame.setTitle(MessageManager.formatMessage(
399                   "label.structure_chooser_filter_time",
400  totalTime));
401           if (errors.size() > 0)
402           {
403             StringBuilder errorMsg = new StringBuilder();
404             for (String error : errors)
405             {
406               errorMsg.append(error).append("\n");
407             }
408             JOptionPane.showMessageDialog(null, errorMsg.toString(),
409                     MessageManager.getString("label.pdb_web-service_error"),
410                     JOptionPane.ERROR_MESSAGE);
411           }
412         }
413
414         lbl_loading.setVisible(false);
415
416         validateSelections();
417       }
418     });
419     filterThread.start();
420   }
421
422   /**
423    * Handles action event for btn_pdbFromFile
424    */
425   public void pdbFromFile_actionPerformed()
426   {
427     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
428             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
429     chooser.setFileView(new jalview.io.JalviewFileView());
430     chooser.setDialogTitle(MessageManager.formatMessage(
431             "label.select_pdb_file_for",
432             selectedSequence.getDisplayId(false)));
433     chooser.setToolTipText(MessageManager.formatMessage(
434             "label.load_pdb_file_associate_with_sequence",
435             selectedSequence.getDisplayId(false)));
436
437     int value = chooser.showOpenDialog(null);
438     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
439     {
440       selectedPdbFileName = chooser.getSelectedFile().getPath();
441       jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
442       validateSelections();
443     }
444   }
445
446   /**
447    * Populates the filter combo-box options dynamically depending on discovered
448    * structures
449    */
450   protected void populateFilterComboBox()
451   {
452     if (isStructuresDiscovered())
453     {
454       cmb_filterOption.addItem(new FilterOption("Best Quality",
455               PDBDocField.OVERALL_QUALITY.getCode(), VIEWS_FILTER));
456       cmb_filterOption.addItem(new FilterOption("Best UniProt Coverage",
457               PDBDocField.UNIPROT_COVERAGE.getCode(), VIEWS_FILTER));
458       cmb_filterOption.addItem(new FilterOption("Highest Resolution",
459               PDBDocField.RESOLUTION.getCode(), VIEWS_FILTER));
460       cmb_filterOption.addItem(new FilterOption("Highest Protein Chain",
461               PDBDocField.PROTEIN_CHAIN_COUNT.getCode(), VIEWS_FILTER));
462       cmb_filterOption.addItem(new FilterOption("Highest Bound Molecules",
463               PDBDocField.BOUND_MOLECULE_COUNT.getCode(), VIEWS_FILTER));
464       cmb_filterOption.addItem(new FilterOption("Highest Polymer Residues",
465               PDBDocField.POLYMER_RESIDUE_COUNT.getCode(), VIEWS_FILTER));
466     }
467     cmb_filterOption.addItem(new FilterOption("Enter PDB Id", "-",
468             VIEWS_ENTER_ID));
469     cmb_filterOption.addItem(new FilterOption("From File", "-",
470             VIEWS_FROM_FILE));
471     cmb_filterOption.addItem(new FilterOption("Cached PDB Entries", "-",
472             VIEWS_LOCAL_PDB));
473   }
474
475   /**
476    * Updates the displayed view based on the selected filter option
477    */
478   protected void updateCurrentView()
479   {
480     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
481             .getSelectedItem());
482     layout_switchableViews.show(pnl_switchableViews,
483             selectedFilterOpt.getView());
484     String filterTitle = mainFrame.getTitle();
485     mainFrame.setTitle(frameTitle);
486     chk_invertFilter.setVisible(false);
487     if (selectedFilterOpt.getView() == VIEWS_FILTER)
488     {
489       mainFrame.setTitle(filterTitle);
490       chk_invertFilter.setVisible(true);
491       filterResultSet(selectedFilterOpt.getValue());
492     }
493     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
494             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
495     {
496       mainFrame.setTitle(MessageManager
497               .getString("label.structure_chooser_manual_association"));
498       idInputAssSeqPanel.loadCmbAssSeq();
499       fileChooserAssSeqPanel.loadCmbAssSeq();
500     }
501     validateSelections();
502   }
503
504   /**
505    * Validates user selection and activates the view button if all parameters
506    * are correct
507    */
508   public void validateSelections()
509   {
510     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
511             .getSelectedItem());
512     btn_view.setEnabled(false);
513     String currentView = selectedFilterOpt.getView();
514     if (currentView == VIEWS_FILTER)
515     {
516       if (tbl_summary.getSelectedRows().length > 0)
517       {
518         btn_view.setEnabled(true);
519       }
520     }
521     else if (currentView == VIEWS_LOCAL_PDB)
522     {
523       if (tbl_local_pdb.getSelectedRows().length > 0)
524       {
525         btn_view.setEnabled(true);
526       }
527     }
528     else if (currentView == VIEWS_ENTER_ID)
529     {
530       validateAssociationEnterPdb();
531     }
532     else if (currentView == VIEWS_FROM_FILE)
533     {
534       validateAssociationFromFile();
535     }
536   }
537
538   /**
539    * Validates inputs from the Manual PDB entry panel
540    */
541   public void validateAssociationEnterPdb()
542   {
543     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
544             .getCmb_assSeq().getSelectedItem();
545     lbl_pdbManualFetchStatus.setIcon(errorImage);
546     lbl_pdbManualFetchStatus.setToolTipText("");
547     if (txt_search.getText().length() > 0)
548     {
549       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(
550               true, MessageManager.formatMessage(
551                       "info.no_pdb_entry_found_for",
552                               txt_search.getText())));
553     }
554
555     if (errorWarning.length() > 0)
556     {
557       lbl_pdbManualFetchStatus.setIcon(warningImage);
558       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(
559               true, errorWarning.toString()));
560     }
561
562     if (selectedSequences.length == 1
563             || !assSeqOpt.getName().equalsIgnoreCase(
564                     "-Select Associated Seq-"))
565     {
566       txt_search.setEnabled(true);
567       if (isValidPBDEntry)
568       {
569         btn_view.setEnabled(true);
570         lbl_pdbManualFetchStatus.setToolTipText("");
571         lbl_pdbManualFetchStatus.setIcon(goodImage);
572       }
573     }
574     else
575     {
576       txt_search.setEnabled(false);
577       lbl_pdbManualFetchStatus.setIcon(errorImage);
578     }
579   }
580
581   /**
582    * Validates inputs for the manual PDB file selection options
583    */
584   public void validateAssociationFromFile()
585   {
586     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
587             .getCmb_assSeq().getSelectedItem();
588     lbl_fromFileStatus.setIcon(errorImage);
589     if (selectedSequences.length == 1
590             || (assSeqOpt != null && !assSeqOpt.getName().equalsIgnoreCase(
591                     "-Select Associated Seq-")))
592     {
593       btn_pdbFromFile.setEnabled(true);
594       if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
595       {
596         btn_view.setEnabled(true);
597         lbl_fromFileStatus.setIcon(goodImage);
598       }
599     }
600     else
601     {
602       btn_pdbFromFile.setEnabled(false);
603       lbl_fromFileStatus.setIcon(errorImage);
604     }
605   }
606
607   @Override
608   public void cmbAssSeqStateChanged()
609   {
610     validateSelections();
611   }
612
613   /**
614    * Handles the state change event for the 'filter' combo-box and 'invert'
615    * check-box
616    */
617   @Override
618   protected void stateChanged(ItemEvent e)
619   {
620     if (e.getSource() instanceof JCheckBox)
621     {
622       updateCurrentView();
623     }
624     else
625     {
626       if (e.getStateChange() == ItemEvent.SELECTED)
627       {
628         updateCurrentView();
629       }
630     }
631
632   }
633
634   /**
635    * Handles action event for btn_ok
636    */
637   @Override
638   public void ok_ActionPerformed()
639   {
640     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
641             .getSelectedItem());
642     String currentView = selectedFilterOpt.getView();
643     if (currentView == VIEWS_FILTER)
644     {
645       int pdbIdColIndex = tbl_summary.getColumn(
646               PDBRestClient.PDBDocField.PDB_ID.getName()).getModelIndex();
647       int refSeqColIndex = tbl_summary.getColumn("Ref Sequence")
648               .getModelIndex();
649       int[] selectedRows = tbl_summary.getSelectedRows();
650       PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
651       int count = 0;
652       ArrayList<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
653       for (int row : selectedRows)
654       {
655         String pdbIdStr = tbl_summary.getValueAt(row, pdbIdColIndex)
656                 .toString();
657         SequenceI selectedSeq = (SequenceI) tbl_summary.getValueAt(row,
658                 refSeqColIndex);
659         selectedSeqsToView.add(selectedSeq);
660         PDBEntry pdbEntry = selectedSeq.getPDBEntry(pdbIdStr);
661         if (pdbEntry == null)
662         {
663           pdbEntry = new PDBEntry();
664           pdbEntry.setId(pdbIdStr);
665           pdbEntry.setType(PDBEntry.Type.PDB);
666           selectedSeq.getDatasetSequence().addPDBId(pdbEntry);
667         }
668         pdbEntriesToView[count++] = pdbEntry;
669       }
670       SequenceI[] selectedSeqs = selectedSeqsToView
671               .toArray(new SequenceI[selectedSeqsToView.size()]);
672       launchStructureViewer(ap.getStructureSelectionManager(),
673               pdbEntriesToView, ap, selectedSeqs);
674     }
675     else if (currentView == VIEWS_LOCAL_PDB)
676     {
677       int[] selectedRows = tbl_local_pdb.getSelectedRows();
678       PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
679       int count = 0;
680       int pdbIdColIndex = tbl_local_pdb.getColumn(
681               PDBRestClient.PDBDocField.PDB_ID.getName()).getModelIndex();
682       int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
683               .getModelIndex();
684       ArrayList<SequenceI> selectedSeqsToView = new ArrayList<SequenceI>();
685       for (int row : selectedRows)
686       {
687         PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
688                 pdbIdColIndex);
689         pdbEntriesToView[count++] = pdbEntry;
690         SequenceI selectedSeq = (SequenceI) tbl_local_pdb.getValueAt(row,
691                 refSeqColIndex);
692         selectedSeqsToView.add(selectedSeq);
693       }
694       SequenceI[] selectedSeqs = selectedSeqsToView
695               .toArray(new SequenceI[selectedSeqsToView.size()]);
696       launchStructureViewer(ap.getStructureSelectionManager(),
697               pdbEntriesToView, ap, selectedSeqs);
698     }
699     else if (currentView == VIEWS_ENTER_ID)
700     {
701       SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
702               .getCmb_assSeq().getSelectedItem()).getSequence();
703       if (userSelectedSeq != null)
704       {
705         selectedSequence = userSelectedSeq;
706       }
707
708       String pdbIdStr = txt_search.getText();
709       PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
710       if (pdbEntry == null)
711       {
712         pdbEntry = new PDBEntry();
713         pdbEntry.setId(pdbIdStr);
714         pdbEntry.setType(PDBEntry.Type.PDB);
715         selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
716       }
717
718       PDBEntry[] pdbEntriesToView = new PDBEntry[]
719       { pdbEntry };
720       launchStructureViewer(ap.getStructureSelectionManager(),
721               pdbEntriesToView, ap, new SequenceI[]
722               { selectedSequence });
723     }
724     else if (currentView == VIEWS_FROM_FILE)
725     {
726       SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
727               .getCmb_assSeq().getSelectedItem()).getSequence();
728       if (userSelectedSeq != null)
729       {
730         selectedSequence = userSelectedSeq;
731       }
732       PDBEntry fileEntry = new AssociatePdbFileWithSeq()
733               .associatePdbWithSeq(selectedPdbFileName,
734                       jalview.io.AppletFormatAdapter.FILE,
735                       selectedSequence, true, Desktop.instance);
736
737       launchStructureViewer(ap.getStructureSelectionManager(),
738               new PDBEntry[]
739               { fileEntry }, ap, new SequenceI[]
740               { selectedSequence });
741     }
742     mainFrame.dispose();
743   }
744
745   private void launchStructureViewer(final StructureSelectionManager ssm,
746           final PDBEntry[] pdbEntriesToView,
747           final AlignmentPanel alignPanel, final SequenceI[] sequences)
748   {
749     final StructureViewer sViewer = new StructureViewer(ssm);
750     new Thread(new Runnable()
751     {
752       public void run()
753       {
754         if (pdbEntriesToView.length > 1)
755         {
756           ArrayList<SequenceI[]> seqsMap = new ArrayList<SequenceI[]>();
757           for (SequenceI seq : sequences)
758           {
759             seqsMap.add(new SequenceI[]
760             { seq });
761           }
762           SequenceI[][] collatedSeqs = seqsMap.toArray(new SequenceI[0][0]);
763           sViewer.viewStructures(pdbEntriesToView, collatedSeqs, alignPanel);
764         }
765         else
766         {
767           sViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
768         }
769       }
770     }).start();
771   }
772
773   /**
774    * Populates the combo-box used in associating manually fetched structures to
775    * a unique sequence when more than one sequence selection is made.
776    */
777   public void populateCmbAssociateSeqOptions(
778           JComboBox<AssociateSeqOptions> cmb_assSeq, JLabel lbl_associateSeq)
779   {
780     cmb_assSeq.removeAllItems();
781     cmb_assSeq.addItem(new AssociateSeqOptions("-Select Associated Seq-",
782             null));
783     lbl_associateSeq.setVisible(false);
784     if (selectedSequences.length > 1)
785     {
786       for (SequenceI seq : selectedSequences)
787       {
788         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
789       }
790     }
791     else
792     {
793       String seqName = selectedSequence.getDisplayId(false);
794       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
795       lbl_associateSeq.setText(seqName);
796       lbl_associateSeq.setVisible(true);
797       cmb_assSeq.setVisible(false);
798     }
799   }
800
801   public boolean isStructuresDiscovered()
802   {
803     return structuresDiscovered;
804   }
805
806   public void setStructuresDiscovered(boolean structuresDiscovered)
807   {
808     this.structuresDiscovered = structuresDiscovered;
809   }
810
811   public Collection<PDBResponseSummary> getDiscoveredStructuresSet()
812   {
813     return discoveredStructuresSet;
814   }
815
816   @Override
817   protected void txt_search_ActionPerformed()
818   {
819     new Thread()
820     {
821       public void run()
822       {
823     errorWarning.setLength(0);
824     isValidPBDEntry = false;
825     if (txt_search.getText().length() > 0)
826     {
827       List<PDBDocField> wantedFields = new ArrayList<PDBDocField>();
828       wantedFields.add(PDBDocField.PDB_ID);
829       PDBRestRequest pdbRequest = new PDBRestRequest();
830       pdbRequest.setAllowEmptySeq(false);
831       pdbRequest.setResponseSize(1);
832       pdbRequest.setFieldToSearchBy("(pdb_id:");
833       pdbRequest.setWantedFields(wantedFields);
834       pdbRequest.setSearchTerm(txt_search.getText() + ")");
835       pdbRequest.setAssociatedSequence(selectedSequence);
836       pdbRestCleint = new PDBRestClient();
837       PDBRestResponse resultList;
838       try
839       {
840         resultList = pdbRestCleint.executeRequest(pdbRequest);
841       } catch (Exception e)
842       {
843         errorWarning.append(e.getMessage());
844         return;
845       } finally
846       {
847         validateSelections();
848       }
849       if (resultList.getSearchSummary() != null
850               && resultList.getSearchSummary().size() > 0)
851       {
852         isValidPBDEntry = true;
853       }
854     }
855     validateSelections();
856       }
857     }.start();
858   }
859
860   @Override
861   public void tabRefresh()
862   {
863     if (selectedSequences != null)
864     {
865       Thread refreshThread = new Thread(new Runnable()
866       {
867         @Override
868         public void run()
869         {
870           fetchStructuresMetaData();
871           filterResultSet(((FilterOption) cmb_filterOption
872                   .getSelectedItem()).getValue());
873         }
874       });
875       refreshThread.start();
876     }
877   }
878
879   public class PDBEntryTableModel extends AbstractTableModel
880   {
881     String[] columns =
882     { "Ref Sequence", "PDB Id", "Chain", "Type", "File" };
883
884     private List<CachedPDB> pdbEntries;
885
886     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
887     {
888       this.pdbEntries = new ArrayList<CachedPDB>(pdbEntries);
889     }
890
891     @Override
892     public String getColumnName(int columnIndex)
893     {
894       return columns[columnIndex];
895     }
896
897     @Override
898     public int getRowCount()
899     {
900       return pdbEntries.size();
901     }
902
903     @Override
904     public int getColumnCount()
905     {
906       return columns.length;
907     }
908
909     @Override
910     public boolean isCellEditable(int row, int column)
911     {
912       return false;
913     }
914
915     @Override
916     public Object getValueAt(int rowIndex, int columnIndex)
917     {
918       Object value = "??";
919       CachedPDB entry = pdbEntries.get(rowIndex);
920       switch (columnIndex)
921       {
922       case 0:
923         value = entry.getSequence();
924         break;
925       case 1:
926         value = entry.getPdbEntry();
927         break;
928       case 2:
929         value = entry.getPdbEntry().getChainCode() == null ? "_" : entry
930                 .getPdbEntry().getChainCode();
931         break;
932       case 3:
933         value = entry.getPdbEntry().getType();
934         break;
935       case 4:
936         value = entry.getPdbEntry().getFile();
937         break;
938       }
939       return value;
940     }
941
942     @Override
943     public Class<?> getColumnClass(int columnIndex)
944     {
945       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
946     }
947
948     public CachedPDB getPDBEntryAt(int row)
949     {
950       return pdbEntries.get(row);
951     }
952
953   }
954
955   private class CachedPDB
956   {
957     private SequenceI sequence;
958
959     private PDBEntry pdbEntry;
960
961     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
962     {
963       this.sequence = sequence;
964       this.pdbEntry = pdbEntry;
965     }
966
967     public SequenceI getSequence()
968     {
969       return sequence;
970     }
971
972     public PDBEntry getPdbEntry()
973     {
974       return pdbEntry;
975     }
976
977   }
978 }