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