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