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