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