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