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