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