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