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