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