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