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