Merge branch 'develop' into features/r2_11_2/JAL-3829_3dbeacons
[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   /**
85    * transient combo box choice for initiating 3db fetch
86    */
87   private static final String VIEWS_QUERYING_TDB = "QUERY_3DB";
88
89   private SequenceI selectedSequence;
90
91   private SequenceI[] selectedSequences;
92
93   private IProgressIndicator progressIndicator;
94
95   private Collection<FTSData> discoveredStructuresSet;
96
97   private StructureChooserQuerySource data;
98
99   @Override
100   protected FTSDataColumnPreferences getFTSDocFieldPrefs()
101   {
102     return data.getDocFieldPrefs();
103   }
104
105   private String selectedPdbFileName;
106
107   private boolean isValidPBDEntry;
108
109   private boolean cachedPDBExists;
110
111   private Collection<FTSData> lastDiscoveredStructuresSet;
112
113   private boolean canQueryTDB = false;
114
115   private boolean notQueriedTDBYet = true;
116
117   List<SequenceI> seqsWithoutSourceDBRef = null;
118
119   private static StructureViewer lastTargetedView = null;
120
121   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
122           AlignmentPanel ap)
123   {
124     // which FTS engine to use
125     data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
126     initDialog();
127
128     this.ap = ap;
129     this.selectedSequence = selectedSeq;
130     this.selectedSequences = selectedSeqs;
131     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
132     init();
133
134   }
135
136   /**
137    * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
138    * least one structure are discovered.
139    */
140   private void populateSeqsWithoutSourceDBRef()
141   {
142     seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
143     boolean needCanonical = false;
144     for (SequenceI seq : selectedSequences)
145     {
146       if (seq.isProtein())
147       {
148         int dbRef = ThreeDBStructureChooserQuerySource
149                 .checkUniprotRefs(seq.getDBRefs());
150         if (dbRef < 0)
151         {
152           if (dbRef == -1)
153           {
154             // need to retrieve canonicals
155             needCanonical = true;
156             seqsWithoutSourceDBRef.add(seq);
157           }
158           else
159           {
160             // could be a sequence with pdb ref
161             if (seq.getAllPDBEntries() == null
162                     || seq.getAllPDBEntries().size() == 0)
163             {
164               seqsWithoutSourceDBRef.add(seq);
165             }
166           }
167         }
168       }
169     }
170     // retrieve database refs for protein sequences
171     if (!seqsWithoutSourceDBRef.isEmpty())
172     {
173       canQueryTDB = true;
174       if (needCanonical)
175       {
176         notQueriedTDBYet = false;
177       }
178     }
179   };
180
181   /**
182    * Initializes parameters used by the Structure Chooser Panel
183    */
184   protected void init()
185   {
186     if (!Jalview.isHeadlessMode())
187     {
188       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
189     }
190
191     chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
192
193     Executors.defaultThreadFactory().newThread(new Runnable()
194     {
195       public void run()
196       {
197         populateSeqsWithoutSourceDBRef();
198         initialStructureDiscovery();
199       }
200
201     }).start();
202
203   }
204
205   // called by init
206   private void initialStructureDiscovery()
207   {
208     // check which FTS engine to use
209     data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
210
211     // ensure a filter option is in force for search
212     populateFilterComboBox(true, cachedPDBExists);
213
214     // looks for any existing structures already loaded
215     // for the sequences (the cached ones)
216     // then queries the StructureChooserQuerySource to
217     // discover more structures.
218     //
219     // Possible optimisation is to only begin querying
220     // the structure chooser if there are no cached structures.
221
222     long startTime = System.currentTimeMillis();
223     updateProgressIndicator(
224             MessageManager.getString("status.loading_cached_pdb_entries"),
225             startTime);
226     loadLocalCachedPDBEntries();
227     updateProgressIndicator(null, startTime);
228     updateProgressIndicator(
229             MessageManager.getString("status.searching_for_pdb_structures"),
230             startTime);
231     fetchStructuresMetaData();
232     // revise filter options if no results were found
233     populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
234     discoverStructureViews();
235     updateProgressIndicator(null, startTime);
236     mainFrame.setVisible(true);
237     updateCurrentView();
238   }
239
240   private void promptForTDBFetch()
241   {
242     final long progressId = System.currentTimeMillis();
243
244     // final action after prompting and discovering db refs
245     final Runnable strucDiscovery = new Runnable()
246     {
247       @Override
248       public void run()
249       {
250         progressBar.setProgressBar("status.searching_3d_beacons", progressId);
251         // TODO: warn if no accessions discovered
252         populateSeqsWithoutSourceDBRef();
253         // redo initial discovery - this time with 3d beacons
254         // Executors.
255         previousWantedFields=null;
256         initialStructureDiscovery();
257         if (!isStructuresDiscovered())
258         {
259           progressBar.setProgressBar("status.no_structures_discovered_from_3d_beacons", progressId);
260         } else {
261           progressBar.setProgressBar(null, progressId);
262         }
263       }
264     };
265
266     final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
267     {
268       
269       @Override
270       public void finished()
271       {
272         // filter has been selected, so we set flag to remove ourselves
273         notQueriedTDBYet = false;
274         // new thread to discover structures - via 3d beacons
275         Executors.defaultThreadFactory().newThread(strucDiscovery).start();
276         
277       }
278     };
279     
280     // fetch db refs if OK pressed
281     final Runnable discoverCanonicalDBrefs = new Runnable() 
282     {
283       @Override
284       public void run()
285       {
286         populateSeqsWithoutSourceDBRef();
287
288         final int y = seqsWithoutSourceDBRef.size();
289         if (y > 0)
290         {
291           final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
292                   .toArray(new SequenceI[y]);
293           DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
294                   progressBar, new DbSourceProxy[]
295                   { new jalview.ws.dbsources.Uniprot() }, null, false);
296           dbRefFetcher.addListener(afterDbRefFetch);
297           // ideally this would also gracefully run with callbacks
298           dbRefFetcher.fetchDBRefs(true);
299         } else {
300           // call finished action directly
301           afterDbRefFetch.finished();
302         }
303       }
304
305     };
306     final Runnable revertview = new Runnable() {
307       public void run() {
308         if (lastSelected!=null) {
309           cmb_filterOption.setSelectedItem(lastSelected);
310         }
311       };
312     };
313     // need cancel and no to result in the discoverPDB action - mocked is
314     // 'cancel'
315     JvOptionPane.newOptionDialog(this)
316             .setResponseHandler(JvOptionPane.OK_OPTION,
317                     discoverCanonicalDBrefs)
318             .setResponseHandler(JvOptionPane.CANCEL_OPTION, revertview)
319             .setResponseHandler(JvOptionPane.NO_OPTION, revertview)
320             .showDialog(
321                     MessageManager.formatMessage(
322                             "label.fetch_references_for_3dbeacons",
323                             seqsWithoutSourceDBRef.size()),
324                     MessageManager
325                             .getString("label.3dbeacons"),
326                     JvOptionPane.YES_NO_OPTION, JvOptionPane.PLAIN_MESSAGE,
327                     null, new Object[]
328                     { MessageManager.getString("action.ok"),
329                         MessageManager.getString("action.cancel") },
330                     MessageManager.getString("action.ok"));
331   }
332
333   /**
334    * Builds a drop-down choice list of existing structure viewers to which new
335    * structures may be added. If this list is empty then it, and the 'Add'
336    * button, are hidden.
337    */
338   private void discoverStructureViews()
339   {
340     if (Desktop.instance != null)
341     {
342       targetView.removeAllItems();
343       if (lastTargetedView != null && !lastTargetedView.isVisible())
344       {
345         lastTargetedView = null;
346       }
347       int linkedViewsAt = 0;
348       for (StructureViewerBase view : Desktop.instance
349               .getStructureViewers(null, null))
350       {
351         StructureViewer viewHandler = (lastTargetedView != null
352                 && lastTargetedView.sview == view) ? lastTargetedView
353                         : StructureViewer.reconfigure(view);
354
355         if (view.isLinkedWith(ap))
356         {
357           targetView.insertItemAt(viewHandler, linkedViewsAt++);
358         }
359         else
360         {
361           targetView.addItem(viewHandler);
362         }
363       }
364
365       /*
366        * show option to Add to viewer if at least 1 viewer found
367        */
368       targetView.setVisible(false);
369       if (targetView.getItemCount() > 0)
370       {
371         targetView.setVisible(true);
372         if (lastTargetedView != null)
373         {
374           targetView.setSelectedItem(lastTargetedView);
375         }
376         else
377         {
378           targetView.setSelectedIndex(0);
379         }
380       }
381       btn_add.setVisible(targetView.isVisible());
382     }
383   }
384
385   /**
386    * Updates the progress indicator with the specified message
387    * 
388    * @param message
389    *          displayed message for the operation
390    * @param id
391    *          unique handle for this indicator
392    */
393   protected void updateProgressIndicator(String message, long id)
394   {
395     if (progressIndicator != null)
396     {
397       progressIndicator.setProgressBar(message, id);
398     }
399   }
400
401   /**
402    * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
403    * selection group
404    */
405   void fetchStructuresMetaData()
406   {
407     long startTime = System.currentTimeMillis();
408     Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
409             .getStructureSummaryFields();
410
411     discoveredStructuresSet = new LinkedHashSet<>();
412     HashSet<String> errors = new HashSet<>();
413
414     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
415             .getSelectedItem());
416
417     for (SequenceI seq : selectedSequences)
418     {
419
420       FTSRestResponse resultList;
421       try
422       {
423         resultList = data.fetchStructuresMetaData(seq, wantedFields,
424                 selectedFilterOpt, !chk_invertFilter.isSelected());
425         // null response means the FTSengine didn't yield a query for this
426         // consider designing a special exception if we really wanted to be
427         // OOCrazy
428         if (resultList == null)
429         {
430           continue;
431         }
432       } catch (Exception e)
433       {
434         e.printStackTrace();
435         errors.add(e.getMessage());
436         continue;
437       }
438       if (resultList.getSearchSummary() != null
439               && !resultList.getSearchSummary().isEmpty())
440       {
441         discoveredStructuresSet.addAll(resultList.getSearchSummary());
442       }
443     }
444
445     int noOfStructuresFound = 0;
446     String totalTime = (System.currentTimeMillis() - startTime)
447             + " milli secs";
448     if (discoveredStructuresSet != null
449             && !discoveredStructuresSet.isEmpty())
450     {
451       getResultTable()
452               .setModel(data.getTableModel(discoveredStructuresSet));
453
454       noOfStructuresFound = discoveredStructuresSet.size();
455       lastDiscoveredStructuresSet = discoveredStructuresSet;
456       mainFrame.setTitle(MessageManager.formatMessage(
457               "label.structure_chooser_no_of_structures",
458               noOfStructuresFound, totalTime));
459     }
460     else
461     {
462       mainFrame.setTitle(MessageManager
463               .getString("label.structure_chooser_manual_association"));
464       if (errors.size() > 0)
465       {
466         StringBuilder errorMsg = new StringBuilder();
467         for (String error : errors)
468         {
469           errorMsg.append(error).append("\n");
470         }
471         JvOptionPane.showMessageDialog(this, errorMsg.toString(),
472                 MessageManager.getString("label.pdb_web-service_error"),
473                 JvOptionPane.ERROR_MESSAGE);
474       }
475     }
476   }
477
478   protected void loadLocalCachedPDBEntries()
479   {
480     ArrayList<CachedPDB> entries = new ArrayList<>();
481     for (SequenceI seq : selectedSequences)
482     {
483       if (seq.getDatasetSequence() != null
484               && seq.getDatasetSequence().getAllPDBEntries() != null)
485       {
486         for (PDBEntry pdbEntry : seq.getDatasetSequence()
487                 .getAllPDBEntries())
488         {
489           if (pdbEntry.getFile() != null)
490           {
491             entries.add(new CachedPDB(seq, pdbEntry));
492           }
493         }
494       }
495     }
496     cachedPDBExists = !entries.isEmpty();
497     PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
498     tbl_local_pdb.setModel(tableModelx);
499   }
500
501   /**
502    * Filters a given list of discovered structures based on supplied argument
503    * 
504    * @param fieldToFilterBy
505    *          the field to filter by
506    */
507   void filterResultSet(final String fieldToFilterBy)
508   {
509     Thread filterThread = new Thread(new Runnable()
510     {
511
512       @Override
513       public void run()
514       {
515         long startTime = System.currentTimeMillis();
516         lbl_loading.setVisible(true);
517         Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
518                 .getStructureSummaryFields();
519         Collection<FTSData> filteredResponse = new HashSet<>();
520         HashSet<String> errors = new HashSet<>();
521
522         for (SequenceI seq : selectedSequences)
523         {
524
525           FTSRestResponse resultList;
526           try
527           {
528             resultList = data.selectFirstRankedQuery(seq,
529                     discoveredStructuresSet, wantedFields, fieldToFilterBy,
530                     !chk_invertFilter.isSelected());
531
532           } catch (Exception e)
533           {
534             e.printStackTrace();
535             errors.add(e.getMessage());
536             continue;
537           }
538           if (resultList.getSearchSummary() != null
539                   && !resultList.getSearchSummary().isEmpty())
540           {
541             filteredResponse.addAll(resultList.getSearchSummary());
542           }
543         }
544
545         String totalTime = (System.currentTimeMillis() - startTime)
546                 + " milli secs";
547         if (!filteredResponse.isEmpty())
548         {
549           final int filterResponseCount = filteredResponse.size();
550           Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
551           reorderedStructuresSet.addAll(filteredResponse);
552           reorderedStructuresSet.addAll(discoveredStructuresSet);
553           getResultTable()
554                   .setModel(data.getTableModel(reorderedStructuresSet));
555
556           FTSRestResponse.configureTableColumn(getResultTable(),
557                   wantedFields, tempUserPrefs);
558           getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
559           getResultTable().getColumn("Ref Sequence").setMinWidth(100);
560           getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
561           // Update table selection model here
562           getResultTable().addRowSelectionInterval(0,
563                   filterResponseCount - 1);
564           mainFrame.setTitle(MessageManager.formatMessage(
565                   "label.structure_chooser_filter_time", totalTime));
566         }
567         else
568         {
569           mainFrame.setTitle(MessageManager.formatMessage(
570                   "label.structure_chooser_filter_time", totalTime));
571           if (errors.size() > 0)
572           {
573             StringBuilder errorMsg = new StringBuilder();
574             for (String error : errors)
575             {
576               errorMsg.append(error).append("\n");
577             }
578             JvOptionPane.showMessageDialog(null, errorMsg.toString(),
579                     MessageManager.getString("label.pdb_web-service_error"),
580                     JvOptionPane.ERROR_MESSAGE);
581           }
582         }
583
584         lbl_loading.setVisible(false);
585
586         validateSelections();
587       }
588     });
589     filterThread.start();
590   }
591
592   /**
593    * Handles action event for btn_pdbFromFile
594    */
595   @Override
596   protected void pdbFromFile_actionPerformed()
597   {
598     // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
599     // StructureChooser
600     // works
601     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
602             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
603     chooser.setFileView(new jalview.io.JalviewFileView());
604     chooser.setDialogTitle(
605             MessageManager.formatMessage("label.select_pdb_file_for",
606                     selectedSequence.getDisplayId(false)));
607     chooser.setToolTipText(MessageManager.formatMessage(
608             "label.load_pdb_file_associate_with_sequence",
609             selectedSequence.getDisplayId(false)));
610
611     int value = chooser.showOpenDialog(null);
612     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
613     {
614       selectedPdbFileName = chooser.getSelectedFile().getPath();
615       jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
616       validateSelections();
617     }
618   }
619
620   /**
621    * Populates the filter combo-box options dynamically depending on discovered
622    * structures
623    */
624   protected void populateFilterComboBox(boolean haveData,
625           boolean cachedPDBExist)
626   {
627     populateFilterComboBox(haveData, cachedPDBExist, null);
628   }
629
630   /**
631    * Populates the filter combo-box options dynamically depending on discovered
632    * structures
633    */
634   protected void populateFilterComboBox(boolean haveData,
635           boolean cachedPDBExist, FilterOption lastSel)
636   {
637
638     /*
639      * temporarily suspend the change listener behaviour
640      */
641     cmb_filterOption.removeItemListener(this);
642     int selSet = -1;
643     cmb_filterOption.removeAllItems();
644     if (haveData)
645     {
646       List<FilterOption> filters = data
647               .getAvailableFilterOptions(VIEWS_FILTER);
648       data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
649               lastDiscoveredStructuresSet);
650       int p = 0;
651       for (FilterOption filter : filters)
652       {
653         if (lastSel != null && filter.equals(lastSel))
654         {
655           selSet = p;
656         }
657         p++;
658         cmb_filterOption.addItem(filter);
659       }
660     }
661
662     cmb_filterOption.addItem(
663             new FilterOption(MessageManager.getString("label.enter_pdb_id"),
664                     "-", VIEWS_ENTER_ID, false, null));
665     cmb_filterOption.addItem(
666             new FilterOption(MessageManager.getString("label.from_file"),
667                     "-", VIEWS_FROM_FILE, false, null));
668     if (canQueryTDB && notQueriedTDBYet)
669     {
670       FilterOption queryTDBOption = new FilterOption(
671               MessageManager.getString("label.search_3dbeacons"), "-",
672               VIEWS_QUERYING_TDB, false, null);
673       cmb_filterOption.addItem(queryTDBOption);
674     }
675
676     if (cachedPDBExist)
677     {
678       FilterOption cachedOption = new FilterOption(
679               MessageManager.getString("label.cached_structures"), "-",
680               VIEWS_LOCAL_PDB, false, null);
681       cmb_filterOption.addItem(cachedOption);
682       if (selSet == -1)
683       {
684         cmb_filterOption.setSelectedItem(cachedOption);
685       }
686     }
687     if (selSet > -1)
688     {
689       cmb_filterOption.setSelectedIndex(selSet);
690     }
691     cmb_filterOption.addItemListener(this);
692   }
693
694   /**
695    * Updates the displayed view based on the selected filter option
696    */
697   protected void updateCurrentView()
698   {
699     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
700             .getSelectedItem());
701     
702     // first check if we need to rebuild dialog
703     if (selectedFilterOpt.getView() == VIEWS_QUERYING_TDB)
704     {
705       promptForTDBFetch();
706       return;
707     }
708     if (lastSelected == selectedFilterOpt)
709     {
710       // don't need to do anything, probably
711       return;
712     }
713     // otherwise, record selection
714     // and update the layout and dialog accordingly
715     lastSelected = selectedFilterOpt;
716
717     layout_switchableViews.show(pnl_switchableViews,
718             selectedFilterOpt.getView());
719     String filterTitle = mainFrame.getTitle();
720     mainFrame.setTitle(frameTitle);
721     chk_invertFilter.setVisible(false);
722     
723     if (selectedFilterOpt.getView() == VIEWS_FILTER)
724     {
725       mainFrame.setTitle(filterTitle);
726       // TDB Query has no invert as yet
727       chk_invertFilter.setVisible(selectedFilterOpt
728               .getQuerySource() instanceof PDBStructureChooserQuerySource);
729
730       if (data != selectedFilterOpt.getQuerySource()
731               || data.needsRefetch(selectedFilterOpt))
732       {
733         data = selectedFilterOpt.getQuerySource();
734         // rebuild the views completely, since prefs will also change
735         tabRefresh();
736         return;
737       }
738       else
739       {
740         filterResultSet(selectedFilterOpt.getValue());
741       }
742     }
743     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
744             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
745     {
746       mainFrame.setTitle(MessageManager
747               .getString("label.structure_chooser_manual_association"));
748       idInputAssSeqPanel.loadCmbAssSeq();
749       fileChooserAssSeqPanel.loadCmbAssSeq();
750     }
751     validateSelections();
752   }
753
754   /**
755    * Validates user selection and enables the 'Add' and 'New View' buttons if
756    * all parameters are correct (the Add button will only be visible if there is
757    * at least one existing structure viewer open). This basically means at least
758    * one structure selected and no error messages.
759    * <p>
760    * The 'Superpose Structures' option is enabled if either more than one
761    * structure is selected, or the 'Add' to existing view option is enabled, and
762    * disabled if the only option is to open a new view of a single structure.
763    */
764   @Override
765   protected void validateSelections()
766   {
767     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
768             .getSelectedItem());
769     btn_add.setEnabled(false);
770     String currentView = selectedFilterOpt.getView();
771     int selectedCount = 0;
772     if (currentView == VIEWS_FILTER)
773     {
774       selectedCount = getResultTable().getSelectedRows().length;
775       if (selectedCount > 0)
776       {
777         btn_add.setEnabled(true);
778       }
779     }
780     else if (currentView == VIEWS_LOCAL_PDB)
781     {
782       selectedCount = tbl_local_pdb.getSelectedRows().length;
783       if (selectedCount > 0)
784       {
785         btn_add.setEnabled(true);
786       }
787     }
788     else if (currentView == VIEWS_ENTER_ID)
789     {
790       validateAssociationEnterPdb();
791     }
792     else if (currentView == VIEWS_FROM_FILE)
793     {
794       validateAssociationFromFile();
795     }
796
797     btn_newView.setEnabled(btn_add.isEnabled());
798
799     /*
800      * enable 'Superpose' option if more than one structure is selected,
801      * or there are view(s) available to add structure(s) to
802      */
803     chk_superpose
804             .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
805   }
806
807   @Override
808   protected boolean showPopupFor(int selectedRow, int x, int y)
809   {
810     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
811             .getSelectedItem());
812     String currentView = selectedFilterOpt.getView();
813      
814     if (currentView == VIEWS_FILTER && data instanceof ThreeDBStructureChooserQuerySource)
815     {
816       
817       TDB_FTSData row=((ThreeDBStructureChooserQuerySource)data).getFTSDataFor(getResultTable(), selectedRow, discoveredStructuresSet);
818       String pageUrl = row.getModelViewUrl(); 
819       JPopupMenu popup = new JPopupMenu("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.show(getResultTable(), x, y); }
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 }