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