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