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