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