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