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