9f15e55c139ca5d6eca6a01ec8ced47c1f2074b8
[jalview.git] / src / jalview / structures / models / AAStructureBindingModel.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 package jalview.structures.models;
22
23 import java.awt.Color;
24 import java.io.File;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.BitSet;
29 import java.util.HashMap;
30 import java.util.LinkedHashMap;
31 import java.util.List;
32 import java.util.Locale;
33 import java.util.Map;
34
35 import javax.swing.SwingUtilities;
36
37 import jalview.api.AlignViewportI;
38 import jalview.api.AlignmentViewPanel;
39 import jalview.api.FeatureRenderer;
40 import jalview.api.SequenceRenderer;
41 import jalview.api.StructureSelectionManagerProvider;
42 import jalview.api.structures.JalviewStructureDisplayI;
43 import jalview.bin.Console;
44 import jalview.datamodel.AlignmentI;
45 import jalview.datamodel.ColumnSelection;
46 import jalview.datamodel.HiddenColumns;
47 import jalview.datamodel.MappedFeatures;
48 import jalview.datamodel.PDBEntry;
49 import jalview.datamodel.SequenceFeature;
50 import jalview.datamodel.SequenceI;
51 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
52 import jalview.gui.AlignmentPanel;
53 import jalview.gui.Desktop;
54 import jalview.gui.StructureViewer.ViewerType;
55 import jalview.io.DataSourceType;
56 import jalview.io.StructureFile;
57 import jalview.renderer.seqfeatures.FeatureColourFinder;
58 import jalview.schemes.ColourSchemeI;
59 import jalview.schemes.ResidueProperties;
60 import jalview.structure.AtomSpec;
61 import jalview.structure.AtomSpecModel;
62 import jalview.structure.StructureCommandI;
63 import jalview.structure.StructureCommandsI;
64 import jalview.structure.StructureCommandsI.AtomSpecType;
65 import jalview.structure.StructureListener;
66 import jalview.structure.StructureMapping;
67 import jalview.structure.StructureSelectionManager;
68 import jalview.util.Comparison;
69 import jalview.util.MessageManager;
70
71 /**
72  * 
73  * A base class to hold common function for 3D structure model binding. Initial
74  * version created by refactoring JMol and Chimera binding models, but other
75  * structure viewers could in principle be accommodated in future.
76  * 
77  * @author gmcarstairs
78  *
79  */
80 public abstract class AAStructureBindingModel
81         extends SequenceStructureBindingModel
82         implements StructureListener, StructureSelectionManagerProvider
83 {
84   /**
85    * Data bean class to simplify parameterisation in superposeStructures
86    */
87   public static class SuperposeData
88   {
89     public String filename;
90
91     public String pdbId;
92
93     public String chain = "";
94
95     /**
96      * is the mapped sequence not protein ?
97      */
98     public boolean isRna;
99
100     /*
101      * The pdb residue number (if any) mapped to columns of the alignment
102      */
103     public int[] pdbResNo; // or use SparseIntArray?
104
105     public String modelId;
106
107     /**
108      * Constructor
109      * 
110      * @param width
111      *          width of alignment (number of columns that may potentially
112      *          participate in superposition)
113      * @param model
114      *          structure viewer model number
115      */
116     public SuperposeData(int width, String model)
117     {
118       pdbResNo = new int[width];
119       modelId = model;
120     }
121   }
122
123   private static final int MIN_POS_TO_SUPERPOSE = 4;
124
125   private static final String COLOURING_STRUCTURES = MessageManager
126           .getString("status.colouring_structures");
127
128   /*
129    * the Jalview panel through which the user interacts
130    * with the structure viewer
131    */
132   private JalviewStructureDisplayI viewer;
133
134   /*
135    * helper that generates command syntax
136    */
137   private StructureCommandsI commandGenerator;
138
139   private StructureSelectionManager ssm;
140
141   /*
142    * modelled chains, formatted as "pdbid:chainCode"
143    */
144   private List<String> chainNames;
145
146   /*
147    * lookup of pdb file name by key "pdbid:chainCode"
148    */
149   private Map<String, String> chainFile;
150
151   /*
152    * distinct PDB entries (pdb files) associated
153    * with sequences
154    */
155   private PDBEntry[] pdbEntry;
156
157   /*
158    * sequences mapped to each pdbentry
159    */
160   private SequenceI[][] sequence;
161
162   /*
163    * array of target chains for sequences - tied to pdbentry and sequence[]
164    */
165   private String[][] chains;
166
167   /*
168    * datasource protocol for access to PDBEntrylatest
169    */
170   DataSourceType protocol = null;
171
172   protected boolean colourBySequence = true;
173
174   /**
175    * true if all sequences appear to be nucleotide
176    */
177   private boolean nucleotide;
178
179   private boolean finishedInit = false;
180
181   /**
182    * current set of model filenames loaded in the viewer
183    */
184   protected String[] modelFileNames = null;
185
186   public String fileLoadingError;
187
188   protected Thread externalViewerMonitor;
189
190   /**
191    * Constructor
192    * 
193    * @param ssm
194    * @param seqs
195    */
196   public AAStructureBindingModel(StructureSelectionManager ssm,
197           SequenceI[][] seqs)
198   {
199     this.ssm = ssm;
200     this.sequence = seqs;
201     chainNames = new ArrayList<>();
202     chainFile = new HashMap<>();
203   }
204
205   /**
206    * Constructor
207    * 
208    * @param ssm
209    * @param pdbentry
210    * @param sequenceIs
211    * @param protocol
212    */
213   public AAStructureBindingModel(StructureSelectionManager ssm,
214           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
215           DataSourceType protocol)
216   {
217     this(ssm, sequenceIs);
218     this.nucleotide = Comparison.isNucleotide(sequenceIs);
219     this.pdbEntry = pdbentry;
220     this.protocol = protocol;
221     resolveChains();
222   }
223
224   private boolean resolveChains()
225   {
226     /**
227      * final count of chain mappings discovered
228      */
229     int chainmaps = 0;
230     // JBPNote: JAL-2693 - this should be a list of chain mappings per
231     // [pdbentry][sequence]
232     String[][] newchains = new String[pdbEntry.length][];
233     int pe = 0;
234     for (PDBEntry pdb : pdbEntry)
235     {
236       SequenceI[] seqsForPdb = sequence[pe];
237       if (seqsForPdb != null)
238       {
239         newchains[pe] = new String[seqsForPdb.length];
240         int se = 0;
241         for (SequenceI asq : seqsForPdb)
242         {
243           String chain = (chains != null && chains[pe] != null)
244                   ? chains[pe][se]
245                   : null;
246           SequenceI sq = (asq.getDatasetSequence() == null) ? asq
247                   : asq.getDatasetSequence();
248           if (sq.getAllPDBEntries() != null)
249           {
250             for (PDBEntry pdbentry : sq.getAllPDBEntries())
251             {
252               if (pdb.getFile() != null && pdbentry.getFile() != null
253                       && pdb.getFile().equals(pdbentry.getFile()))
254               {
255                 String chaincode = pdbentry.getChainCode();
256                 if (chaincode != null && chaincode.length() > 0)
257                 {
258                   chain = chaincode;
259                   chainmaps++;
260                   break;
261                 }
262               }
263             }
264           }
265           newchains[pe][se] = chain;
266           se++;
267         }
268         pe++;
269       }
270     }
271
272     chains = newchains;
273     return chainmaps > 0;
274   }
275
276   public StructureSelectionManager getSsm()
277   {
278     return ssm;
279   }
280
281   /**
282    * Returns the i'th PDBEntry (or null)
283    * 
284    * @param i
285    * @return
286    */
287   public PDBEntry getPdbEntry(int i)
288   {
289     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
290   }
291
292   /**
293    * Answers true if this binding includes the given PDB id, else false
294    * 
295    * @param pdbId
296    * @return
297    */
298   public boolean hasPdbId(String pdbId)
299   {
300     if (pdbEntry != null)
301     {
302       for (PDBEntry pdb : pdbEntry)
303       {
304         if (pdb.getId().equals(pdbId))
305         {
306           return true;
307         }
308       }
309     }
310     return false;
311   }
312
313   /**
314    * Returns the number of modelled PDB file entries.
315    * 
316    * @return
317    */
318   public int getPdbCount()
319   {
320     return pdbEntry == null ? 0 : pdbEntry.length;
321   }
322
323   public SequenceI[][] getSequence()
324   {
325     return sequence;
326   }
327
328   public String[][] getChains()
329   {
330     return chains;
331   }
332
333   public DataSourceType getProtocol()
334   {
335     return protocol;
336   }
337
338   // TODO may remove this if calling methods can be pulled up here
339   protected void setPdbentry(PDBEntry[] pdbentry)
340   {
341     this.pdbEntry = pdbentry;
342   }
343
344   protected void setSequence(SequenceI[][] sequence)
345   {
346     this.sequence = sequence;
347   }
348
349   protected void setChains(String[][] chains)
350   {
351     this.chains = chains;
352   }
353
354   /**
355    * Construct a title string for the viewer window based on the data Jalview
356    * knows about
357    * 
358    * @param viewerName
359    *          TODO
360    * @param verbose
361    * 
362    * @return
363    */
364   public String getViewerTitle(String viewerName, boolean verbose)
365   {
366     if (getSequence() == null || getSequence().length < 1
367             || getPdbCount() < 1 || getSequence()[0].length < 1)
368     {
369       return ("Jalview " + viewerName + " Window");
370     }
371     // TODO: give a more informative title when multiple structures are
372     // displayed.
373     StringBuilder title = new StringBuilder(64);
374     final PDBEntry pdbe = getPdbEntry(0);
375     title.append(viewerName + " view for " + getSequence()[0][0].getName()
376             + ":" + pdbe.getId());
377
378     if (verbose)
379     {
380       String method = (String) pdbe.getProperty("method");
381       if (method != null)
382       {
383         title.append(" Method: ").append(method);
384       }
385       String chain = (String) pdbe.getProperty("chains");
386       if (chain != null)
387       {
388         title.append(" Chain:").append(chain);
389       }
390     }
391     return title.toString();
392   }
393
394   /**
395    * Called by after closeViewer is called, to release any resources and
396    * references so they can be garbage collected. Override if needed.
397    */
398   protected void releaseUIResources()
399   {
400   }
401
402   @Override
403   public void releaseReferences(Object svl)
404   {
405   }
406
407   public boolean isColourBySequence()
408   {
409     return colourBySequence;
410   }
411
412   /**
413    * Called when the binding thinks the UI needs to be refreshed after a
414    * structure viewer state change. This could be because structures were
415    * loaded, or because an error has occurred. Default does nothing, override as
416    * required.
417    */
418   public void refreshGUI()
419   {
420   }
421
422   /**
423    * Instruct the Jalview binding to update the pdbentries vector if necessary
424    * prior to matching the jmol view's contents to the list of structure files
425    * Jalview knows about. By default does nothing, override as required.
426    */
427   public void refreshPdbEntries()
428   {
429   }
430
431   public void setColourBySequence(boolean colourBySequence)
432   {
433     this.colourBySequence = colourBySequence;
434   }
435
436   protected void addSequenceAndChain(int pe, SequenceI[] seq,
437           String[] tchain)
438   {
439     if (pe < 0 || pe >= getPdbCount())
440     {
441       throw new Error(MessageManager.formatMessage(
442               "error.implementation_error_no_pdbentry_from_index",
443               new Object[]
444               { Integer.valueOf(pe).toString() }));
445     }
446     final String nullChain = "TheNullChain";
447     List<SequenceI> s = new ArrayList<>();
448     List<String> c = new ArrayList<>();
449     if (getChains() == null)
450     {
451       setChains(new String[getPdbCount()][]);
452     }
453     if (getSequence()[pe] != null)
454     {
455       for (int i = 0; i < getSequence()[pe].length; i++)
456       {
457         s.add(getSequence()[pe][i]);
458         if (getChains()[pe] != null)
459         {
460           if (i < getChains()[pe].length)
461           {
462             c.add(getChains()[pe][i]);
463           }
464           else
465           {
466             c.add(nullChain);
467           }
468         }
469         else
470         {
471           if (tchain != null && tchain.length > 0)
472           {
473             c.add(nullChain);
474           }
475         }
476       }
477     }
478     for (int i = 0; i < seq.length; i++)
479     {
480       if (!s.contains(seq[i]))
481       {
482         s.add(seq[i]);
483         if (tchain != null && i < tchain.length)
484         {
485           c.add(tchain[i] == null ? nullChain : tchain[i]);
486         }
487       }
488     }
489     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
490     getSequence()[pe] = tmp;
491     if (c.size() > 0)
492     {
493       String[] tch = c.toArray(new String[c.size()]);
494       for (int i = 0; i < tch.length; i++)
495       {
496         if (tch[i] == nullChain)
497         {
498           tch[i] = null;
499         }
500       }
501       getChains()[pe] = tch;
502     }
503     else
504     {
505       getChains()[pe] = null;
506     }
507   }
508
509   /**
510    * add structures and any known sequence associations
511    * 
512    * @returns the pdb entries added to the current set.
513    */
514   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
515           SequenceI[][] seq, String[][] chns)
516   {
517     List<PDBEntry> v = new ArrayList<>();
518     List<int[]> rtn = new ArrayList<>();
519     for (int i = 0; i < getPdbCount(); i++)
520     {
521       v.add(getPdbEntry(i));
522     }
523     for (int i = 0; i < pdbe.length; i++)
524     {
525       int r = v.indexOf(pdbe[i]);
526       if (r == -1 || r >= getPdbCount())
527       {
528         rtn.add(new int[] { v.size(), i });
529         v.add(pdbe[i]);
530       }
531       else
532       {
533         // just make sure the sequence/chain entries are all up to date
534         addSequenceAndChain(r, seq[i], chns[i]);
535       }
536     }
537     pdbe = v.toArray(new PDBEntry[v.size()]);
538     setPdbentry(pdbe);
539     if (rtn.size() > 0)
540     {
541       // expand the tied sequence[] and string[] arrays
542       SequenceI[][] sqs = new SequenceI[getPdbCount()][];
543       String[][] sch = new String[getPdbCount()][];
544       System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
545       System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
546       setSequence(sqs);
547       setChains(sch);
548       pdbe = new PDBEntry[rtn.size()];
549       for (int r = 0; r < pdbe.length; r++)
550       {
551         int[] stri = (rtn.get(r));
552         // record the pdb file as a new addition
553         pdbe[r] = getPdbEntry(stri[0]);
554         // and add the new sequence/chain entries
555         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
556       }
557     }
558     else
559     {
560       pdbe = null;
561     }
562     return pdbe;
563   }
564
565   /**
566    * Add sequences to the pe'th pdbentry's sequence set.
567    * 
568    * @param pe
569    * @param seq
570    */
571   public void addSequence(int pe, SequenceI[] seq)
572   {
573     addSequenceAndChain(pe, seq, null);
574   }
575
576   /**
577    * add the given sequences to the mapping scope for the given pdb file handle
578    * 
579    * @param pdbFile
580    *          - pdbFile identifier
581    * @param seq
582    *          - set of sequences it can be mapped to
583    */
584   public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
585   {
586     for (int pe = 0; pe < getPdbCount(); pe++)
587     {
588       if (getPdbEntry(pe).getFile().equals(pdbFile))
589       {
590         addSequence(pe, seq);
591       }
592     }
593   }
594
595   @Override
596   public abstract void highlightAtoms(List<AtomSpec> atoms);
597
598   protected boolean isNucleotide()
599   {
600     return this.nucleotide;
601   }
602
603   /**
604    * Returns a readable description of all mappings for the wrapped pdbfile to
605    * any mapped sequences
606    * 
607    * @param pdbfile
608    * @param seqs
609    * @return
610    */
611   public String printMappings()
612   {
613     if (pdbEntry == null)
614     {
615       return "";
616     }
617     StringBuilder sb = new StringBuilder(128);
618     for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
619     {
620       String pdbfile = getPdbEntry(pdbe).getFile();
621       List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
622       sb.append(getSsm().printMappings(pdbfile, seqs));
623     }
624     return sb.toString();
625   }
626
627   /**
628    * Returns the mapped structure position for a given aligned column of a given
629    * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
630    * not mapped to structure.
631    * 
632    * @param seq
633    * @param alignedPos
634    * @param mapping
635    * @return
636    */
637   protected int getMappedPosition(SequenceI seq, int alignedPos,
638           StructureMapping mapping)
639   {
640     if (alignedPos >= seq.getLength())
641     {
642       return -1;
643     }
644
645     if (Comparison.isGap(seq.getCharAt(alignedPos)))
646     {
647       return -1;
648     }
649     int seqPos = seq.findPosition(alignedPos);
650     int pos = mapping.getPDBResNum(seqPos);
651     return pos;
652   }
653
654   /**
655    * Helper method to identify residues that can participate in a structure
656    * superposition command. For each structure, identify a sequence in the
657    * alignment which is mapped to the structure. Identify non-gapped columns in
658    * the sequence which have a mapping to a residue in the structure. Returns
659    * the index of the first structure that has a mapping to the alignment.
660    * 
661    * @param alignment
662    *          the sequence alignment which is the basis of structure
663    *          superposition
664    * @param matched
665    *          a BitSet, where bit j is set to indicate that every structure has
666    *          a mapped residue present in column j (so the column can
667    *          participate in structure alignment)
668    * @param structures
669    *          an array of data beans corresponding to pdb file index
670    * @return
671    */
672   protected int findSuperposableResidues(AlignmentI alignment,
673           BitSet matched,
674           AAStructureBindingModel.SuperposeData[] structures)
675   {
676     int refStructure = -1;
677     String[] files = getStructureFiles();
678     if (files == null)
679     {
680       return -1;
681     }
682     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
683     {
684       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
685       int lastPos = -1;
686
687       /*
688        * Find the first mapped sequence (if any) for this PDB entry which is in
689        * the alignment
690        */
691       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
692       for (int s = 0; s < seqCountForPdbFile; s++)
693       {
694         for (StructureMapping mapping : mappings)
695         {
696           final SequenceI theSequence = getSequence()[pdbfnum][s];
697           if (mapping.getSequence() == theSequence
698                   && alignment.findIndex(theSequence) > -1)
699           {
700             if (refStructure < 0)
701             {
702               refStructure = pdbfnum;
703             }
704             for (int r = 0; r < alignment.getWidth(); r++)
705             {
706               if (!matched.get(r))
707               {
708                 continue;
709               }
710               int pos = getMappedPosition(theSequence, r, mapping);
711               if (pos < 1 || pos == lastPos)
712               {
713                 matched.clear(r);
714                 continue;
715               }
716               lastPos = pos;
717               structures[pdbfnum].pdbResNo[r] = pos;
718             }
719             String chain = mapping.getChain();
720             if (chain != null && chain.trim().length() > 0)
721             {
722               structures[pdbfnum].chain = chain;
723             }
724             structures[pdbfnum].pdbId = mapping.getPdbId();
725             structures[pdbfnum].isRna = !theSequence.isProtein();
726
727             /*
728              * move on to next pdb file (ignore sequences for other chains
729              * for the same structure)
730              */
731             s = seqCountForPdbFile;
732             break; // fixme break out of two loops here!
733           }
734         }
735       }
736     }
737     return refStructure;
738   }
739
740   /**
741    * Returns true if the structure viewer has loaded all of the files of
742    * interest (identified by the file mapping having been set up), or false if
743    * any are still not loaded after a timeout interval.
744    * 
745    * @param files
746    */
747   protected boolean waitForFileLoad(String[] files)
748   {
749     /*
750      * give up after 10 secs plus 1 sec per file
751      */
752     long starttime = System.currentTimeMillis();
753     long endTime = 10000 + 1000 * files.length + starttime;
754     String notLoaded = null;
755
756     boolean waiting = true;
757     while (waiting && System.currentTimeMillis() < endTime)
758     {
759       waiting = false;
760       for (String file : files)
761       {
762         notLoaded = file;
763         if (file == null)
764         {
765           continue;
766         }
767         try
768         {
769           StructureMapping[] sm = getSsm().getMapping(file);
770           if (sm == null || sm.length == 0)
771           {
772             waiting = true;
773           }
774         } catch (Throwable x)
775         {
776           waiting = true;
777         }
778       }
779     }
780
781     if (waiting)
782     {
783       jalview.bin.Console.errPrintln(
784               "Timed out waiting for structure viewer to load file "
785                       + notLoaded);
786       return false;
787     }
788     return true;
789   }
790
791   @Override
792   public boolean isListeningFor(SequenceI seq)
793   {
794     if (sequence != null)
795     {
796       for (SequenceI[] seqs : sequence)
797       {
798         if (seqs != null)
799         {
800           for (SequenceI s : seqs)
801           {
802             if (s == seq || (s.getDatasetSequence() != null
803                     && s.getDatasetSequence() == seq.getDatasetSequence()))
804             {
805               return true;
806             }
807           }
808         }
809       }
810     }
811     return false;
812   }
813
814   public boolean isFinishedInit()
815   {
816     return finishedInit;
817   }
818
819   public void setFinishedInit(boolean fi)
820   {
821     this.finishedInit = fi;
822   }
823
824   /**
825    * Returns a list of chains mapped in this viewer, formatted as
826    * "pdbid:chainCode"
827    * 
828    * @return
829    */
830   public List<String> getChainNames()
831   {
832     return chainNames;
833   }
834
835   /**
836    * Returns the Jalview panel hosting the structure viewer (if any)
837    * 
838    * @return
839    */
840   public JalviewStructureDisplayI getViewer()
841   {
842     return viewer;
843   }
844
845   public void setViewer(JalviewStructureDisplayI v)
846   {
847     viewer = v;
848   }
849
850   /**
851    * Constructs and sends a command to align structures against a reference
852    * structure, based on one or more sequence alignments. May optionally return
853    * an error or warning message for the alignment command(s).
854    * 
855    * @param alignWith
856    *          an array of one or more alignment views to process
857    * @return
858    */
859   public String superposeStructures(List<AlignmentViewPanel> alignWith)
860   {
861     String error = "";
862     String[] files = getStructureFiles();
863
864     if (!waitForFileLoad(files))
865     {
866       return null;
867     }
868     refreshPdbEntries();
869
870     for (AlignmentViewPanel view : alignWith)
871     {
872       AlignmentI alignment = view.getAlignment();
873       HiddenColumns hiddenCols = alignment.getHiddenColumns();
874       /*
875        * 'matched' bit i will be set for visible alignment columns i where
876        * all sequences have a residue with a mapping to their PDB structure
877        */
878       final int width = alignment.getWidth();
879       BitSet matched = new BitSet();
880       ColumnSelection cs = view.getAlignViewport().getColumnSelection();
881       // restrict to active column selection, if there is one
882       if (cs != null && cs.hasSelectedColumns()
883               && cs.getSelected().size() >= 4)
884       {
885         for (int s : cs.getSelected())
886         {
887           if (hiddenCols == null)
888           {
889             matched.set(s);
890           }
891           else
892           {
893             matched.set(hiddenCols.visibleToAbsoluteColumn(s));
894           }
895         }
896       }
897       else
898       {
899         for (int m = 0; m < width; m++)
900         {
901           if (hiddenCols == null || hiddenCols.isVisible(m))
902           {
903             matched.set(m);
904           }
905         }
906       }
907       AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
908       for (int f = 0; f < files.length; f++)
909       {
910         structures[f] = new AAStructureBindingModel.SuperposeData(width,
911                 getModelIdForFile(files[f]));
912       }
913
914       /*
915        * Calculate the superposable alignment columns ('matched'), and the
916        * corresponding structure residue positions (structures.pdbResNo)
917        */
918       int refStructure = findSuperposableResidues(alignment, matched,
919               structures);
920
921       /*
922        * require at least 4 positions to be able to execute superposition
923        */
924       int nmatched = matched.cardinality();
925       if (nmatched < MIN_POS_TO_SUPERPOSE)
926       {
927         String msg = MessageManager
928                 .formatMessage("label.insufficient_residues", nmatched);
929         error += view.getViewName() + ": " + msg + "; ";
930         continue;
931       }
932
933       /*
934        * get a model of the superposable residues in the reference structure 
935        */
936       AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
937               matched);
938
939       /*
940        * Show all as backbone before doing superposition(s)
941        * (residues used for matching will be shown as ribbon)
942        */
943       // todo better way to ensure synchronous than setting getReply true!!
944       executeCommands(commandGenerator.showBackbone(), true, null);
945
946       AtomSpecType backbone = structures[refStructure].isRna
947               ? AtomSpecType.PHOSPHATE
948               : AtomSpecType.ALPHA;
949       List<AtomSpecModel> models = new ArrayList<AtomSpecModel>();
950       models.add(refAtoms);
951       /*
952        * superpose each (other) structure to the reference in turn
953        */
954       for (int i = 0; i < structures.length; i++)
955       {
956         if (i != refStructure)
957         {
958           AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
959           List<StructureCommandI> commands = commandGenerator
960                   .superposeStructures(refAtoms, atomSpec, backbone);
961           List<String> replies = executeCommands(commands, true, null);
962           for (String reply : replies)
963           {
964             // return this error (Chimera only) to the user
965             if (reply.toLowerCase(Locale.ROOT)
966                     .contains("unequal numbers of atoms"))
967             {
968               error += "; " + reply;
969             }
970           }
971           models.add(atomSpec);
972         }
973       }
974       List<StructureCommandI> finalView = commandGenerator
975               .centerViewOn(models);
976       if (finalView != null && finalView.size() > 0)
977       {
978         executeCommands(finalView, false, "Centered on Superposition");
979       }
980     }
981     return error;
982   }
983
984   private AtomSpecModel getAtomSpec(
985           AAStructureBindingModel.SuperposeData superposeData,
986           BitSet matched)
987   {
988     AtomSpecModel model = new AtomSpecModel();
989     int nextColumnMatch = matched.nextSetBit(0);
990     while (nextColumnMatch != -1)
991     {
992       int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
993       model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
994               superposeData.chain);
995       nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
996     }
997
998     return model;
999   }
1000
1001   /**
1002    * returns the current sequenceRenderer that should be used to colour the
1003    * structures
1004    * 
1005    * @param alignment
1006    * 
1007    * @return
1008    */
1009   public abstract SequenceRenderer getSequenceRenderer(
1010           AlignmentViewPanel alignment);
1011
1012   /**
1013    * Sends a command to the structure viewer to colour each chain with a
1014    * distinct colour (to the extent supported by the viewer)
1015    */
1016   public void colourByChain()
1017   {
1018     colourBySequence = false;
1019
1020     // TODO: JAL-628 colour chains distinctly across all visible models
1021
1022     executeCommand(false, COLOURING_STRUCTURES,
1023             commandGenerator.colourByChain());
1024   }
1025
1026   /**
1027    * Sends a command to the structure viewer to colour each chain with a
1028    * distinct colour (to the extent supported by the viewer)
1029    */
1030   public void colourByCharge()
1031   {
1032     colourBySequence = false;
1033
1034     executeCommands(commandGenerator.colourByCharge(), false,
1035             COLOURING_STRUCTURES);
1036   }
1037
1038   /**
1039    * Sends a command to the structure to apply a colour scheme (defined in
1040    * Jalview but not necessarily applied to the alignment), which defines a
1041    * colour per residue letter. More complex schemes (e.g. that depend on
1042    * consensus) cannot be used here and are ignored.
1043    * 
1044    * @param cs
1045    */
1046   public void colourByJalviewColourScheme(ColourSchemeI cs)
1047   {
1048     colourBySequence = false;
1049
1050     if (cs == null || !cs.isSimple())
1051     {
1052       return;
1053     }
1054
1055     /*
1056      * build a map of {Residue3LetterCode, Color}
1057      */
1058     Map<String, Color> colours = new HashMap<>();
1059     List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1060             false);
1061     for (String resName : residues)
1062     {
1063       char res = resName.length() == 3
1064               ? ResidueProperties.getSingleCharacterCode(resName)
1065               : resName.charAt(0);
1066       Color colour = cs.findColour(res, 0, null, null, 0f);
1067       colours.put(resName, colour);
1068     }
1069
1070     /*
1071      * pass to the command constructor, and send the command
1072      */
1073     List<StructureCommandI> cmd = commandGenerator
1074             .colourByResidues(colours);
1075     executeCommands(cmd, false, COLOURING_STRUCTURES);
1076   }
1077
1078   public void setBackgroundColour(Color col)
1079   {
1080     StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1081     executeCommand(false, null, cmd);
1082   }
1083
1084   /**
1085    * Execute one structure viewer command. If {@code getReply} is true, may
1086    * optionally return one or more reply messages, else returns null.
1087    * 
1088    * @param cmd
1089    * @param getReply
1090    */
1091   protected abstract List<String> executeCommand(StructureCommandI cmd,
1092           boolean getReply);
1093
1094   /**
1095    * Executes one or more structure viewer commands
1096    * 
1097    * @param commands
1098    * @param getReply
1099    * @param msg
1100    */
1101   protected List<String> executeCommands(List<StructureCommandI> commands,
1102           boolean getReply, String msg)
1103   {
1104     return executeCommand(getReply, msg,
1105             commands.toArray(new StructureCommandI[commands.size()]));
1106   }
1107
1108   /**
1109    * Executes one or more structure viewer commands, optionally returning the
1110    * reply, and optionally showing a status message while the command is being
1111    * executed.
1112    * <p>
1113    * If a reply is wanted, the execution is done synchronously (waits),
1114    * otherwise it is done in a separate thread (doesn't wait). WARNING: if you
1115    * are sending commands that need to execute before later calls to
1116    * executeCommand (e.g. mouseovers, which clean up after previous ones) then
1117    * set getReply true to ensure that commands are not executed out of order.
1118    * 
1119    * @param getReply
1120    * @param msg
1121    * @param cmds
1122    * @return
1123    */
1124   protected List<String> executeCommand(boolean getReply, String msg,
1125           StructureCommandI... cmds)
1126   {
1127     JalviewStructureDisplayI theViewer = getViewer();
1128     final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1129
1130     if (getReply)
1131     {
1132       /*
1133        * execute and wait for reply
1134        */
1135       List<String> response = new ArrayList<>();
1136       try
1137       {
1138         for (StructureCommandI cmd : cmds)
1139         {
1140           List<String> replies = executeCommand(cmd, true);
1141           if (replies != null)
1142           {
1143             response.addAll(replies);
1144           }
1145         }
1146         return response;
1147       } finally
1148       {
1149         if (msg != null)
1150         {
1151           theViewer.stopProgressBar(null, handle);
1152         }
1153       }
1154     }
1155
1156     /*
1157      * fire and forget
1158      */
1159     String threadName = msg == null ? "StructureCommand" : msg;
1160     new Thread(new Runnable()
1161     {
1162       @Override
1163       public void run()
1164       {
1165         try
1166         {
1167           for (StructureCommandI cmd : cmds)
1168           {
1169             executeCommand(cmd, false);
1170           }
1171         } finally
1172         {
1173           if (msg != null)
1174           {
1175             SwingUtilities.invokeLater(new Runnable()
1176             {
1177               @Override
1178               public void run()
1179               {
1180                 theViewer.stopProgressBar(null, handle);
1181               }
1182             });
1183           }
1184         }
1185       }
1186     }, threadName).start();
1187     return null;
1188   }
1189
1190   /**
1191    * Colours any structures associated with sequences in the given alignment as
1192    * coloured in the alignment view, provided colourBySequence is enabled
1193    */
1194   public void colourBySequence(AlignmentViewPanel alignmentv)
1195   {
1196     if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1197     {
1198       return;
1199     }
1200     Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1201             alignmentv);
1202
1203     List<StructureCommandI> colourBySequenceCommands = commandGenerator
1204             .colourBySequence(colourMap);
1205     executeCommands(colourBySequenceCommands, false, COLOURING_STRUCTURES);
1206   }
1207
1208   /**
1209    * Centre the display in the structure viewer
1210    */
1211   public void focusView()
1212   {
1213     executeCommand(false, null, commandGenerator.focusView());
1214   }
1215
1216   /**
1217    * Generates and executes a command to show only specified chains in the
1218    * structure viewer. The list of chains to show should contain entries
1219    * formatted as "pdbid:chaincode".
1220    * 
1221    * @param toShow
1222    */
1223   public void showChains(List<String> toShow)
1224   {
1225     // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1226
1227     /*
1228      * Reformat the pdbid:chainCode values as modelNo:chainCode
1229      * since this is what is needed to construct the viewer command
1230      * todo: find a less messy way to do this
1231      */
1232     List<String> showThese = new ArrayList<>();
1233     for (String chainId : toShow)
1234     {
1235       String[] tokens = chainId.split("\\:");
1236       if (tokens.length == 2)
1237       {
1238         String pdbFile = getFileForChain(chainId);
1239         String model = getModelIdForFile(pdbFile);
1240         showThese.add(model + ":" + tokens[1]);
1241       }
1242     }
1243     executeCommands(commandGenerator.showChains(showThese), false, null);
1244   }
1245
1246   /**
1247    * Answers the structure viewer's model id given a PDB file name. Returns an
1248    * empty string if model id is not found.
1249    * 
1250    * @param chainId
1251    * @return
1252    */
1253   protected abstract String getModelIdForFile(String chainId);
1254
1255   public boolean hasFileLoadingError()
1256   {
1257     return fileLoadingError != null && fileLoadingError.length() > 0;
1258   }
1259
1260   /**
1261    * Returns the FeatureRenderer for the given alignment view
1262    * 
1263    * @param avp
1264    * @return
1265    */
1266   public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1267   {
1268     AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1269             : avp;
1270     if (ap == null)
1271     {
1272       return null;
1273     }
1274     return ap.getFeatureRenderer();
1275   }
1276
1277   protected void setStructureCommands(StructureCommandsI cmd)
1278   {
1279     commandGenerator = cmd;
1280   }
1281
1282   /**
1283    * Records association of one chain id (formatted as "pdbid:chainCode") with
1284    * the corresponding PDB file name
1285    * 
1286    * @param chainId
1287    * @param fileName
1288    */
1289   public void addChainFile(String chainId, String fileName)
1290   {
1291     chainFile.put(chainId, fileName);
1292   }
1293
1294   /**
1295    * Returns the PDB filename for the given chain id (formatted as
1296    * "pdbid:chainCode"), or null if not found
1297    * 
1298    * @param chainId
1299    * @return
1300    */
1301   protected String getFileForChain(String chainId)
1302   {
1303     return chainFile.get(chainId);
1304   }
1305
1306   @Override
1307   public void updateColours(Object source)
1308   {
1309     if (getViewer() == null)
1310     {
1311       // can happen if a viewer was not instantiated or cleaned up and is still
1312       // registered - mostly during tests
1313       return;
1314     }
1315     AlignmentViewPanel ap = (AlignmentViewPanel) source;
1316     // ignore events from panels not used to colour this view
1317     if (!getViewer().isUsedForColourBy(ap))
1318     {
1319       return;
1320     }
1321     if (!isLoadingFromArchive())
1322     {
1323       colourBySequence(ap);
1324     }
1325   }
1326
1327   public StructureCommandsI getCommandGenerator()
1328   {
1329     return commandGenerator;
1330   }
1331
1332   protected abstract ViewerType getViewerType();
1333
1334   /**
1335    * Builds a data structure which records mapped structure residues for each
1336    * colour. From this we can easily generate the viewer commands for colour by
1337    * sequence. Constructs and returns a map of {@code Color} to
1338    * {@code AtomSpecModel}, where the atomspec model holds
1339    * 
1340    * <pre>
1341    *   Model ids
1342    *     Chains
1343    *       Residue positions
1344    * </pre>
1345    * 
1346    * Ordering is by order of addition (for colours), natural ordering (for
1347    * models and chains)
1348    * 
1349    * @param ssm
1350    * @param sequence
1351    * @param viewPanel
1352    * @return
1353    */
1354   protected Map<Object, AtomSpecModel> buildColoursMap(
1355           StructureSelectionManager ssm, SequenceI[][] sequence,
1356           AlignmentViewPanel viewPanel)
1357   {
1358     String[] files = getStructureFiles();
1359     SequenceRenderer sr = getSequenceRenderer(viewPanel);
1360     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1361     FeatureColourFinder finder = new FeatureColourFinder(fr);
1362     AlignViewportI viewport = viewPanel.getAlignViewport();
1363     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1364     AlignmentI al = viewport.getAlignment();
1365     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1366     Color lastColour = null;
1367
1368     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1369     {
1370       final String modelId = getModelIdForFile(files[pdbfnum]);
1371       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1372
1373       if (mapping == null || mapping.length < 1)
1374       {
1375         continue;
1376       }
1377
1378       int startPos = -1, lastPos = -1;
1379       String lastChain = "";
1380       for (int s = 0; s < sequence[pdbfnum].length; s++)
1381       {
1382         for (int sp, m = 0; m < mapping.length; m++)
1383         {
1384           final SequenceI seq = sequence[pdbfnum][s];
1385           if (mapping[m].getSequence() == seq
1386                   && (sp = al.findIndex(seq)) > -1)
1387           {
1388             SequenceI asp = al.getSequenceAt(sp);
1389             for (int r = 0; r < asp.getLength(); r++)
1390             {
1391               // no mapping to gaps in sequence
1392               if (Comparison.isGap(asp.getCharAt(r)))
1393               {
1394                 continue;
1395               }
1396               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1397
1398               if (pos < 1 || pos == lastPos)
1399               {
1400                 continue;
1401               }
1402
1403               Color colour = sr.getResidueColour(seq, r, finder);
1404
1405               /*
1406                * darker colour for hidden regions
1407                */
1408               if (!cs.isVisible(r))
1409               {
1410                 colour = Color.GRAY;
1411               }
1412
1413               final String chain = mapping[m].getChain();
1414
1415               /*
1416                * Just keep incrementing the end position for this colour range
1417                * _unless_ colour, PDB model or chain has changed, or there is a
1418                * gap in the mapped residue sequence
1419                */
1420               final boolean newColour = !colour.equals(lastColour);
1421               final boolean nonContig = lastPos + 1 != pos;
1422               final boolean newChain = !chain.equals(lastChain);
1423               if (newColour || nonContig || newChain)
1424               {
1425                 if (startPos != -1)
1426                 {
1427                   addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1428                           lastPos, lastChain);
1429                 }
1430                 startPos = pos;
1431               }
1432               lastColour = colour;
1433               lastPos = pos;
1434               lastChain = chain;
1435             }
1436             // final colour range
1437             if (lastColour != null)
1438             {
1439               addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1440                       lastPos, lastChain);
1441             }
1442             // break;
1443           }
1444         }
1445       }
1446     }
1447     return colourMap;
1448   }
1449
1450   /**
1451    * todo better refactoring (map lookup or similar to get viewer structure id)
1452    * 
1453    * @param pdbfnum
1454    * @param file
1455    * @return
1456    */
1457   protected String getModelId(int pdbfnum, String file)
1458   {
1459     return String.valueOf(pdbfnum);
1460   }
1461
1462   /**
1463    * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1464    * full PDB file path
1465    * 
1466    * @param pdb
1467    * @param file
1468    */
1469   public void stashFoundChains(StructureFile pdb, String file)
1470   {
1471     for (int i = 0; i < pdb.getChains().size(); i++)
1472     {
1473       String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1474       addChainFile(chid, file);
1475       getChainNames().add(chid);
1476     }
1477   }
1478
1479   /**
1480    * Helper method to add one contiguous range to the AtomSpec model for the
1481    * given value (creating the model if necessary). As used by Jalview,
1482    * {@code value} is
1483    * <ul>
1484    * <li>a colour, when building a 'colour structure by sequence' command</li>
1485    * <li>a feature value, when building a 'set Chimera attributes from features'
1486    * command</li>
1487    * </ul>
1488    * 
1489    * @param map
1490    * @param value
1491    * @param model
1492    * @param startPos
1493    * @param endPos
1494    * @param chain
1495    */
1496   public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1497           Object value, String model, int startPos, int endPos,
1498           String chain)
1499   {
1500     /*
1501      * Get/initialize map of data for the colour
1502      */
1503     AtomSpecModel atomSpec = map.get(value);
1504     if (atomSpec == null)
1505     {
1506       atomSpec = new AtomSpecModel();
1507       map.put(value, atomSpec);
1508     }
1509
1510     atomSpec.addRange(model, startPos, endPos, chain);
1511   }
1512
1513   /**
1514    * Returns the file extension (including '.' separator) to use for a saved
1515    * viewer session file. Default is to return null (not supported), override as
1516    * required.
1517    * 
1518    * @return
1519    */
1520   public String getSessionFileExtension()
1521   {
1522     return null;
1523   }
1524
1525   /**
1526    * If supported, saves the state of the structure viewer to a temporary file
1527    * and returns the file. Returns null and logs an error on any failure.
1528    * 
1529    * @return
1530    */
1531   public File saveSession()
1532   {
1533     String prefix = getViewerType().toString();
1534     String suffix = getSessionFileExtension();
1535     File f = null;
1536     try
1537     {
1538       f = File.createTempFile(prefix, suffix);
1539       saveSession(f);
1540     } catch (IOException e)
1541     {
1542       Console.error(String.format("Error saving %s session: %s", prefix,
1543               e.toString()));
1544     }
1545
1546     return f;
1547   }
1548
1549   /**
1550    * Saves the structure viewer session to the given file
1551    * 
1552    * @param f
1553    */
1554   protected void saveSession(File f)
1555   {
1556     StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1557     if (cmd != null)
1558     {
1559       executeCommand(cmd, false);
1560     }
1561   }
1562
1563   /**
1564    * Returns true if the viewer is an external structure viewer for which the
1565    * process is still alive, else false (for Jmol, or an external viewer which
1566    * the user has independently closed)
1567    * 
1568    * @return
1569    */
1570   public boolean isViewerRunning()
1571   {
1572     return false;
1573   }
1574
1575   /**
1576    * Closes Jalview's structure viewer panel and releases associated resources.
1577    * If it is managing an external viewer program, and {@code forceClose} is
1578    * true, also asks that program to close.
1579    * 
1580    * @param forceClose
1581    */
1582   public void closeViewer(boolean forceClose)
1583   {
1584     getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1585     releaseUIResources();
1586
1587     /*
1588      * end the thread that closes this panel if the external viewer closes
1589      */
1590     if (externalViewerMonitor != null)
1591     {
1592       externalViewerMonitor.interrupt();
1593       externalViewerMonitor = null;
1594     }
1595
1596     stopListening();
1597
1598     if (forceClose)
1599     {
1600       StructureCommandI cmd = getCommandGenerator().closeViewer();
1601       if (cmd != null)
1602       {
1603         executeCommand(cmd, false);
1604       }
1605     }
1606   }
1607
1608   /**
1609    * Returns the URL of a help page for the structure viewer, or null if none is
1610    * known
1611    * 
1612    * @return
1613    */
1614   public String getHelpURL()
1615   {
1616     return null;
1617   }
1618
1619   /**
1620    * <pre>
1621    * Helper method to build a map of 
1622    *   { featureType, { feature value, AtomSpecModel } }
1623    * </pre>
1624    * 
1625    * @param viewPanel
1626    * @return
1627    */
1628   protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1629           AlignmentViewPanel viewPanel)
1630   {
1631     Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1632     String[] files = getStructureFiles();
1633     if (files == null)
1634     {
1635       return theMap;
1636     }
1637
1638     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1639     if (fr == null)
1640     {
1641       return theMap;
1642     }
1643
1644     AlignViewportI viewport = viewPanel.getAlignViewport();
1645     List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1646
1647     /*
1648      * if alignment is showing features from complement, we also transfer
1649      * these features to the corresponding mapped structure residues
1650      */
1651     boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1652     List<String> complementFeatures = new ArrayList<>();
1653     FeatureRenderer complementRenderer = null;
1654     if (showLinkedFeatures)
1655     {
1656       AlignViewportI comp = fr.getViewport().getCodingComplement();
1657       if (comp != null)
1658       {
1659         complementRenderer = Desktop.getAlignFrameFor(comp)
1660                 .getFeatureRenderer();
1661         complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1662       }
1663     }
1664     if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1665     {
1666       return theMap;
1667     }
1668
1669     AlignmentI alignment = viewPanel.getAlignment();
1670     SequenceI[][] seqs = getSequence();
1671
1672     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1673     {
1674       String modelId = getModelIdForFile(files[pdbfnum]);
1675       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1676
1677       if (mapping == null || mapping.length < 1)
1678       {
1679         continue;
1680       }
1681
1682       for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1683       {
1684         for (int m = 0; m < mapping.length; m++)
1685         {
1686           final SequenceI seq = seqs[pdbfnum][seqNo];
1687           int sp = alignment.findIndex(seq);
1688           StructureMapping structureMapping = mapping[m];
1689           if (structureMapping.getSequence() == seq && sp > -1)
1690           {
1691             /*
1692              * found a sequence with a mapping to a structure;
1693              * now scan its features
1694              */
1695             if (!visibleFeatures.isEmpty())
1696             {
1697               scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1698                       theMap, modelId);
1699             }
1700             if (showLinkedFeatures)
1701             {
1702               scanComplementFeatures(complementRenderer, structureMapping,
1703                       seq, theMap, modelId);
1704             }
1705           }
1706         }
1707       }
1708     }
1709     return theMap;
1710   }
1711
1712   /**
1713    * Ask the structure viewer to open a session file. Returns true if
1714    * successful, else false (or not supported).
1715    * 
1716    * @param filepath
1717    * @return
1718    */
1719   public boolean openSession(String filepath)
1720   {
1721     StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1722     if (cmd == null)
1723     {
1724       return false;
1725     }
1726     executeCommand(cmd, true);
1727     // todo: test for failure - how?
1728     return true;
1729   }
1730
1731   /**
1732    * Scans visible features in mapped positions of the CDS/peptide complement,
1733    * and adds any found to the map of attribute values/structure positions
1734    * 
1735    * @param complementRenderer
1736    * @param structureMapping
1737    * @param seq
1738    * @param theMap
1739    * @param modelNumber
1740    */
1741   protected static void scanComplementFeatures(
1742           FeatureRenderer complementRenderer,
1743           StructureMapping structureMapping, SequenceI seq,
1744           Map<String, Map<Object, AtomSpecModel>> theMap,
1745           String modelNumber)
1746   {
1747     /*
1748      * for each sequence residue mapped to a structure position...
1749      */
1750     for (int seqPos : structureMapping.getMapping().keySet())
1751     {
1752       /*
1753        * find visible complementary features at mapped position(s)
1754        */
1755       MappedFeatures mf = complementRenderer
1756               .findComplementFeaturesAtResidue(seq, seqPos);
1757       if (mf != null)
1758       {
1759         for (SequenceFeature sf : mf.features)
1760         {
1761           String type = sf.getType();
1762
1763           /*
1764            * Don't copy features which originated from Chimera
1765            */
1766           if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1767                   .equals(sf.getFeatureGroup()))
1768           {
1769             continue;
1770           }
1771
1772           /*
1773            * record feature 'value' (score/description/type) as at the
1774            * corresponding structure position
1775            */
1776           List<int[]> mappedRanges = structureMapping
1777                   .getPDBResNumRanges(seqPos, seqPos);
1778
1779           if (!mappedRanges.isEmpty())
1780           {
1781             String value = sf.getDescription();
1782             if (value == null || value.length() == 0)
1783             {
1784               value = type;
1785             }
1786             float score = sf.getScore();
1787             if (score != 0f && !Float.isNaN(score))
1788             {
1789               value = Float.toString(score);
1790             }
1791             Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1792             if (featureValues == null)
1793             {
1794               featureValues = new HashMap<>();
1795               theMap.put(type, featureValues);
1796             }
1797             for (int[] range : mappedRanges)
1798             {
1799               addAtomSpecRange(featureValues, value, modelNumber, range[0],
1800                       range[1], structureMapping.getChain());
1801             }
1802           }
1803         }
1804       }
1805     }
1806   }
1807
1808   /**
1809    * Inspect features on the sequence; for each feature that is visible,
1810    * determine its mapped ranges in the structure (if any) according to the
1811    * given mapping, and add them to the map.
1812    * 
1813    * @param visibleFeatures
1814    * @param mapping
1815    * @param seq
1816    * @param theMap
1817    * @param modelId
1818    */
1819   protected static void scanSequenceFeatures(List<String> visibleFeatures,
1820           StructureMapping mapping, SequenceI seq,
1821           Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1822   {
1823     List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1824             visibleFeatures.toArray(new String[visibleFeatures.size()]));
1825     for (SequenceFeature sf : sfs)
1826     {
1827       String type = sf.getType();
1828
1829       /*
1830        * Don't copy features which originated from Chimera
1831        */
1832       if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1833               .equals(sf.getFeatureGroup()))
1834       {
1835         continue;
1836       }
1837
1838       List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1839               sf.getEnd());
1840
1841       if (!mappedRanges.isEmpty())
1842       {
1843         String value = sf.getDescription();
1844         if (value == null || value.length() == 0)
1845         {
1846           value = type;
1847         }
1848         float score = sf.getScore();
1849         if (score != 0f && !Float.isNaN(score))
1850         {
1851           value = Float.toString(score);
1852         }
1853         Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1854         if (featureValues == null)
1855         {
1856           featureValues = new HashMap<>();
1857           theMap.put(type, featureValues);
1858         }
1859         for (int[] range : mappedRanges)
1860         {
1861           addAtomSpecRange(featureValues, value, modelId, range[0],
1862                   range[1], mapping.getChain());
1863         }
1864       }
1865     }
1866   }
1867
1868   /**
1869    * Returns the number of structure files in the structure viewer and mapped to
1870    * Jalview. This may be zero if the files are still in the process of loading
1871    * in the viewer.
1872    * 
1873    * @return
1874    */
1875   public int getMappedStructureCount()
1876   {
1877     String[] files = getStructureFiles();
1878     return files == null ? 0 : files.length;
1879   }
1880
1881   /**
1882    * Starts a thread that waits for the external viewer program process to
1883    * finish, so that we can then close the associated resources. This avoids
1884    * leaving orphaned viewer panels in Jalview if the user closes the external
1885    * viewer.
1886    * 
1887    * @param p
1888    */
1889   protected void startExternalViewerMonitor(Process p)
1890   {
1891     externalViewerMonitor = new Thread(new Runnable()
1892     {
1893
1894       @Override
1895       public void run()
1896       {
1897         try
1898         {
1899           p.waitFor();
1900           JalviewStructureDisplayI display = getViewer();
1901           if (display != null)
1902           {
1903             display.closeViewer(false);
1904           }
1905         } catch (InterruptedException e)
1906         {
1907           // exit thread if Chimera Viewer is closed in Jalview
1908         }
1909       }
1910     });
1911     externalViewerMonitor.start();
1912   }
1913
1914   /**
1915    * If supported by the external structure viewer, sends it commands to notify
1916    * model or selection changes to the specified URL (where Jalview has started
1917    * a listener)
1918    * 
1919    * @param uri
1920    */
1921   protected void startListening(String uri)
1922   {
1923     List<StructureCommandI> commands = getCommandGenerator()
1924             .startNotifications(uri);
1925     if (commands != null)
1926     {
1927       executeCommands(commands, false, null);
1928     }
1929   }
1930
1931   /**
1932    * If supported by the external structure viewer, sends it commands to stop
1933    * notifying model or selection changes
1934    */
1935   protected void stopListening()
1936   {
1937     List<StructureCommandI> commands = getCommandGenerator()
1938             .stopNotifications();
1939     if (commands != null)
1940     {
1941       executeCommands(commands, false, null);
1942     }
1943   }
1944
1945   /**
1946    * If supported by the structure viewer, queries it for all residue attributes
1947    * with the given attribute name, and creates features on corresponding
1948    * residues of the alignment. Returns the number of features added.
1949    * 
1950    * @param attName
1951    * @param alignmentPanel
1952    * @return
1953    */
1954   public int copyStructureAttributesToFeatures(String attName,
1955           AlignmentPanel alignmentPanel)
1956   {
1957     StructureCommandI cmd = getCommandGenerator()
1958             .getResidueAttributes(attName);
1959     if (cmd == null)
1960     {
1961       return 0;
1962     }
1963     List<String> residueAttributes = executeCommand(cmd, true);
1964
1965     int featuresAdded = createFeaturesForAttributes(attName,
1966             residueAttributes);
1967     if (featuresAdded > 0)
1968     {
1969       alignmentPanel.getFeatureRenderer().featuresAdded();
1970     }
1971     return featuresAdded;
1972   }
1973
1974   /**
1975    * Parses {@code residueAttributes} and creates sequence features on any
1976    * mapped alignment residues. Returns the number of features created.
1977    * <p>
1978    * {@code residueAttributes} is the reply from the structure viewer to a
1979    * command to list any residue attributes for the given attribute name. Syntax
1980    * and parsing of this is viewer-specific.
1981    * 
1982    * @param attName
1983    * @param residueAttributes
1984    * @return
1985    */
1986   protected int createFeaturesForAttributes(String attName,
1987           List<String> residueAttributes)
1988   {
1989     return 0;
1990   }
1991 }