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