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