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