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