11e50dbf2ff6ffcfce7734918a8e68b923d07687
[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.Callable;
35 import java.util.concurrent.Executors;
36
37 import javax.swing.JCheckBox;
38 import javax.swing.JComboBox;
39 import javax.swing.JLabel;
40 import javax.swing.JMenuItem;
41 import javax.swing.JPopupMenu;
42 import javax.swing.JTable;
43 import javax.swing.SwingUtilities;
44 import javax.swing.table.AbstractTableModel;
45
46 import jalview.api.structures.JalviewStructureDisplayI;
47 import jalview.bin.Cache;
48 import jalview.bin.Console;
49 import jalview.bin.Jalview;
50 import jalview.datamodel.PDBEntry;
51 import jalview.datamodel.SequenceI;
52 import jalview.fts.api.FTSData;
53 import jalview.fts.api.FTSDataColumnI;
54 import jalview.fts.api.FTSRestClientI;
55 import jalview.fts.core.FTSDataColumnPreferences;
56 import jalview.fts.core.FTSRestRequest;
57 import jalview.fts.core.FTSRestResponse;
58 import jalview.fts.service.pdb.PDBFTSRestClient;
59 import jalview.fts.service.threedbeacons.TDB_FTSData;
60 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
61 import jalview.gui.structurechooser.StructureChooserQuerySource;
62 import jalview.gui.structurechooser.ThreeDBStructureChooserQuerySource;
63 import jalview.io.DataSourceType;
64 import jalview.io.JalviewFileChooser;
65 import jalview.io.JalviewFileView;
66 import jalview.jbgui.FilterOption;
67 import jalview.jbgui.GStructureChooser;
68 import jalview.structure.StructureImportSettings.TFType;
69 import jalview.structure.StructureMapping;
70 import jalview.structure.StructureSelectionManager;
71 import jalview.util.MessageManager;
72 import jalview.util.Platform;
73 import jalview.util.StringUtils;
74 import jalview.ws.DBRefFetcher;
75 import jalview.ws.DBRefFetcher.FetchFinishedListenerI;
76 import jalview.ws.seqfetcher.DbSourceProxy;
77 import jalview.ws.sifts.SiftsSettings;
78
79 /**
80  * Provides the behaviors for the Structure chooser Panel
81  * 
82  * @author tcnofoegbu
83  *
84  */
85 @SuppressWarnings("serial")
86 public class StructureChooser extends GStructureChooser
87         implements IProgressIndicator
88 {
89   private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
90
91   /**
92    * warn user if need to fetch more than this many uniprot records at once
93    */
94   private static final int THRESHOLD_WARN_UNIPROT_FETCH_NEEDED = 20;
95
96   private SequenceI selectedSequence;
97
98   private SequenceI[] selectedSequences;
99
100   private IProgressIndicator progressIndicator;
101
102   private Collection<FTSData> discoveredStructuresSet;
103
104   private StructureChooserQuerySource data;
105
106   @Override
107   protected FTSDataColumnPreferences getFTSDocFieldPrefs()
108   {
109     return data.getDocFieldPrefs();
110   }
111
112   private String selectedPdbFileName;
113
114   private TFType localPdbTempfacType;
115
116   private String localPdbPaeMatrixFileName;
117
118   private boolean isValidPBDEntry;
119
120   private boolean cachedPDBExists;
121
122   private Collection<FTSData> lastDiscoveredStructuresSet;
123
124   private boolean canQueryTDB = false;
125
126   private boolean notQueriedTDBYet = true;
127
128   List<SequenceI> seqsWithoutSourceDBRef = null;
129
130   private boolean showChooserGUI = true;
131
132   private static StructureViewer lastTargetedView = null;
133
134   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
135           AlignmentPanel ap)
136   {
137     this(selectedSeqs, selectedSeq, ap, true);
138   }
139
140   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
141           AlignmentPanel ap, boolean showGUI)
142   {
143     // which FTS engine to use
144     data = StructureChooserQuerySource.getQuerySourceFor(selectedSeqs);
145     initDialog();
146
147     this.ap = ap;
148     this.selectedSequence = selectedSeq;
149     this.selectedSequences = selectedSeqs;
150     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
151     this.showChooserGUI = showGUI;
152     init();
153
154   }
155
156   /**
157    * sets canQueryTDB if protein sequences without a canonical uniprot ref or at
158    * least one structure are discovered.
159    */
160   private void populateSeqsWithoutSourceDBRef()
161   {
162     seqsWithoutSourceDBRef = new ArrayList<SequenceI>();
163     boolean needCanonical = false;
164     for (SequenceI seq : selectedSequences)
165     {
166       if (seq.isProtein())
167       {
168         int dbRef = ThreeDBStructureChooserQuerySource
169                 .checkUniprotRefs(seq.getDBRefs());
170         if (dbRef < 0)
171         {
172           if (dbRef == -1)
173           {
174             // need to retrieve canonicals
175             needCanonical = true;
176             seqsWithoutSourceDBRef.add(seq);
177           }
178           else
179           {
180             // could be a sequence with pdb ref
181             if (seq.getAllPDBEntries() == null
182                     || seq.getAllPDBEntries().size() == 0)
183             {
184               seqsWithoutSourceDBRef.add(seq);
185             }
186           }
187         }
188       }
189     }
190     // retrieve database refs for protein sequences
191     if (!seqsWithoutSourceDBRef.isEmpty())
192     {
193       canQueryTDB = true;
194       if (needCanonical)
195       {
196         // triggers display of the 'Query TDB' button
197         notQueriedTDBYet = true;
198       }
199     }
200   };
201
202   /**
203    * Initializes parameters used by the Structure Chooser Panel
204    */
205   protected void init()
206   {
207     if (!Jalview.isHeadlessMode())
208     {
209       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
210     }
211
212     chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
213     btn_queryTDB.addActionListener(new ActionListener()
214     {
215
216       @Override
217       public void actionPerformed(ActionEvent e)
218       {
219         promptForTDBFetch(false);
220       }
221     });
222
223     Executors.defaultThreadFactory().newThread(new Runnable()
224     {
225       @Override
226       public void run()
227       {
228         populateSeqsWithoutSourceDBRef();
229         initialStructureDiscovery();
230       }
231
232     }).start();
233
234   }
235
236   // called by init
237   private void initialStructureDiscovery()
238   {
239     // check which FTS engine to use
240     data = StructureChooserQuerySource.getQuerySourceFor(selectedSequences);
241
242     // ensure a filter option is in force for search
243     populateFilterComboBox(true, cachedPDBExists);
244
245     // looks for any existing structures already loaded
246     // for the sequences (the cached ones)
247     // then queries the StructureChooserQuerySource to
248     // discover more structures.
249     //
250     // Possible optimisation is to only begin querying
251     // the structure chooser if there are no cached structures.
252
253     long startTime = System.currentTimeMillis();
254     updateProgressIndicator(
255             MessageManager.getString("status.loading_cached_pdb_entries"),
256             startTime);
257     loadLocalCachedPDBEntries();
258     updateProgressIndicator(null, startTime);
259     updateProgressIndicator(
260             MessageManager.getString("status.searching_for_pdb_structures"),
261             startTime);
262     fetchStructuresMetaData();
263     // revise filter options if no results were found
264     populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
265     discoverStructureViews();
266     updateProgressIndicator(null, startTime);
267     mainFrame.setVisible(showChooserGUI);
268     updateCurrentView();
269   }
270
271   /**
272    * raises dialog for Uniprot fetch followed by 3D beacons search
273    * 
274    * @param ignoreGui
275    *          - when true, don't ask, just fetch
276    */
277   public void promptForTDBFetch(boolean ignoreGui)
278   {
279     final long progressId = System.currentTimeMillis();
280
281     // final action after prompting and discovering db refs
282     final Runnable strucDiscovery = new Runnable()
283     {
284       @Override
285       public void run()
286       {
287         mainFrame.setEnabled(false);
288         cmb_filterOption.setEnabled(false);
289         progressBar.setProgressBar(
290                 MessageManager.getString("status.searching_3d_beacons"),
291                 progressId);
292         btn_queryTDB.setEnabled(false);
293         // TODO: warn if no accessions discovered
294         populateSeqsWithoutSourceDBRef();
295         // redo initial discovery - this time with 3d beacons
296         // Executors.
297         previousWantedFields = null;
298         lastSelected = (FilterOption) cmb_filterOption.getSelectedItem();
299         cmb_filterOption.setSelectedItem(null);
300         cachedPDBExists = false; // reset to initial
301         initialStructureDiscovery();
302         if (!isStructuresDiscovered())
303         {
304           progressBar.setProgressBar(MessageManager.getString(
305                   "status.no_structures_discovered_from_3d_beacons"),
306                   progressId);
307           btn_queryTDB.setToolTipText(MessageManager.getString(
308                   "status.no_structures_discovered_from_3d_beacons"));
309           btn_queryTDB.setEnabled(false);
310           pnl_queryTDB.setVisible(false);
311         }
312         else
313         {
314           cmb_filterOption.setSelectedIndex(0); // select 'best'
315           btn_queryTDB.setVisible(false);
316           pnl_queryTDB.setVisible(false);
317           progressBar.setProgressBar(null, progressId);
318         }
319         mainFrame.setEnabled(true);
320         cmb_filterOption.setEnabled(true);
321       }
322     };
323
324     final FetchFinishedListenerI afterDbRefFetch = new FetchFinishedListenerI()
325     {
326
327       @Override
328       public void finished()
329       {
330         // filter has been selected, so we set flag to remove ourselves
331         notQueriedTDBYet = false;
332         // new thread to discover structures - via 3d beacons
333         Executors.defaultThreadFactory().newThread(strucDiscovery).start();
334
335       }
336     };
337
338     // fetch db refs if OK pressed
339     final Callable discoverCanonicalDBrefs = () -> {
340       btn_queryTDB.setEnabled(false);
341       populateSeqsWithoutSourceDBRef();
342
343       final int y = seqsWithoutSourceDBRef.size();
344       if (y > 0)
345       {
346         final SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
347                 .toArray(new SequenceI[y]);
348         DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef,
349                 progressBar, new DbSourceProxy[]
350                 { new jalview.ws.dbsources.Uniprot() }, null, false);
351         dbRefFetcher.addListener(afterDbRefFetch);
352         // ideally this would also gracefully run with callbacks
353
354         dbRefFetcher.fetchDBRefs(true);
355       }
356       else
357       {
358         // call finished action directly
359         afterDbRefFetch.finished();
360       }
361       return null;
362     };
363     final Callable revertview = () -> {
364       if (lastSelected != null)
365       {
366         cmb_filterOption.setSelectedItem(lastSelected);
367       }
368       return null;
369     };
370     int threshold = Cache.getDefault("UNIPROT_AUTOFETCH_THRESHOLD",
371             THRESHOLD_WARN_UNIPROT_FETCH_NEEDED);
372     Console.debug("Using Uniprot fetch threshold of " + threshold);
373     if (ignoreGui || seqsWithoutSourceDBRef.size() < threshold)
374     {
375       Executors.newSingleThreadExecutor().submit(discoverCanonicalDBrefs);
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     JalviewFileChooser chooser = new JalviewFileChooser(
668             Cache.getProperty("LAST_DIRECTORY"));
669     chooser.setFileView(new 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 == JalviewFileChooser.APPROVE_OPTION)
679     {
680       selectedPdbFileName = chooser.getSelectedFile().getPath();
681       Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
682       localPdbPaeMatrixFileName = guessPAEFilename();
683       validateSelections();
684     }
685   }
686
687   /**
688    * Handles action event for btn_pdbFromFile
689    */
690   @Override
691   protected void paeMatrixFile_actionPerformed()
692   {
693     File pdbFile = new File(selectedPdbFileName);
694     String setFile = Cache.getProperty("LAST_DIRECTORY");
695     if (localPdbPaeMatrixFileName != null)
696     {
697       File paeFile = new File(localPdbPaeMatrixFileName);
698       if (paeFile.exists())
699         setFile = paeFile.getAbsolutePath();
700       else if (paeFile.getParentFile().exists())
701         setFile = paeFile.getParentFile().getAbsolutePath();
702     }
703     else
704     {
705       String guess = guessPAEFilename();
706       if (guess != null)
707         setFile = guess;
708     }
709     JalviewFileChooser chooser = new JalviewFileChooser(setFile);
710     chooser.setFileView(new JalviewFileView());
711     chooser.setDialogTitle(MessageManager.formatMessage(
712             "label.select_pae_matrix_file_for", pdbFile.getName()));
713     chooser.setToolTipText(MessageManager.formatMessage(
714             "label.load_pae_matrix_file_associate_with_structure",
715             pdbFile.getName()));
716
717     int value = chooser.showOpenDialog(null);
718     if (value == JalviewFileChooser.APPROVE_OPTION)
719     {
720       localPdbPaeMatrixFileName = chooser.getSelectedFile().getPath();
721       Cache.setProperty("LAST_DIRECTORY", localPdbPaeMatrixFileName);
722     }
723     validateAssociationFromFile();
724   }
725
726   private String guessPAEFilename()
727   {
728     if (selectedPdbFileName.toLowerCase(Locale.ROOT).endsWith(".pdb")
729             || selectedPdbFileName.toLowerCase(Locale.ROOT)
730                     .endsWith(".cif"))
731     {
732       String jsonExt = selectedPdbFileName.substring(0,
733               selectedPdbFileName.length() - 4) + ".json";
734       // AlphaFold naming scheme
735       String guessFile1 = StringUtils.replaceLast(jsonExt, "model",
736               "predicted_aligned_error");
737       // nf-core mode naming scheme
738       String guessFile2 = StringUtils.replaceLast(jsonExt, ".json",
739               "_scores.json");
740       if (new File(guessFile1).exists())
741       {
742         return guessFile1;
743       }
744       else if (new File(jsonExt).exists())
745       {
746         return jsonExt;
747       }
748       else if (new File(guessFile2).exists())
749       {
750         return guessFile2;
751       }
752     }
753     return null;
754   }
755
756   /**
757    * Populates the filter combo-box options dynamically depending on discovered
758    * structures
759    */
760   protected void populateFilterComboBox(boolean haveData,
761           boolean cachedPDBExist)
762   {
763     populateFilterComboBox(haveData, cachedPDBExist, null);
764   }
765
766   /**
767    * Populates the filter combo-box options dynamically depending on discovered
768    * structures
769    */
770   protected void populateFilterComboBox(boolean haveData,
771           boolean cachedPDBExist, FilterOption lastSel)
772   {
773
774     /*
775      * temporarily suspend the change listener behaviour
776      */
777     cmb_filterOption.removeItemListener(this);
778     int selSet = -1;
779     cmb_filterOption.removeAllItems();
780     if (haveData)
781     {
782       List<FilterOption> filters = data
783               .getAvailableFilterOptions(VIEWS_FILTER);
784       data.updateAvailableFilterOptions(VIEWS_FILTER, filters,
785               lastDiscoveredStructuresSet);
786       int p = 0;
787       for (FilterOption filter : filters)
788       {
789         if (lastSel != null && filter.equals(lastSel))
790         {
791           selSet = p;
792         }
793         p++;
794         cmb_filterOption.addItem(filter);
795       }
796     }
797
798     cmb_filterOption.addItem(
799             new FilterOption(MessageManager.getString("label.enter_pdb_id"),
800                     "-", VIEWS_ENTER_ID, false, null));
801     cmb_filterOption.addItem(
802             new FilterOption(MessageManager.getString("label.from_file"),
803                     "-", VIEWS_FROM_FILE, false, null));
804     if (canQueryTDB && notQueriedTDBYet)
805     {
806       btn_queryTDB.setVisible(true);
807       pnl_queryTDB.setVisible(true);
808     }
809
810     if (cachedPDBExist)
811     {
812       FilterOption cachedOption = new FilterOption(
813               MessageManager.getString("label.cached_structures"), "-",
814               VIEWS_LOCAL_PDB, false, null);
815       cmb_filterOption.addItem(cachedOption);
816       if (selSet == -1)
817       {
818         cmb_filterOption.setSelectedItem(cachedOption);
819       }
820     }
821     if (selSet > -1)
822     {
823       cmb_filterOption.setSelectedIndex(selSet);
824     }
825     cmb_filterOption.addItemListener(this);
826   }
827
828   /**
829    * Updates the displayed view based on the selected filter option
830    */
831   protected void updateCurrentView()
832   {
833     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
834             .getSelectedItem());
835
836     if (lastSelected == selectedFilterOpt)
837     {
838       // don't need to do anything, probably
839       return;
840     }
841     // otherwise, record selection
842     // and update the layout and dialog accordingly
843     lastSelected = selectedFilterOpt;
844
845     layout_switchableViews.show(pnl_switchableViews,
846             selectedFilterOpt.getView());
847     String filterTitle = mainFrame.getTitle();
848     mainFrame.setTitle(frameTitle);
849     chk_invertFilter.setVisible(false);
850
851     if (selectedFilterOpt.getView() == VIEWS_FILTER)
852     {
853       mainFrame.setTitle(filterTitle);
854       // TDB Query has no invert as yet
855       chk_invertFilter.setVisible(selectedFilterOpt
856               .getQuerySource() instanceof PDBStructureChooserQuerySource);
857
858       if (data != selectedFilterOpt.getQuerySource()
859               || data.needsRefetch(selectedFilterOpt))
860       {
861         data = selectedFilterOpt.getQuerySource();
862         // rebuild the views completely, since prefs will also change
863         tabRefresh();
864         return;
865       }
866       else
867       {
868         filterResultSet(selectedFilterOpt.getValue());
869       }
870     }
871     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
872             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
873     {
874       mainFrame.setTitle(MessageManager
875               .getString("label.structure_chooser_manual_association"));
876       idInputAssSeqPanel.loadCmbAssSeq();
877       fileChooserAssSeqPanel.loadCmbAssSeq();
878     }
879     validateSelections();
880   }
881
882   /**
883    * Validates user selection and enables the 'Add' and 'New View' buttons if
884    * all parameters are correct (the Add button will only be visible if there is
885    * at least one existing structure viewer open). This basically means at least
886    * one structure selected and no error messages.
887    * <p>
888    * The 'Superpose Structures' option is enabled if either more than one
889    * structure is selected, or the 'Add' to existing view option is enabled, and
890    * disabled if the only option is to open a new view of a single structure.
891    */
892   @Override
893   protected void validateSelections()
894   {
895     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
896             .getSelectedItem());
897     btn_add.setEnabled(false);
898     String currentView = selectedFilterOpt.getView();
899     int selectedCount = 0;
900     if (currentView == VIEWS_FILTER)
901     {
902       selectedCount = getResultTable().getSelectedRows().length;
903       if (selectedCount > 0)
904       {
905         btn_add.setEnabled(true);
906       }
907     }
908     else if (currentView == VIEWS_LOCAL_PDB)
909     {
910       selectedCount = tbl_local_pdb.getSelectedRows().length;
911       if (selectedCount > 0)
912       {
913         btn_add.setEnabled(true);
914       }
915     }
916     else if (currentView == VIEWS_ENTER_ID)
917     {
918       validateAssociationEnterPdb();
919     }
920     else if (currentView == VIEWS_FROM_FILE)
921     {
922       validateAssociationFromFile();
923     }
924
925     btn_newView.setEnabled(btn_add.isEnabled());
926
927     /*
928      * enable 'Superpose' option if more than one structure is selected,
929      * or there are view(s) available to add structure(s) to
930      */
931     chk_superpose
932             .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
933   }
934
935   @Override
936   protected boolean showPopupFor(int selectedRow, int x, int y)
937   {
938     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
939             .getSelectedItem());
940     String currentView = selectedFilterOpt.getView();
941
942     if (currentView == VIEWS_FILTER
943             && data instanceof ThreeDBStructureChooserQuerySource)
944     {
945
946       TDB_FTSData row = ((ThreeDBStructureChooserQuerySource) data)
947               .getFTSDataFor(getResultTable(), selectedRow,
948                       discoveredStructuresSet);
949       String pageUrl = row.getModelViewUrl();
950       JPopupMenu popup = new JPopupMenu("3D Beacons");
951       JMenuItem viewUrl = new JMenuItem("View model web page");
952       viewUrl.addActionListener(new ActionListener()
953       {
954         @Override
955         public void actionPerformed(ActionEvent e)
956         {
957           Desktop.showUrl(pageUrl);
958         }
959       });
960       popup.add(viewUrl);
961       SwingUtilities.invokeLater(new Runnable()
962       {
963         @Override
964         public void run()
965         {
966           popup.show(getResultTable(), x, y);
967         }
968       });
969       return true;
970     }
971     // event not handled by us
972     return false;
973   }
974
975   /**
976    * Validates inputs from the Manual PDB entry panel
977    */
978   protected void validateAssociationEnterPdb()
979   {
980     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
981             .getCmb_assSeq().getSelectedItem();
982     lbl_pdbManualFetchStatus.setIcon(errorImage);
983     lbl_pdbManualFetchStatus.setToolTipText("");
984     if (txt_search.getText().length() > 0)
985     {
986       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
987               MessageManager.formatMessage("info.no_pdb_entry_found_for",
988                       txt_search.getText())));
989     }
990
991     if (errorWarning.length() > 0)
992     {
993       lbl_pdbManualFetchStatus.setIcon(warningImage);
994       lbl_pdbManualFetchStatus.setToolTipText(
995               JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
996     }
997
998     if (selectedSequences.length == 1 || !assSeqOpt.getName()
999             .equalsIgnoreCase("-Select Associated Seq-"))
1000     {
1001       txt_search.setEnabled(true);
1002       if (isValidPBDEntry)
1003       {
1004         btn_add.setEnabled(true);
1005         lbl_pdbManualFetchStatus.setToolTipText("");
1006         lbl_pdbManualFetchStatus.setIcon(goodImage);
1007       }
1008     }
1009     else
1010     {
1011       txt_search.setEnabled(false);
1012       lbl_pdbManualFetchStatus.setIcon(errorImage);
1013     }
1014   }
1015
1016   /**
1017    * Validates inputs for the manual PDB file selection options
1018    */
1019   protected void validateAssociationFromFile()
1020   {
1021     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
1022             .getCmb_assSeq().getSelectedItem();
1023     // lbl_fromFileStatus.setIcon(errorImage);
1024     String pdbFileString = "";
1025     String pdbFileTooltip = "";
1026     if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
1027             .getName().equalsIgnoreCase("-Select Associated Seq-")))
1028     {
1029       btn_pdbFromFile.setEnabled(true);
1030       if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
1031       {
1032         btn_add.setEnabled(true);
1033         // lbl_fromFileStatus.setIcon(goodImage);
1034         pdbFileString = new File(selectedPdbFileName).getName();
1035         pdbFileTooltip = new File(selectedPdbFileName).getAbsolutePath();
1036         setPdbOptionsEnabled(true);
1037       }
1038       else
1039       {
1040         pdbFileString = MessageManager.getString("label.none");
1041         pdbFileTooltip = MessageManager.getString("label.nothing_selected");
1042       }
1043     }
1044     else
1045     {
1046       btn_pdbFromFile.setEnabled(false);
1047       // lbl_fromFileStatus.setIcon(errorImage);
1048       pdbFileString = MessageManager.getString("label.none");
1049       pdbFileTooltip = MessageManager.getString("label.nothing_selected");
1050     }
1051     lbl_pdbFile.setText(pdbFileString);
1052     lbl_pdbFile.setToolTipText(pdbFileTooltip);
1053
1054     // PAE file choice
1055     String paeFileString = "";
1056     String paeFileTooltip = "";
1057     if (localPdbPaeMatrixFileName != null
1058             && localPdbPaeMatrixFileName.length() > 0)
1059     {
1060       paeFileString = new File(localPdbPaeMatrixFileName).getName();
1061       paeFileTooltip = new File(localPdbPaeMatrixFileName)
1062               .getAbsolutePath();
1063     }
1064     else
1065     {
1066       paeFileString = MessageManager.getString("label.none");
1067       paeFileTooltip = MessageManager.getString("label.nothing_selected");
1068     }
1069     lbl_paeFile.setText(paeFileString);
1070     lbl_paeFile.setToolTipText(paeFileTooltip);
1071   }
1072
1073   @Override
1074   protected void cmbAssSeqStateChanged()
1075   {
1076     validateSelections();
1077   }
1078
1079   private FilterOption lastSelected = null;
1080
1081   /**
1082    * Handles the state change event for the 'filter' combo-box and 'invert'
1083    * check-box
1084    */
1085   @Override
1086   protected void stateChanged(ItemEvent e)
1087   {
1088     if (e.getSource() instanceof JCheckBox)
1089     {
1090       updateCurrentView();
1091     }
1092     else
1093     {
1094       if (e.getStateChange() == ItemEvent.SELECTED)
1095       {
1096         updateCurrentView();
1097       }
1098     }
1099
1100   }
1101
1102   /**
1103    * select structures for viewing by their PDB IDs
1104    * 
1105    * @param pdbids
1106    * @return true if structures were found and marked as selected
1107    */
1108   public boolean selectStructure(String... pdbids)
1109   {
1110     boolean found = false;
1111
1112     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1113             .getSelectedItem());
1114     String currentView = selectedFilterOpt.getView();
1115     JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1116             : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
1117
1118     if (restable == null)
1119     {
1120       // can't select (enter PDB ID, or load file - need to also select which
1121       // sequence to associate with)
1122       return false;
1123     }
1124
1125     int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
1126     for (int r = 0; r < restable.getRowCount(); r++)
1127     {
1128       for (int p = 0; p < pdbids.length; p++)
1129       {
1130         if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
1131                 .equalsIgnoreCase(pdbids[p]))
1132         {
1133           restable.setRowSelectionInterval(r, r);
1134           found = true;
1135         }
1136       }
1137     }
1138     return found;
1139   }
1140
1141   /**
1142    * Handles the 'New View' action
1143    */
1144   @Override
1145   protected void newView_ActionPerformed()
1146   {
1147     targetView.setSelectedItem(null);
1148     showStructures(false);
1149   }
1150
1151   /**
1152    * Handles the 'Add to existing viewer' action
1153    */
1154   @Override
1155   protected void add_ActionPerformed()
1156   {
1157     showStructures(false);
1158   }
1159
1160   /**
1161    * structure viewer opened by this dialog, or null
1162    */
1163   private StructureViewer sViewer = null;
1164
1165   public void showStructures(boolean waitUntilFinished)
1166   {
1167
1168     final StructureSelectionManager ssm = ap.getStructureSelectionManager();
1169
1170     final int preferredHeight = pnl_filter.getHeight();
1171
1172     Runnable viewStruc = new Runnable()
1173     {
1174       @Override
1175       public void run()
1176       {
1177         FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
1178                 .getSelectedItem());
1179         String currentView = selectedFilterOpt.getView();
1180         JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
1181                 : tbl_local_pdb;
1182
1183         if (currentView == VIEWS_FILTER)
1184         {
1185           int[] selectedRows = restable.getSelectedRows();
1186           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1187           List<SequenceI> selectedSeqsToView = new ArrayList<>();
1188           pdbEntriesToView = data.collectSelectedRows(restable,
1189                   selectedRows, selectedSeqsToView);
1190
1191           SequenceI[] selectedSeqs = selectedSeqsToView
1192                   .toArray(new SequenceI[selectedSeqsToView.size()]);
1193           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1194                   selectedSeqs);
1195         }
1196         else if (currentView == VIEWS_LOCAL_PDB)
1197         {
1198           int[] selectedRows = tbl_local_pdb.getSelectedRows();
1199           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
1200           int count = 0;
1201           int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
1202                   .getModelIndex();
1203           int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
1204                   .getModelIndex();
1205           List<SequenceI> selectedSeqsToView = new ArrayList<>();
1206           for (int row : selectedRows)
1207           {
1208             PDBEntry pdbEntry = ((PDBEntryTableModel) tbl_local_pdb
1209                     .getModel()).getPDBEntryAt(row).getPdbEntry();
1210
1211             pdbEntriesToView[count++] = pdbEntry;
1212             SequenceI selectedSeq = (SequenceI) tbl_local_pdb
1213                     .getValueAt(row, refSeqColIndex);
1214             selectedSeqsToView.add(selectedSeq);
1215           }
1216           SequenceI[] selectedSeqs = selectedSeqsToView
1217                   .toArray(new SequenceI[selectedSeqsToView.size()]);
1218           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1219                   selectedSeqs);
1220         }
1221         else if (currentView == VIEWS_ENTER_ID)
1222         {
1223           SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
1224                   .getCmb_assSeq().getSelectedItem()).getSequence();
1225           if (userSelectedSeq != null)
1226           {
1227             selectedSequence = userSelectedSeq;
1228           }
1229           String pdbIdStr = txt_search.getText();
1230           PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
1231           if (pdbEntry == null)
1232           {
1233             pdbEntry = new PDBEntry();
1234             if (pdbIdStr.split(":").length > 1)
1235             {
1236               pdbEntry.setId(pdbIdStr.split(":")[0]);
1237               pdbEntry.setChainCode(
1238                       pdbIdStr.split(":")[1].toUpperCase(Locale.ROOT));
1239             }
1240             else
1241             {
1242               pdbEntry.setId(pdbIdStr);
1243             }
1244             pdbEntry.setType(PDBEntry.Type.PDB);
1245             selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
1246           }
1247
1248           PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
1249           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
1250                   new SequenceI[]
1251                   { selectedSequence });
1252         }
1253         else if (currentView == VIEWS_FROM_FILE)
1254         {
1255           SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
1256                   .getCmb_assSeq().getSelectedItem()).getSequence();
1257           if (userSelectedSeq != null)
1258           {
1259             selectedSequence = userSelectedSeq;
1260           }
1261           PDBEntry fileEntry = new AssociatePdbFileWithSeq()
1262                   .associatePdbWithSeq(selectedPdbFileName,
1263                           DataSourceType.FILE, selectedSequence, true,
1264                           Desktop.instance);
1265           /* LOOK AT
1266           public PDBEntry associatePdbWithSeq(String choice, DataSourceType file,
1267                   SequenceI sequence, boolean prompt,
1268                   StructureSelectionManagerProvider ssmp)
1269           IN AssociatePdbFileWithSeq */
1270
1271           // DO SOMETHING WITH
1272           if (StructureChooser.this.localPdbPaeMatrixFileName != null)
1273           {
1274
1275           }
1276           if (StructureChooser.this.combo_tempFacAs
1277                   .getSelectedItem() != null)
1278           {
1279
1280           }
1281
1282           sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
1283                   ap, new SequenceI[]
1284                   { selectedSequence });
1285         }
1286         SwingUtilities.invokeLater(new Runnable()
1287         {
1288           @Override
1289           public void run()
1290           {
1291             closeAction(preferredHeight);
1292             mainFrame.dispose();
1293           }
1294         });
1295       }
1296     };
1297     Thread runner = new Thread(viewStruc);
1298     runner.start();
1299     if (waitUntilFinished)
1300     {
1301       while (sViewer == null ? runner.isAlive()
1302               : (sViewer.sview == null ? true
1303                       : !sViewer.sview.hasMapping()))
1304       {
1305         try
1306         {
1307           Thread.sleep(300);
1308         } catch (InterruptedException ie)
1309         {
1310
1311         }
1312       }
1313     }
1314   }
1315
1316   /**
1317    * Answers a structure viewer (new or existing) configured to superimpose
1318    * added structures or not according to the user's choice
1319    * 
1320    * @param ssm
1321    * @return
1322    */
1323   StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
1324   {
1325     Object sv = targetView.getSelectedItem();
1326
1327     return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
1328   }
1329
1330   /**
1331    * Adds PDB structures to a new or existing structure viewer
1332    * 
1333    * @param ssm
1334    * @param pdbEntriesToView
1335    * @param alignPanel
1336    * @param sequences
1337    * @return
1338    */
1339   private StructureViewer launchStructureViewer(
1340           StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
1341           final AlignmentPanel alignPanel, SequenceI[] sequences)
1342   {
1343     long progressId = sequences.hashCode();
1344     setProgressBar(MessageManager
1345             .getString("status.launching_3d_structure_viewer"), progressId);
1346     final StructureViewer theViewer = getTargetedStructureViewer(ssm);
1347     boolean superimpose = chk_superpose.isSelected();
1348     theViewer.setSuperpose(superimpose);
1349
1350     /*
1351      * remember user's choice of superimpose or not
1352      */
1353     Cache.setProperty(AUTOSUPERIMPOSE,
1354             Boolean.valueOf(superimpose).toString());
1355
1356     setProgressBar(null, progressId);
1357     if (SiftsSettings.isMapWithSifts())
1358     {
1359       List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
1360       int p = 0;
1361       // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
1362       // real PDB ID. For moment, we can also safely do this if there is already
1363       // a known mapping between the PDBEntry and the sequence.
1364       for (SequenceI seq : sequences)
1365       {
1366         PDBEntry pdbe = pdbEntriesToView[p++];
1367         if (pdbe != null && pdbe.getFile() != null)
1368         {
1369           StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
1370           if (smm != null && smm.length > 0)
1371           {
1372             for (StructureMapping sm : smm)
1373             {
1374               if (sm.getSequence() == seq)
1375               {
1376                 continue;
1377               }
1378             }
1379           }
1380         }
1381         if (seq.getPrimaryDBRefs().isEmpty())
1382         {
1383           seqsWithoutSourceDBRef.add(seq);
1384           continue;
1385         }
1386       }
1387       if (!seqsWithoutSourceDBRef.isEmpty())
1388       {
1389         int y = seqsWithoutSourceDBRef.size();
1390         setProgressBar(MessageManager.formatMessage(
1391                 "status.fetching_dbrefs_for_sequences_without_valid_refs",
1392                 y), progressId);
1393         SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
1394                 .toArray(new SequenceI[y]);
1395         DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
1396         dbRefFetcher.fetchDBRefs(true);
1397
1398         setProgressBar("Fetch complete.", progressId); // todo i18n
1399       }
1400     }
1401     if (pdbEntriesToView.length > 1)
1402     {
1403       setProgressBar(
1404               MessageManager.getString(
1405                       "status.fetching_3d_structures_for_selected_entries"),
1406               progressId);
1407       theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
1408     }
1409     else
1410     {
1411       setProgressBar(MessageManager.formatMessage(
1412               "status.fetching_3d_structures_for",
1413               pdbEntriesToView[0].getId()), progressId);
1414       theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
1415     }
1416     setProgressBar(null, progressId);
1417     // remember the last viewer we used...
1418     lastTargetedView = theViewer;
1419     return theViewer;
1420   }
1421
1422   /**
1423    * Populates the combo-box used in associating manually fetched structures to
1424    * a unique sequence when more than one sequence selection is made.
1425    */
1426   @Override
1427   protected void populateCmbAssociateSeqOptions(
1428           JComboBox<AssociateSeqOptions> cmb_assSeq,
1429           JLabel lbl_associateSeq)
1430   {
1431     cmb_assSeq.removeAllItems();
1432     cmb_assSeq.addItem(
1433             new AssociateSeqOptions("-Select Associated Seq-", null));
1434     lbl_associateSeq.setVisible(false);
1435     if (selectedSequences.length > 1)
1436     {
1437       for (SequenceI seq : selectedSequences)
1438       {
1439         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
1440       }
1441     }
1442     else
1443     {
1444       String seqName = selectedSequence.getDisplayId(false);
1445       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
1446       lbl_associateSeq.setText(seqName);
1447       lbl_associateSeq.setVisible(true);
1448       cmb_assSeq.setVisible(false);
1449     }
1450   }
1451
1452   protected boolean isStructuresDiscovered()
1453   {
1454     return discoveredStructuresSet != null
1455             && !discoveredStructuresSet.isEmpty();
1456   }
1457
1458   protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1459                                // this.
1460   // Doing a search for "1" or "1c" is valuable?
1461   // Those work but are enormously slow.
1462
1463   @Override
1464   protected void txt_search_ActionPerformed()
1465   {
1466     String text = txt_search.getText().trim();
1467     if (text.length() >= PDB_ID_MIN)
1468       new Thread()
1469       {
1470
1471         @Override
1472         public void run()
1473         {
1474           errorWarning.setLength(0);
1475           isValidPBDEntry = false;
1476           if (text.length() > 0)
1477           {
1478             // TODO move this pdb id search into the PDB specific
1479             // FTSSearchEngine
1480             // for moment, it will work fine as is because it is self-contained
1481             String searchTerm = text.toLowerCase(Locale.ROOT);
1482             searchTerm = searchTerm.split(":")[0];
1483             // System.out.println(">>>>> search term : " + searchTerm);
1484             List<FTSDataColumnI> wantedFields = new ArrayList<>();
1485             FTSRestRequest pdbRequest = new FTSRestRequest();
1486             pdbRequest.setAllowEmptySeq(false);
1487             pdbRequest.setResponseSize(1);
1488             pdbRequest.setFieldToSearchBy("(pdb_id:");
1489             pdbRequest.setWantedFields(wantedFields);
1490             pdbRequest.setSearchTerm(searchTerm + ")");
1491             pdbRequest.setAssociatedSequence(selectedSequence);
1492             FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1493             wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1494             FTSRestResponse resultList;
1495             try
1496             {
1497               resultList = pdbRestClient.executeRequest(pdbRequest);
1498             } catch (Exception e)
1499             {
1500               errorWarning.append(e.getMessage());
1501               return;
1502             } finally
1503             {
1504               validateSelections();
1505             }
1506             if (resultList.getSearchSummary() != null
1507                     && resultList.getSearchSummary().size() > 0)
1508             {
1509               isValidPBDEntry = true;
1510             }
1511           }
1512           validateSelections();
1513         }
1514       }.start();
1515   }
1516
1517   @Override
1518   protected void tabRefresh()
1519   {
1520     if (selectedSequences != null)
1521     {
1522       lbl_loading.setVisible(true);
1523       Thread refreshThread = new Thread(new Runnable()
1524       {
1525         @Override
1526         public void run()
1527         {
1528           fetchStructuresMetaData();
1529           // populateFilterComboBox(true, cachedPDBExists);
1530
1531           filterResultSet(
1532                   ((FilterOption) cmb_filterOption.getSelectedItem())
1533                           .getValue());
1534           lbl_loading.setVisible(false);
1535         }
1536       });
1537       refreshThread.start();
1538     }
1539   }
1540
1541   public class PDBEntryTableModel extends AbstractTableModel
1542   {
1543     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1544         "File" };
1545
1546     private List<CachedPDB> pdbEntries;
1547
1548     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1549     {
1550       this.pdbEntries = new ArrayList<>(pdbEntries);
1551     }
1552
1553     @Override
1554     public String getColumnName(int columnIndex)
1555     {
1556       return columns[columnIndex];
1557     }
1558
1559     @Override
1560     public int getRowCount()
1561     {
1562       return pdbEntries.size();
1563     }
1564
1565     @Override
1566     public int getColumnCount()
1567     {
1568       return columns.length;
1569     }
1570
1571     @Override
1572     public boolean isCellEditable(int row, int column)
1573     {
1574       return false;
1575     }
1576
1577     @Override
1578     public Object getValueAt(int rowIndex, int columnIndex)
1579     {
1580       Object value = "??";
1581       CachedPDB entry = pdbEntries.get(rowIndex);
1582       switch (columnIndex)
1583       {
1584       case 0:
1585         value = entry.getSequence();
1586         break;
1587       case 1:
1588         value = entry.getQualifiedId();
1589         break;
1590       case 2:
1591         value = entry.getPdbEntry().getChainCode() == null ? "_"
1592                 : entry.getPdbEntry().getChainCode();
1593         break;
1594       case 3:
1595         value = entry.getPdbEntry().getType();
1596         break;
1597       case 4:
1598         value = entry.getPdbEntry().getFile();
1599         break;
1600       }
1601       return value;
1602     }
1603
1604     @Override
1605     public Class<?> getColumnClass(int columnIndex)
1606     {
1607       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1608     }
1609
1610     public CachedPDB getPDBEntryAt(int row)
1611     {
1612       return pdbEntries.get(row);
1613     }
1614
1615   }
1616
1617   private class CachedPDB
1618   {
1619     private SequenceI sequence;
1620
1621     private PDBEntry pdbEntry;
1622
1623     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1624     {
1625       this.sequence = sequence;
1626       this.pdbEntry = pdbEntry;
1627     }
1628
1629     public String getQualifiedId()
1630     {
1631       if (pdbEntry.hasProvider())
1632       {
1633         return pdbEntry.getProvider() + ":" + pdbEntry.getId();
1634       }
1635       return pdbEntry.toString();
1636     }
1637
1638     public SequenceI getSequence()
1639     {
1640       return sequence;
1641     }
1642
1643     public PDBEntry getPdbEntry()
1644     {
1645       return pdbEntry;
1646     }
1647
1648   }
1649
1650   private IProgressIndicator progressBar;
1651
1652   @Override
1653   public void setProgressBar(String message, long id)
1654   {
1655     if (!Platform.isHeadless())
1656       progressBar.setProgressBar(message, id);
1657   }
1658
1659   @Override
1660   public void registerHandler(long id, IProgressIndicatorHandler handler)
1661   {
1662     progressBar.registerHandler(id, handler);
1663   }
1664
1665   @Override
1666   public boolean operationInProgress()
1667   {
1668     return progressBar.operationInProgress();
1669   }
1670
1671   public JalviewStructureDisplayI getOpenedStructureViewer()
1672   {
1673     return sViewer == null ? null : sViewer.sview;
1674   }
1675
1676   @Override
1677   protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1678   {
1679     data.setDocFieldPrefs(newPrefs);
1680
1681   }
1682
1683   /**
1684    * 
1685    * @return true when all initialisation threads have finished and dialog is
1686    *         visible
1687    */
1688   public boolean isDialogVisible()
1689   {
1690     return mainFrame != null && data != null && cmb_filterOption != null
1691             && mainFrame.isVisible()
1692             && cmb_filterOption.getSelectedItem() != null;
1693   }
1694
1695   /**
1696    * 
1697    * @return true if the 3D-Beacons query button will/has been displayed
1698    */
1699   public boolean isCanQueryTDB()
1700   {
1701     return canQueryTDB;
1702   }
1703
1704   public boolean isNotQueriedTDBYet()
1705   {
1706     return notQueriedTDBYet;
1707   }
1708
1709   /**
1710    * Open a single structure file for a given sequence
1711    */
1712   public static void openStructureFileForSequence(AlignmentPanel ap,
1713           SequenceI seq, File sFile)
1714   {
1715     // Open the chooser headlessly. Not sure this is actually needed ?
1716     StructureChooser sc = new StructureChooser(new SequenceI[] { seq }, seq,
1717             ap, false);
1718     StructureSelectionManager ssm = ap.getStructureSelectionManager();
1719     PDBEntry fileEntry = null;
1720     try
1721     {
1722       fileEntry = new AssociatePdbFileWithSeq().associatePdbWithSeq(
1723               sFile.getAbsolutePath(), DataSourceType.FILE, seq, true,
1724               Desktop.instance);
1725     } catch (Exception e)
1726     {
1727       Console.error("Could not open structure file '"
1728               + sFile.getAbsolutePath() + "'");
1729       return;
1730     }
1731
1732     StructureViewer sViewer = sc.launchStructureViewer(ssm,
1733             new PDBEntry[]
1734             { fileEntry }, ap, new SequenceI[] { seq });
1735
1736     sc.mainFrame.dispose();
1737   }
1738 }