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