JAL-3829 3d-beacons structure chooser logic (not yet finished)
[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 jalview.api.structures.JalviewStructureDisplayI;
25 import jalview.bin.Cache;
26 import jalview.bin.Jalview;
27 import jalview.datamodel.DBRefEntry;
28 import jalview.datamodel.DBRefSource;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.fts.api.FTSData;
32 import jalview.fts.api.FTSDataColumnI;
33 import jalview.fts.api.FTSRestClientI;
34 import jalview.fts.core.FTSDataColumnPreferences;
35 import jalview.fts.core.FTSRestRequest;
36 import jalview.fts.core.FTSRestResponse;
37 import jalview.fts.service.pdb.PDBFTSRestClient;
38 import jalview.gui.structurechooser.PDBStructureChooserQuerySource;
39 import jalview.gui.structurechooser.StructureChooserQuerySource;
40 import jalview.io.DataSourceType;
41 import jalview.jbgui.GStructureChooser;
42 import jalview.jbgui.GStructureChooser.FilterOption;
43 import jalview.structure.StructureMapping;
44 import jalview.structure.StructureSelectionManager;
45 import jalview.util.MessageManager;
46 import jalview.ws.DBRefFetcher;
47 import jalview.ws.sifts.SiftsSettings;
48
49 import java.awt.event.ItemEvent;
50 import java.util.ArrayList;
51 import java.util.Collection;
52 import java.util.HashSet;
53 import java.util.LinkedHashSet;
54 import java.util.List;
55 import java.util.Objects;
56 import java.util.Set;
57 import java.util.Vector;
58
59 import javax.swing.JCheckBox;
60 import javax.swing.JComboBox;
61 import javax.swing.JLabel;
62 import javax.swing.JTable;
63 import javax.swing.SwingUtilities;
64 import javax.swing.table.AbstractTableModel;
65
66 /**
67  * Provides the behaviors for the Structure chooser Panel
68  * 
69  * @author tcnofoegbu
70  *
71  */
72 @SuppressWarnings("serial")
73 public class StructureChooser extends GStructureChooser
74         implements IProgressIndicator
75 {
76   private static final String AUTOSUPERIMPOSE = "AUTOSUPERIMPOSE";
77
78   private SequenceI selectedSequence;
79
80   private SequenceI[] selectedSequences;
81
82   private IProgressIndicator progressIndicator;
83
84   private Collection<FTSData> discoveredStructuresSet;
85
86   private StructureChooserQuerySource data;
87
88   @Override
89   protected FTSDataColumnPreferences getFTSDocFieldPrefs()
90   {
91     return data.getDocFieldPrefs();
92   }
93
94   private String selectedPdbFileName;
95
96   private boolean isValidPBDEntry;
97
98   private boolean cachedPDBExists;
99
100   private static StructureViewer lastTargetedView = null;
101
102   public StructureChooser(SequenceI[] selectedSeqs, SequenceI selectedSeq,
103           AlignmentPanel ap)
104   {
105     // which FTS engine to use
106     data = StructureChooserQuerySource
107             .getTDBfts();
108     initDialog();
109     
110     this.ap = ap;
111     this.selectedSequence = selectedSeq;
112     this.selectedSequences = selectedSeqs;
113     this.progressIndicator = (ap == null) ? null : ap.alignFrame;
114     init();
115     
116   }
117
118   /**
119    * Initializes parameters used by the Structure Chooser Panel
120    */
121   protected void init()
122   {
123     if (!Jalview.isHeadlessMode())
124     {
125       progressBar = new ProgressBar(this.statusPanel, this.statusBar);
126     }
127
128     chk_superpose.setSelected(Cache.getDefault(AUTOSUPERIMPOSE, true));
129
130     // ensure a filter option is in force for search
131     populateFilterComboBox(true, cachedPDBExists);
132     Thread discoverPDBStructuresThread = new Thread(new Runnable()
133     {
134       @Override
135       public void run()
136       {
137         long startTime = System.currentTimeMillis();
138         updateProgressIndicator(MessageManager
139                 .getString("status.loading_cached_pdb_entries"), startTime);
140         loadLocalCachedPDBEntries();
141         updateProgressIndicator(null, startTime);
142         updateProgressIndicator(MessageManager.getString(
143                 "status.searching_for_pdb_structures"), startTime);
144         fetchStructuresMetaData();
145         // revise filter options if no results were found
146         populateFilterComboBox(isStructuresDiscovered(), cachedPDBExists);
147         discoverStructureViews();
148         updateProgressIndicator(null, startTime);
149         mainFrame.setVisible(true);
150         updateCurrentView();
151       }
152     });
153     discoverPDBStructuresThread.start();
154   }
155
156   /**
157    * Builds a drop-down choice list of existing structure viewers to which new
158    * structures may be added. If this list is empty then it, and the 'Add'
159    * button, are hidden.
160    */
161   private void discoverStructureViews()
162   {
163     if (Desktop.instance != null)
164     {
165       targetView.removeAllItems();
166       if (lastTargetedView != null && !lastTargetedView.isVisible())
167       {
168         lastTargetedView = null;
169       }
170       int linkedViewsAt = 0;
171       for (StructureViewerBase view : Desktop.instance
172               .getStructureViewers(null, null))
173       {
174         StructureViewer viewHandler = (lastTargetedView != null
175                 && lastTargetedView.sview == view) ? lastTargetedView
176                         : StructureViewer.reconfigure(view);
177
178         if (view.isLinkedWith(ap))
179         {
180           targetView.insertItemAt(viewHandler, linkedViewsAt++);
181         }
182         else
183         {
184           targetView.addItem(viewHandler);
185         }
186       }
187
188       /*
189        * show option to Add to viewer if at least 1 viewer found
190        */
191       targetView.setVisible(false);
192       if (targetView.getItemCount() > 0)
193       {
194         targetView.setVisible(true);
195         if (lastTargetedView != null)
196         {
197           targetView.setSelectedItem(lastTargetedView);
198         }
199         else
200         {
201           targetView.setSelectedIndex(0);
202         }
203       }
204       btn_add.setVisible(targetView.isVisible());
205     }
206   }
207
208   /**
209    * Updates the progress indicator with the specified message
210    * 
211    * @param message
212    *          displayed message for the operation
213    * @param id
214    *          unique handle for this indicator
215    */
216   protected void updateProgressIndicator(String message, long id)
217   {
218     if (progressIndicator != null)
219     {
220       progressIndicator.setProgressBar(message, id);
221     }
222   }
223
224   /**
225    * Retrieve meta-data for all the structure(s) for a given sequence(s) in a
226    * selection group
227    */
228   void fetchStructuresMetaData()
229   {
230     long startTime = System.currentTimeMillis();
231     Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
232             .getStructureSummaryFields();
233
234     discoveredStructuresSet = new LinkedHashSet<>();
235     HashSet<String> errors = new HashSet<>();
236
237     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
238             .getSelectedItem());
239
240     for (SequenceI seq : selectedSequences)
241     {
242
243       FTSRestResponse resultList;
244       try
245       {
246         resultList = data.fetchStructuresMetaData(seq, wantedFields,
247                 selectedFilterOpt, !chk_invertFilter.isSelected());
248         // null response means the FTSengine didn't yield a query for this
249         // consider designing a special exception if we really wanted to be OOCrazy
250         if (resultList==null)
251         {
252           continue;
253         }
254       } catch (Exception e)
255       {
256         e.printStackTrace();
257         errors.add(e.getMessage());
258         continue;
259       }
260       if (resultList.getSearchSummary() != null
261               && !resultList.getSearchSummary().isEmpty())
262       {
263         discoveredStructuresSet.addAll(resultList.getSearchSummary());
264       }
265     }
266
267     int noOfStructuresFound = 0;
268     String totalTime = (System.currentTimeMillis() - startTime)
269             + " milli secs";
270     if (discoveredStructuresSet != null
271             && !discoveredStructuresSet.isEmpty())
272     {
273       getResultTable()
274               .setModel(data.getTableModel(discoveredStructuresSet));
275       noOfStructuresFound = discoveredStructuresSet.size();
276       mainFrame.setTitle(MessageManager.formatMessage(
277               "label.structure_chooser_no_of_structures",
278               noOfStructuresFound, totalTime));
279     }
280     else
281     {
282       mainFrame.setTitle(MessageManager
283               .getString("label.structure_chooser_manual_association"));
284       if (errors.size() > 0)
285       {
286         StringBuilder errorMsg = new StringBuilder();
287         for (String error : errors)
288         {
289           errorMsg.append(error).append("\n");
290         }
291         JvOptionPane.showMessageDialog(this, errorMsg.toString(),
292                 MessageManager.getString("label.pdb_web-service_error"),
293                 JvOptionPane.ERROR_MESSAGE);
294       }
295     }
296   }
297
298   protected void loadLocalCachedPDBEntries()
299   {
300     ArrayList<CachedPDB> entries = new ArrayList<>();
301     for (SequenceI seq : selectedSequences)
302     {
303       if (seq.getDatasetSequence() != null
304               && seq.getDatasetSequence().getAllPDBEntries() != null)
305       {
306         for (PDBEntry pdbEntry : seq.getDatasetSequence()
307                 .getAllPDBEntries())
308         {
309           if (pdbEntry.getFile() != null)
310           {
311             entries.add(new CachedPDB(seq, pdbEntry));
312           }
313         }
314       }
315     }
316     cachedPDBExists = !entries.isEmpty();
317     PDBEntryTableModel tableModelx = new PDBEntryTableModel(entries);
318     tbl_local_pdb.setModel(tableModelx);
319   }
320
321   /**
322    * Filters a given list of discovered structures based on supplied argument
323    * 
324    * @param fieldToFilterBy
325    *          the field to filter by
326    */
327   void filterResultSet(final String fieldToFilterBy)
328   {
329     Thread filterThread = new Thread(new Runnable()
330     {
331       @Override
332       public void run()
333       {
334         long startTime = System.currentTimeMillis();
335         lbl_loading.setVisible(true);
336         Collection<FTSDataColumnI> wantedFields = data.getDocFieldPrefs()
337                 .getStructureSummaryFields();
338         Collection<FTSData> filteredResponse = new HashSet<>();
339         HashSet<String> errors = new HashSet<>();
340
341         for (SequenceI seq : selectedSequences)
342         {
343
344           FTSRestResponse resultList;
345           try
346           {
347             resultList = data.selectFirstRankedQuery(seq, wantedFields,
348                     fieldToFilterBy, !chk_invertFilter.isSelected());
349
350           } catch (Exception e)
351           {
352             e.printStackTrace();
353             errors.add(e.getMessage());
354             continue;
355           }
356           if (resultList.getSearchSummary() != null
357                   && !resultList.getSearchSummary().isEmpty())
358           {
359             filteredResponse.addAll(resultList.getSearchSummary());
360           }
361         }
362
363         String totalTime = (System.currentTimeMillis() - startTime)
364                 + " milli secs";
365         if (!filteredResponse.isEmpty())
366         {
367           final int filterResponseCount = filteredResponse.size();
368           Collection<FTSData> reorderedStructuresSet = new LinkedHashSet<>();
369           reorderedStructuresSet.addAll(filteredResponse);
370           reorderedStructuresSet.addAll(discoveredStructuresSet);
371           getResultTable()
372                   .setModel(data.getTableModel(reorderedStructuresSet));
373
374           FTSRestResponse.configureTableColumn(getResultTable(),
375                   wantedFields, tempUserPrefs);
376           getResultTable().getColumn("Ref Sequence").setPreferredWidth(120);
377           getResultTable().getColumn("Ref Sequence").setMinWidth(100);
378           getResultTable().getColumn("Ref Sequence").setMaxWidth(200);
379           // Update table selection model here
380           getResultTable().addRowSelectionInterval(0,
381                   filterResponseCount - 1);
382           mainFrame.setTitle(MessageManager.formatMessage(
383                   "label.structure_chooser_filter_time", totalTime));
384         }
385         else
386         {
387           mainFrame.setTitle(MessageManager.formatMessage(
388                   "label.structure_chooser_filter_time", totalTime));
389           if (errors.size() > 0)
390           {
391             StringBuilder errorMsg = new StringBuilder();
392             for (String error : errors)
393             {
394               errorMsg.append(error).append("\n");
395             }
396             JvOptionPane.showMessageDialog(null, errorMsg.toString(),
397                     MessageManager.getString("label.pdb_web-service_error"),
398                     JvOptionPane.ERROR_MESSAGE);
399           }
400         }
401
402         lbl_loading.setVisible(false);
403
404         validateSelections();
405       }
406     });
407     filterThread.start();
408   }
409
410   /**
411    * Handles action event for btn_pdbFromFile
412    */
413   @Override
414   protected void pdbFromFile_actionPerformed()
415   {
416     // TODO: JAL-3048 not needed for Jalview-JS until JSmol dep and
417     // StructureChooser
418     // works
419     jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
420             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
421     chooser.setFileView(new jalview.io.JalviewFileView());
422     chooser.setDialogTitle(
423             MessageManager.formatMessage("label.select_pdb_file_for",
424                     selectedSequence.getDisplayId(false)));
425     chooser.setToolTipText(MessageManager.formatMessage(
426             "label.load_pdb_file_associate_with_sequence",
427             selectedSequence.getDisplayId(false)));
428
429     int value = chooser.showOpenDialog(null);
430     if (value == jalview.io.JalviewFileChooser.APPROVE_OPTION)
431     {
432       selectedPdbFileName = chooser.getSelectedFile().getPath();
433       jalview.bin.Cache.setProperty("LAST_DIRECTORY", selectedPdbFileName);
434       validateSelections();
435     }
436   }
437
438   /**
439    * Populates the filter combo-box options dynamically depending on discovered
440    * structures
441    */
442   protected void populateFilterComboBox(boolean haveData,
443           boolean cachedPDBExist)
444   {
445     /*
446      * temporarily suspend the change listener behaviour
447      */
448     cmb_filterOption.removeItemListener(this);
449
450     cmb_filterOption.removeAllItems();
451     if (haveData)
452     {
453       cmb_filterOption.addItem(new FilterOption(
454               MessageManager.getString("label.best_quality"),
455               "overall_quality", VIEWS_FILTER, false));
456       cmb_filterOption.addItem(new FilterOption(
457               MessageManager.getString("label.best_resolution"),
458               "resolution", VIEWS_FILTER, false));
459       cmb_filterOption.addItem(new FilterOption(
460               MessageManager.getString("label.most_protein_chain"),
461               "number_of_protein_chains", VIEWS_FILTER, false));
462       cmb_filterOption.addItem(new FilterOption(
463               MessageManager.getString("label.most_bound_molecules"),
464               "number_of_bound_molecules", VIEWS_FILTER, false));
465       cmb_filterOption.addItem(new FilterOption(
466               MessageManager.getString("label.most_polymer_residues"),
467               "number_of_polymer_residues", VIEWS_FILTER, true));
468     }
469     cmb_filterOption.addItem(
470             new FilterOption(MessageManager.getString("label.enter_pdb_id"),
471                     "-", VIEWS_ENTER_ID, false));
472     cmb_filterOption.addItem(
473             new FilterOption(MessageManager.getString("label.from_file"),
474                     "-", VIEWS_FROM_FILE, false));
475
476     if (cachedPDBExist)
477     {
478       FilterOption cachedOption = new FilterOption(
479               MessageManager.getString("label.cached_structures"), "-",
480               VIEWS_LOCAL_PDB, false);
481       cmb_filterOption.addItem(cachedOption);
482       cmb_filterOption.setSelectedItem(cachedOption);
483     }
484
485     cmb_filterOption.addItemListener(this);
486   }
487
488   /**
489    * Updates the displayed view based on the selected filter option
490    */
491   protected void updateCurrentView()
492   {
493     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
494             .getSelectedItem());
495     layout_switchableViews.show(pnl_switchableViews,
496             selectedFilterOpt.getView());
497     String filterTitle = mainFrame.getTitle();
498     mainFrame.setTitle(frameTitle);
499     chk_invertFilter.setVisible(false);
500     if (selectedFilterOpt.getView() == VIEWS_FILTER)
501     {
502       mainFrame.setTitle(filterTitle);
503       chk_invertFilter.setVisible(true);
504       filterResultSet(selectedFilterOpt.getValue());
505     }
506     else if (selectedFilterOpt.getView() == VIEWS_ENTER_ID
507             || selectedFilterOpt.getView() == VIEWS_FROM_FILE)
508     {
509       mainFrame.setTitle(MessageManager
510               .getString("label.structure_chooser_manual_association"));
511       idInputAssSeqPanel.loadCmbAssSeq();
512       fileChooserAssSeqPanel.loadCmbAssSeq();
513     }
514     validateSelections();
515   }
516
517   /**
518    * Validates user selection and enables the 'Add' and 'New View' buttons if
519    * all parameters are correct (the Add button will only be visible if there is
520    * at least one existing structure viewer open). This basically means at least
521    * one structure selected and no error messages.
522    * <p>
523    * The 'Superpose Structures' option is enabled if either more than one
524    * structure is selected, or the 'Add' to existing view option is enabled, and
525    * disabled if the only option is to open a new view of a single structure.
526    */
527   @Override
528   protected void validateSelections()
529   {
530     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
531             .getSelectedItem());
532     btn_add.setEnabled(false);
533     String currentView = selectedFilterOpt.getView();
534     int selectedCount = 0;
535     if (currentView == VIEWS_FILTER)
536     {
537       selectedCount = getResultTable().getSelectedRows().length;
538       if (selectedCount > 0)
539       {
540         btn_add.setEnabled(true);
541       }
542     }
543     else if (currentView == VIEWS_LOCAL_PDB)
544     {
545       selectedCount = tbl_local_pdb.getSelectedRows().length;
546       if (selectedCount > 0)
547       {
548         btn_add.setEnabled(true);
549       }
550     }
551     else if (currentView == VIEWS_ENTER_ID)
552     {
553       validateAssociationEnterPdb();
554     }
555     else if (currentView == VIEWS_FROM_FILE)
556     {
557       validateAssociationFromFile();
558     }
559
560     btn_newView.setEnabled(btn_add.isEnabled());
561
562     /*
563      * enable 'Superpose' option if more than one structure is selected,
564      * or there are view(s) available to add structure(s) to
565      */
566     chk_superpose
567             .setEnabled(selectedCount > 1 || targetView.getItemCount() > 0);
568   }
569
570   /**
571    * Validates inputs from the Manual PDB entry panel
572    */
573   protected void validateAssociationEnterPdb()
574   {
575     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) idInputAssSeqPanel
576             .getCmb_assSeq().getSelectedItem();
577     lbl_pdbManualFetchStatus.setIcon(errorImage);
578     lbl_pdbManualFetchStatus.setToolTipText("");
579     if (txt_search.getText().length() > 0)
580     {
581       lbl_pdbManualFetchStatus.setToolTipText(JvSwingUtils.wrapTooltip(true,
582               MessageManager.formatMessage("info.no_pdb_entry_found_for",
583                       txt_search.getText())));
584     }
585
586     if (errorWarning.length() > 0)
587     {
588       lbl_pdbManualFetchStatus.setIcon(warningImage);
589       lbl_pdbManualFetchStatus.setToolTipText(
590               JvSwingUtils.wrapTooltip(true, errorWarning.toString()));
591     }
592
593     if (selectedSequences.length == 1 || !assSeqOpt.getName()
594             .equalsIgnoreCase("-Select Associated Seq-"))
595     {
596       txt_search.setEnabled(true);
597       if (isValidPBDEntry)
598       {
599         btn_add.setEnabled(true);
600         lbl_pdbManualFetchStatus.setToolTipText("");
601         lbl_pdbManualFetchStatus.setIcon(goodImage);
602       }
603     }
604     else
605     {
606       txt_search.setEnabled(false);
607       lbl_pdbManualFetchStatus.setIcon(errorImage);
608     }
609   }
610
611   /**
612    * Validates inputs for the manual PDB file selection options
613    */
614   protected void validateAssociationFromFile()
615   {
616     AssociateSeqOptions assSeqOpt = (AssociateSeqOptions) fileChooserAssSeqPanel
617             .getCmb_assSeq().getSelectedItem();
618     lbl_fromFileStatus.setIcon(errorImage);
619     if (selectedSequences.length == 1 || (assSeqOpt != null && !assSeqOpt
620             .getName().equalsIgnoreCase("-Select Associated Seq-")))
621     {
622       btn_pdbFromFile.setEnabled(true);
623       if (selectedPdbFileName != null && selectedPdbFileName.length() > 0)
624       {
625         btn_add.setEnabled(true);
626         lbl_fromFileStatus.setIcon(goodImage);
627       }
628     }
629     else
630     {
631       btn_pdbFromFile.setEnabled(false);
632       lbl_fromFileStatus.setIcon(errorImage);
633     }
634   }
635
636   @Override
637   protected void cmbAssSeqStateChanged()
638   {
639     validateSelections();
640   }
641
642   /**
643    * Handles the state change event for the 'filter' combo-box and 'invert'
644    * check-box
645    */
646   @Override
647   protected void stateChanged(ItemEvent e)
648   {
649     if (e.getSource() instanceof JCheckBox)
650     {
651       updateCurrentView();
652     }
653     else
654     {
655       if (e.getStateChange() == ItemEvent.SELECTED)
656       {
657         updateCurrentView();
658       }
659     }
660
661   }
662
663   /**
664    * select structures for viewing by their PDB IDs
665    * 
666    * @param pdbids
667    * @return true if structures were found and marked as selected
668    */
669   public boolean selectStructure(String... pdbids)
670   {
671     boolean found = false;
672
673     FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
674             .getSelectedItem());
675     String currentView = selectedFilterOpt.getView();
676     JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
677             : (currentView == VIEWS_LOCAL_PDB) ? tbl_local_pdb : null;
678
679     if (restable == null)
680     {
681       // can't select (enter PDB ID, or load file - need to also select which
682       // sequence to associate with)
683       return false;
684     }
685
686     int pdbIdColIndex = restable.getColumn("PDB Id").getModelIndex();
687     for (int r = 0; r < restable.getRowCount(); r++)
688     {
689       for (int p = 0; p < pdbids.length; p++)
690       {
691         if (String.valueOf(restable.getValueAt(r, pdbIdColIndex))
692                 .equalsIgnoreCase(pdbids[p]))
693         {
694           restable.setRowSelectionInterval(r, r);
695           found = true;
696         }
697       }
698     }
699     return found;
700   }
701
702   /**
703    * Handles the 'New View' action
704    */
705   @Override
706   protected void newView_ActionPerformed()
707   {
708     targetView.setSelectedItem(null);
709     showStructures(false);
710   }
711
712   /**
713    * Handles the 'Add to existing viewer' action
714    */
715   @Override
716   protected void add_ActionPerformed()
717   {
718     showStructures(false);
719   }
720
721   /**
722    * structure viewer opened by this dialog, or null
723    */
724   private StructureViewer sViewer = null;
725
726   public void showStructures(boolean waitUntilFinished)
727   {
728
729     final StructureSelectionManager ssm = ap.getStructureSelectionManager();
730
731     final int preferredHeight = pnl_filter.getHeight();
732
733     Runnable viewStruc = new Runnable()
734     {
735       @Override
736       public void run()
737       {
738         FilterOption selectedFilterOpt = ((FilterOption) cmb_filterOption
739                 .getSelectedItem());
740         String currentView = selectedFilterOpt.getView();
741         JTable restable = (currentView == VIEWS_FILTER) ? getResultTable()
742                 : tbl_local_pdb;
743
744         if (currentView == VIEWS_FILTER)
745         {
746           int[] selectedRows = restable.getSelectedRows();
747           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
748           List<SequenceI> selectedSeqsToView = new ArrayList<>();
749           pdbEntriesToView = data.collectSelectedRows(restable,selectedRows,selectedSeqsToView);
750
751           SequenceI[] selectedSeqs = selectedSeqsToView
752                   .toArray(new SequenceI[selectedSeqsToView.size()]);
753           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
754                   selectedSeqs);
755         }
756         else if (currentView == VIEWS_LOCAL_PDB)
757         {
758           int[] selectedRows = tbl_local_pdb.getSelectedRows();
759           PDBEntry[] pdbEntriesToView = new PDBEntry[selectedRows.length];
760           int count = 0;
761           int pdbIdColIndex = tbl_local_pdb.getColumn("PDB Id")
762                   .getModelIndex();
763           int refSeqColIndex = tbl_local_pdb.getColumn("Ref Sequence")
764                   .getModelIndex();
765           List<SequenceI> selectedSeqsToView = new ArrayList<>();
766           for (int row : selectedRows)
767           {
768             PDBEntry pdbEntry = (PDBEntry) tbl_local_pdb.getValueAt(row,
769                     pdbIdColIndex);
770             pdbEntriesToView[count++] = pdbEntry;
771             SequenceI selectedSeq = (SequenceI) tbl_local_pdb
772                     .getValueAt(row, refSeqColIndex);
773             selectedSeqsToView.add(selectedSeq);
774           }
775           SequenceI[] selectedSeqs = selectedSeqsToView
776                   .toArray(new SequenceI[selectedSeqsToView.size()]);
777           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
778                   selectedSeqs);
779         }
780         else if (currentView == VIEWS_ENTER_ID)
781         {
782           SequenceI userSelectedSeq = ((AssociateSeqOptions) idInputAssSeqPanel
783                   .getCmb_assSeq().getSelectedItem()).getSequence();
784           if (userSelectedSeq != null)
785           {
786             selectedSequence = userSelectedSeq;
787           }
788           String pdbIdStr = txt_search.getText();
789           PDBEntry pdbEntry = selectedSequence.getPDBEntry(pdbIdStr);
790           if (pdbEntry == null)
791           {
792             pdbEntry = new PDBEntry();
793             if (pdbIdStr.split(":").length > 1)
794             {
795               pdbEntry.setId(pdbIdStr.split(":")[0]);
796               pdbEntry.setChainCode(pdbIdStr.split(":")[1].toUpperCase());
797             }
798             else
799             {
800               pdbEntry.setId(pdbIdStr);
801             }
802             pdbEntry.setType(PDBEntry.Type.PDB);
803             selectedSequence.getDatasetSequence().addPDBId(pdbEntry);
804           }
805
806           PDBEntry[] pdbEntriesToView = new PDBEntry[] { pdbEntry };
807           sViewer = launchStructureViewer(ssm, pdbEntriesToView, ap,
808                   new SequenceI[]
809                   { selectedSequence });
810         }
811         else if (currentView == VIEWS_FROM_FILE)
812         {
813           SequenceI userSelectedSeq = ((AssociateSeqOptions) fileChooserAssSeqPanel
814                   .getCmb_assSeq().getSelectedItem()).getSequence();
815           if (userSelectedSeq != null)
816           {
817             selectedSequence = userSelectedSeq;
818           }
819           PDBEntry fileEntry = new AssociatePdbFileWithSeq()
820                   .associatePdbWithSeq(selectedPdbFileName,
821                           DataSourceType.FILE, selectedSequence, true,
822                           Desktop.instance);
823
824           sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
825                   ap, new SequenceI[]
826                   { selectedSequence });
827         }
828         SwingUtilities.invokeLater(new Runnable()
829         {
830           @Override
831           public void run()
832           {
833             closeAction(preferredHeight);
834             mainFrame.dispose();
835           }
836         });
837       }
838     };
839     Thread runner = new Thread(viewStruc);
840     runner.start();
841     if (waitUntilFinished)
842     {
843       while (sViewer == null ? runner.isAlive()
844               : (sViewer.sview == null ? true
845                       : !sViewer.sview.hasMapping()))
846       {
847         try
848         {
849           Thread.sleep(300);
850         } catch (InterruptedException ie)
851         {
852
853         }
854       }
855     }
856   }
857
858   /**
859    * Answers a structure viewer (new or existing) configured to superimpose
860    * added structures or not according to the user's choice
861    * 
862    * @param ssm
863    * @return
864    */
865   StructureViewer getTargetedStructureViewer(StructureSelectionManager ssm)
866   {
867     Object sv = targetView.getSelectedItem();
868
869     return sv == null ? new StructureViewer(ssm) : (StructureViewer) sv;
870   }
871
872   /**
873    * Adds PDB structures to a new or existing structure viewer
874    * 
875    * @param ssm
876    * @param pdbEntriesToView
877    * @param alignPanel
878    * @param sequences
879    * @return
880    */
881   private StructureViewer launchStructureViewer(
882           StructureSelectionManager ssm, final PDBEntry[] pdbEntriesToView,
883           final AlignmentPanel alignPanel, SequenceI[] sequences)
884   {
885     long progressId = sequences.hashCode();
886     setProgressBar(MessageManager
887             .getString("status.launching_3d_structure_viewer"), progressId);
888     final StructureViewer theViewer = getTargetedStructureViewer(ssm);
889     boolean superimpose = chk_superpose.isSelected();
890     theViewer.setSuperpose(superimpose);
891
892     /*
893      * remember user's choice of superimpose or not
894      */
895     Cache.setProperty(AUTOSUPERIMPOSE,
896             Boolean.valueOf(superimpose).toString());
897
898     setProgressBar(null, progressId);
899     if (SiftsSettings.isMapWithSifts())
900     {
901       List<SequenceI> seqsWithoutSourceDBRef = new ArrayList<>();
902       int p = 0;
903       // TODO: skip PDBEntry:Sequence pairs where PDBEntry doesn't look like a
904       // real PDB ID. For moment, we can also safely do this if there is already
905       // a known mapping between the PDBEntry and the sequence.
906       for (SequenceI seq : sequences)
907       {
908         PDBEntry pdbe = pdbEntriesToView[p++];
909         if (pdbe != null && pdbe.getFile() != null)
910         {
911           StructureMapping[] smm = ssm.getMapping(pdbe.getFile());
912           if (smm != null && smm.length > 0)
913           {
914             for (StructureMapping sm : smm)
915             {
916               if (sm.getSequence() == seq)
917               {
918                 continue;
919               }
920             }
921           }
922         }
923         if (seq.getPrimaryDBRefs().isEmpty())
924         {
925           seqsWithoutSourceDBRef.add(seq);
926           continue;
927         }
928       }
929       if (!seqsWithoutSourceDBRef.isEmpty())
930       {
931         int y = seqsWithoutSourceDBRef.size();
932         setProgressBar(MessageManager.formatMessage(
933                 "status.fetching_dbrefs_for_sequences_without_valid_refs",
934                 y), progressId);
935         SequenceI[] seqWithoutSrcDBRef = seqsWithoutSourceDBRef
936                 .toArray(new SequenceI[y]);
937         DBRefFetcher dbRefFetcher = new DBRefFetcher(seqWithoutSrcDBRef);
938         dbRefFetcher.fetchDBRefs(true);
939
940         setProgressBar("Fetch complete.", progressId); // todo i18n
941       }
942     }
943     if (pdbEntriesToView.length > 1)
944     {
945       setProgressBar(
946               MessageManager.getString(
947                       "status.fetching_3d_structures_for_selected_entries"),
948               progressId);
949       theViewer.viewStructures(pdbEntriesToView, sequences, alignPanel);
950     }
951     else
952     {
953       setProgressBar(MessageManager.formatMessage(
954               "status.fetching_3d_structures_for",
955               pdbEntriesToView[0].getId()), progressId);
956       theViewer.viewStructures(pdbEntriesToView[0], sequences, alignPanel);
957     }
958     setProgressBar(null, progressId);
959     // remember the last viewer we used...
960     lastTargetedView = theViewer;
961     return theViewer;
962   }
963
964   /**
965    * Populates the combo-box used in associating manually fetched structures to
966    * a unique sequence when more than one sequence selection is made.
967    */
968   @Override
969   protected void populateCmbAssociateSeqOptions(
970           JComboBox<AssociateSeqOptions> cmb_assSeq,
971           JLabel lbl_associateSeq)
972   {
973     cmb_assSeq.removeAllItems();
974     cmb_assSeq.addItem(
975             new AssociateSeqOptions("-Select Associated Seq-", null));
976     lbl_associateSeq.setVisible(false);
977     if (selectedSequences.length > 1)
978     {
979       for (SequenceI seq : selectedSequences)
980       {
981         cmb_assSeq.addItem(new AssociateSeqOptions(seq));
982       }
983     }
984     else
985     {
986       String seqName = selectedSequence.getDisplayId(false);
987       seqName = seqName.length() <= 40 ? seqName : seqName.substring(0, 39);
988       lbl_associateSeq.setText(seqName);
989       lbl_associateSeq.setVisible(true);
990       cmb_assSeq.setVisible(false);
991     }
992   }
993
994   protected boolean isStructuresDiscovered()
995   {
996     return discoveredStructuresSet != null
997             && !discoveredStructuresSet.isEmpty();
998   }
999
1000   protected int PDB_ID_MIN = 3;// or: (Jalview.isJS() ? 3 : 1); // Bob proposes
1001                                // this.
1002   // Doing a search for "1" or "1c" is valuable?
1003   // Those work but are enormously slow.
1004
1005   @Override
1006   protected void txt_search_ActionPerformed()
1007   {
1008     String text = txt_search.getText().trim();
1009     if (text.length() >= PDB_ID_MIN)
1010       new Thread()
1011       {
1012
1013         @Override
1014         public void run()
1015         {
1016           errorWarning.setLength(0);
1017           isValidPBDEntry = false;
1018           if (text.length() > 0)
1019           {
1020             // TODO move this pdb id search into the PDB specific
1021             // FTSSearchEngine
1022             // for moment, it will work fine as is because it is self-contained
1023             String searchTerm = text.toLowerCase();
1024             searchTerm = searchTerm.split(":")[0];
1025             // System.out.println(">>>>> search term : " + searchTerm);
1026             List<FTSDataColumnI> wantedFields = new ArrayList<>();
1027             FTSRestRequest pdbRequest = new FTSRestRequest();
1028             pdbRequest.setAllowEmptySeq(false);
1029             pdbRequest.setResponseSize(1);
1030             pdbRequest.setFieldToSearchBy("(pdb_id:");
1031             pdbRequest.setWantedFields(wantedFields);
1032             pdbRequest.setSearchTerm(searchTerm + ")");
1033             pdbRequest.setAssociatedSequence(selectedSequence);
1034             FTSRestClientI pdbRestClient = PDBFTSRestClient.getInstance();
1035             wantedFields.add(pdbRestClient.getPrimaryKeyColumn());
1036             FTSRestResponse resultList;
1037             try
1038             {
1039               resultList = pdbRestClient.executeRequest(pdbRequest);
1040             } catch (Exception e)
1041             {
1042               errorWarning.append(e.getMessage());
1043               return;
1044             } finally
1045             {
1046               validateSelections();
1047             }
1048             if (resultList.getSearchSummary() != null
1049                     && resultList.getSearchSummary().size() > 0)
1050             {
1051               isValidPBDEntry = true;
1052             }
1053           }
1054           validateSelections();
1055         }
1056       }.start();
1057   }
1058
1059   @Override
1060   protected void tabRefresh()
1061   {
1062     if (selectedSequences != null)
1063     {
1064       Thread refreshThread = new Thread(new Runnable()
1065       {
1066         @Override
1067         public void run()
1068         {
1069           fetchStructuresMetaData();
1070           filterResultSet(
1071                   ((FilterOption) cmb_filterOption.getSelectedItem())
1072                           .getValue());
1073         }
1074       });
1075       refreshThread.start();
1076     }
1077   }
1078
1079   public class PDBEntryTableModel extends AbstractTableModel
1080   {
1081     String[] columns = { "Ref Sequence", "PDB Id", "Chain", "Type",
1082         "File" };
1083
1084     private List<CachedPDB> pdbEntries;
1085
1086     public PDBEntryTableModel(List<CachedPDB> pdbEntries)
1087     {
1088       this.pdbEntries = new ArrayList<>(pdbEntries);
1089     }
1090
1091     @Override
1092     public String getColumnName(int columnIndex)
1093     {
1094       return columns[columnIndex];
1095     }
1096
1097     @Override
1098     public int getRowCount()
1099     {
1100       return pdbEntries.size();
1101     }
1102
1103     @Override
1104     public int getColumnCount()
1105     {
1106       return columns.length;
1107     }
1108
1109     @Override
1110     public boolean isCellEditable(int row, int column)
1111     {
1112       return false;
1113     }
1114
1115     @Override
1116     public Object getValueAt(int rowIndex, int columnIndex)
1117     {
1118       Object value = "??";
1119       CachedPDB entry = pdbEntries.get(rowIndex);
1120       switch (columnIndex)
1121       {
1122       case 0:
1123         value = entry.getSequence();
1124         break;
1125       case 1:
1126         value = entry.getPdbEntry();
1127         break;
1128       case 2:
1129         value = entry.getPdbEntry().getChainCode() == null ? "_"
1130                 : entry.getPdbEntry().getChainCode();
1131         break;
1132       case 3:
1133         value = entry.getPdbEntry().getType();
1134         break;
1135       case 4:
1136         value = entry.getPdbEntry().getFile();
1137         break;
1138       }
1139       return value;
1140     }
1141
1142     @Override
1143     public Class<?> getColumnClass(int columnIndex)
1144     {
1145       return columnIndex == 0 ? SequenceI.class : PDBEntry.class;
1146     }
1147
1148     public CachedPDB getPDBEntryAt(int row)
1149     {
1150       return pdbEntries.get(row);
1151     }
1152
1153   }
1154
1155   private class CachedPDB
1156   {
1157     private SequenceI sequence;
1158
1159     private PDBEntry pdbEntry;
1160
1161     public CachedPDB(SequenceI sequence, PDBEntry pdbEntry)
1162     {
1163       this.sequence = sequence;
1164       this.pdbEntry = pdbEntry;
1165     }
1166
1167     public SequenceI getSequence()
1168     {
1169       return sequence;
1170     }
1171
1172     public PDBEntry getPdbEntry()
1173     {
1174       return pdbEntry;
1175     }
1176
1177   }
1178
1179   private IProgressIndicator progressBar;
1180
1181   @Override
1182   public void setProgressBar(String message, long id)
1183   {
1184     progressBar.setProgressBar(message, id);
1185   }
1186
1187   @Override
1188   public void registerHandler(long id, IProgressIndicatorHandler handler)
1189   {
1190     progressBar.registerHandler(id, handler);
1191   }
1192
1193   @Override
1194   public boolean operationInProgress()
1195   {
1196     return progressBar.operationInProgress();
1197   }
1198
1199   public JalviewStructureDisplayI getOpenedStructureViewer()
1200   {
1201     return sViewer == null ? null : sViewer.sview;
1202   }
1203
1204   @Override
1205   protected void setFTSDocFieldPrefs(FTSDataColumnPreferences newPrefs)
1206   {
1207     data.setDocFieldPrefs(newPrefs);
1208     
1209   }
1210 }