JAL-3403 Fit To Window menu item for Jmol
[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 jalview.api.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.SequenceRenderer;
26 import jalview.api.StructureSelectionManagerProvider;
27 import jalview.api.structures.JalviewStructureDisplayI;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.SequenceI;
32 import jalview.ext.rbvi.chimera.AtomSpecModel;
33 import jalview.io.DataSourceType;
34 import jalview.schemes.ColourSchemeI;
35 import jalview.structure.AtomSpec;
36 import jalview.structure.StructureListener;
37 import jalview.structure.StructureMapping;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.util.Comparison;
40 import jalview.util.MessageManager;
41
42 import java.awt.Color;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.BitSet;
46 import java.util.Collections;
47 import java.util.Iterator;
48 import java.util.List;
49
50 /**
51  * 
52  * A base class to hold common function for protein structure model binding.
53  * Initial version created by refactoring JMol and Chimera binding models, but
54  * other structure viewers could in principle be accommodated in future.
55  * 
56  * @author gmcarstairs
57  *
58  */
59 public abstract class AAStructureBindingModel
60         extends SequenceStructureBindingModel
61         implements StructureListener, StructureSelectionManagerProvider
62 {
63
64   private StructureSelectionManager ssm;
65
66   /*
67    * distinct PDB entries (pdb files) associated
68    * with sequences
69    */
70   private PDBEntry[] pdbEntry;
71
72   /*
73    * sequences mapped to each pdbentry
74    */
75   private SequenceI[][] sequence;
76
77   /*
78    * array of target chains for sequences - tied to pdbentry and sequence[]
79    */
80   private String[][] chains;
81
82   /*
83    * datasource protocol for access to PDBEntrylatest
84    */
85   DataSourceType protocol = null;
86
87   protected boolean colourBySequence = true;
88
89   private boolean nucleotide;
90
91   private boolean finishedInit = false;
92
93   /**
94    * current set of model filenames loaded in the Jmol instance
95    */
96   protected String[] modelFileNames = null;
97
98   public String fileLoadingError;
99
100   private boolean showAlignmentOnly;
101
102   /*
103    * a list of chains "pdbid:chainid" to show in the viewer;
104    * empty means show all
105    */
106   // TODO make private once deprecated JalviewJmolBinding.centerViewer removed
107   protected List<String> chainsToShow;
108
109   private boolean hideHiddenRegions;
110
111   protected List<String> chainNames = new ArrayList<>();
112
113   /**
114    * Data bean class to simplify parameterisation in superposeStructures
115    */
116   protected class SuperposeData
117   {
118     /**
119      * Constructor with alignment width argument
120      * 
121      * @param width
122      */
123     public SuperposeData(int width)
124     {
125       pdbResNo = new int[width];
126     }
127
128     public String filename;
129
130     public String pdbId;
131
132     public String chain = "";
133
134     public boolean isRna;
135
136     /*
137      * The pdb residue number (if any) mapped to each column of the alignment
138      */
139     public int[] pdbResNo;
140   }
141
142   /**
143    * Constructor
144    * 
145    * @param ssm
146    * @param seqs
147    */
148   public AAStructureBindingModel(StructureSelectionManager ssm,
149           SequenceI[][] seqs)
150   {
151     this.ssm = ssm;
152     this.sequence = seqs;
153     chainsToShow = new ArrayList<>();
154   }
155
156   /**
157    * Constructor
158    * 
159    * @param ssm
160    * @param pdbentry
161    * @param sequenceIs
162    * @param protocol
163    */
164   public AAStructureBindingModel(StructureSelectionManager ssm,
165           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
166           DataSourceType protocol)
167   {
168     this.ssm = ssm;
169     this.sequence = sequenceIs;
170     this.nucleotide = Comparison.isNucleotide(sequenceIs);
171     this.pdbEntry = pdbentry;
172     this.protocol = protocol;
173     chainsToShow = new ArrayList<>();
174
175     resolveChains();
176   }
177
178   private boolean resolveChains()
179   {
180     /**
181      * final count of chain mappings discovered
182      */
183     int chainmaps = 0;
184     // JBPNote: JAL-2693 - this should be a list of chain mappings per
185     // [pdbentry][sequence]
186     String[][] newchains = new String[pdbEntry.length][];
187     int pe = 0;
188     for (PDBEntry pdb : pdbEntry)
189     {
190       SequenceI[] seqsForPdb = sequence[pe];
191       if (seqsForPdb != null)
192       {
193         newchains[pe] = new String[seqsForPdb.length];
194         int se = 0;
195         for (SequenceI asq : seqsForPdb)
196         {
197           String chain = (chains != null && chains[pe] != null)
198                   ? chains[pe][se]
199                   : null;
200           SequenceI sq = (asq.getDatasetSequence() == null) ? asq
201                   : asq.getDatasetSequence();
202           if (sq.getAllPDBEntries() != null)
203           {
204             for (PDBEntry pdbentry : sq.getAllPDBEntries())
205             {
206               if (pdb.getFile() != null && pdbentry.getFile() != null
207                       && pdb.getFile().equals(pdbentry.getFile()))
208               {
209                 String chaincode = pdbentry.getChainCode();
210                 if (chaincode != null && chaincode.length() > 0)
211                 {
212                   chain = chaincode;
213                   chainmaps++;
214                   break;
215                 }
216               }
217             }
218           }
219           newchains[pe][se] = chain;
220           se++;
221         }
222         pe++;
223       }
224     }
225
226     chains = newchains;
227     return chainmaps > 0;
228   }
229   public StructureSelectionManager getSsm()
230   {
231     return ssm;
232   }
233
234   /**
235    * Returns the i'th PDBEntry (or null)
236    * 
237    * @param i
238    * @return
239    */
240   public PDBEntry getPdbEntry(int i)
241   {
242     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
243   }
244
245   /**
246    * Answers true if this binding includes the given PDB id, else false
247    * 
248    * @param pdbId
249    * @return
250    */
251   public boolean hasPdbId(String pdbId)
252   {
253     if (pdbEntry != null)
254     {
255       for (PDBEntry pdb : pdbEntry)
256       {
257         if (pdb.getId().equals(pdbId))
258         {
259           return true;
260         }
261       }
262     }
263     return false;
264   }
265
266   /**
267    * Returns the number of modelled PDB file entries.
268    * 
269    * @return
270    */
271   public int getPdbCount()
272   {
273     return pdbEntry == null ? 0 : pdbEntry.length;
274   }
275
276   public SequenceI[][] getSequence()
277   {
278     return sequence;
279   }
280
281   public String[][] getChains()
282   {
283     return chains;
284   }
285
286   public DataSourceType getProtocol()
287   {
288     return protocol;
289   }
290
291   // TODO may remove this if calling methods can be pulled up here
292   protected void setPdbentry(PDBEntry[] pdbentry)
293   {
294     this.pdbEntry = pdbentry;
295   }
296
297   protected void setSequence(SequenceI[][] sequence)
298   {
299     this.sequence = sequence;
300   }
301
302   protected void setChains(String[][] chains)
303   {
304     this.chains = chains;
305   }
306
307   /**
308    * Construct a title string for the viewer window based on the data Jalview
309    * knows about
310    * 
311    * @param viewerName
312    *          TODO
313    * @param verbose
314    * 
315    * @return
316    */
317   public String getViewerTitle(String viewerName, boolean verbose)
318   {
319     if (getSequence() == null || getSequence().length < 1
320             || getPdbCount() < 1 || getSequence()[0].length < 1)
321     {
322       return ("Jalview " + viewerName + " Window");
323     }
324     // TODO: give a more informative title when multiple structures are
325     // displayed.
326     StringBuilder title = new StringBuilder(64);
327     final PDBEntry pdbe = getPdbEntry(0);
328     title.append(viewerName + " view for " + getSequence()[0][0].getName()
329             + ":" + pdbe.getId());
330
331     if (verbose)
332     {
333       String method = (String) pdbe.getProperty("method");
334       if (method != null)
335       {
336         title.append(" Method: ").append(method);
337       }
338       String chain = (String) pdbe.getProperty("chains");
339       if (chain != null)
340       {
341         title.append(" Chain:").append(chain);
342       }
343     }
344     return title.toString();
345   }
346
347   /**
348    * Called by after closeViewer is called, to release any resources and
349    * references so they can be garbage collected. Override if needed.
350    */
351   protected void releaseUIResources()
352   {
353
354   }
355
356   public boolean isColourBySequence()
357   {
358     return colourBySequence;
359   }
360
361   public void setColourBySequence(boolean colourBySequence)
362   {
363     this.colourBySequence = colourBySequence;
364   }
365
366   protected void addSequenceAndChain(int pe, SequenceI[] seq,
367           String[] tchain)
368   {
369     if (pe < 0 || pe >= getPdbCount())
370     {
371       throw new Error(MessageManager.formatMessage(
372               "error.implementation_error_no_pdbentry_from_index",
373               new Object[]
374               { Integer.valueOf(pe).toString() }));
375     }
376     final String nullChain = "TheNullChain";
377     List<SequenceI> s = new ArrayList<>();
378     List<String> c = new ArrayList<>();
379     if (getChains() == null)
380     {
381       setChains(new String[getPdbCount()][]);
382     }
383     if (getSequence()[pe] != null)
384     {
385       for (int i = 0; i < getSequence()[pe].length; i++)
386       {
387         s.add(getSequence()[pe][i]);
388         if (getChains()[pe] != null)
389         {
390           if (i < getChains()[pe].length)
391           {
392             c.add(getChains()[pe][i]);
393           }
394           else
395           {
396             c.add(nullChain);
397           }
398         }
399         else
400         {
401           if (tchain != null && tchain.length > 0)
402           {
403             c.add(nullChain);
404           }
405         }
406       }
407     }
408     for (int i = 0; i < seq.length; i++)
409     {
410       if (!s.contains(seq[i]))
411       {
412         s.add(seq[i]);
413         if (tchain != null && i < tchain.length)
414         {
415           c.add(tchain[i] == null ? nullChain : tchain[i]);
416         }
417       }
418     }
419     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
420     getSequence()[pe] = tmp;
421     if (c.size() > 0)
422     {
423       String[] tch = c.toArray(new String[c.size()]);
424       for (int i = 0; i < tch.length; i++)
425       {
426         if (tch[i] == nullChain)
427         {
428           tch[i] = null;
429         }
430       }
431       getChains()[pe] = tch;
432     }
433     else
434     {
435       getChains()[pe] = null;
436     }
437   }
438
439   /**
440    * add structures and any known sequence associations
441    * 
442    * @returns the pdb entries added to the current set.
443    */
444   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
445           SequenceI[][] seq, String[][] chns)
446   {
447     List<PDBEntry> v = new ArrayList<>();
448     List<int[]> rtn = new ArrayList<>();
449     for (int i = 0; i < getPdbCount(); i++)
450     {
451       v.add(getPdbEntry(i));
452     }
453     for (int i = 0; i < pdbe.length; i++)
454     {
455       int r = v.indexOf(pdbe[i]);
456       if (r == -1 || r >= getPdbCount())
457       {
458         rtn.add(new int[] { v.size(), i });
459         v.add(pdbe[i]);
460       }
461       else
462       {
463         // just make sure the sequence/chain entries are all up to date
464         addSequenceAndChain(r, seq[i], chns[i]);
465       }
466     }
467     pdbe = v.toArray(new PDBEntry[v.size()]);
468     setPdbentry(pdbe);
469     if (rtn.size() > 0)
470     {
471       // expand the tied sequence[] and string[] arrays
472       SequenceI[][] sqs = new SequenceI[getPdbCount()][];
473       String[][] sch = new String[getPdbCount()][];
474       System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
475       System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
476       setSequence(sqs);
477       setChains(sch);
478       pdbe = new PDBEntry[rtn.size()];
479       for (int r = 0; r < pdbe.length; r++)
480       {
481         int[] stri = (rtn.get(r));
482         // record the pdb file as a new addition
483         pdbe[r] = getPdbEntry(stri[0]);
484         // and add the new sequence/chain entries
485         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
486       }
487     }
488     else
489     {
490       pdbe = null;
491     }
492     return pdbe;
493   }
494
495   /**
496    * Add sequences to the pe'th pdbentry's sequence set.
497    * 
498    * @param pe
499    * @param seq
500    */
501   public void addSequence(int pe, SequenceI[] seq)
502   {
503     addSequenceAndChain(pe, seq, null);
504   }
505
506   /**
507    * add the given sequences to the mapping scope for the given pdb file handle
508    * 
509    * @param pdbFile
510    *          - pdbFile identifier
511    * @param seq
512    *          - set of sequences it can be mapped to
513    */
514   public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
515   {
516     for (int pe = 0; pe < getPdbCount(); pe++)
517     {
518       if (getPdbEntry(pe).getFile().equals(pdbFile))
519       {
520         addSequence(pe, seq);
521       }
522     }
523   }
524
525   @Override
526   public abstract void highlightAtoms(List<AtomSpec> atoms);
527
528   protected boolean isNucleotide()
529   {
530     return this.nucleotide;
531   }
532
533   /**
534    * Returns a readable description of all mappings for the wrapped pdbfile to
535    * any mapped sequences
536    * 
537    * @param pdbfile
538    * @param seqs
539    * @return
540    */
541   public String printMappings()
542   {
543     if (pdbEntry == null)
544     {
545       return "";
546     }
547     StringBuilder sb = new StringBuilder(128);
548     for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
549     {
550       String pdbfile = getPdbEntry(pdbe).getFile();
551       List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
552       sb.append(getSsm().printMappings(pdbfile, seqs));
553     }
554     return sb.toString();
555   }
556
557   /**
558    * Returns the mapped structure position for a given aligned column of a given
559    * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
560    * not mapped to structure.
561    * 
562    * @param seq
563    * @param alignedPos
564    * @param mapping
565    * @return
566    */
567   protected int getMappedPosition(SequenceI seq, int alignedPos,
568           StructureMapping mapping)
569   {
570     if (alignedPos >= seq.getLength())
571     {
572       return -1;
573     }
574
575     if (Comparison.isGap(seq.getCharAt(alignedPos)))
576     {
577       return -1;
578     }
579     int seqPos = seq.findPosition(alignedPos);
580     int pos = mapping.getPDBResNum(seqPos);
581     return pos;
582   }
583
584   /**
585    * Helper method to identify residues that can participate in a structure
586    * superposition command. For each structure, identify a sequence in the
587    * alignment which is mapped to the structure. Identify non-gapped columns in
588    * the sequence which have a mapping to a residue in the structure. Returns
589    * the index of the first structure that has a mapping to the alignment.
590    * 
591    * @param alignment
592    *          the sequence alignment which is the basis of structure
593    *          superposition
594    * @param matched
595    *          a BitSet, where bit j is set to indicate that every structure has
596    *          a mapped residue present in column j (so the column can
597    *          participate in structure alignment)
598    * @param structures
599    *          an array of data beans corresponding to pdb file index
600    * @return
601    */
602   protected int findSuperposableResidues(AlignmentI alignment,
603           BitSet matched, SuperposeData[] structures)
604   {
605     int refStructure = -1;
606     String[] files = getStructureFiles();
607     if (files == null)
608     {
609       return -1;
610     }
611     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
612     {
613       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
614       int lastPos = -1;
615
616       /*
617        * Find the first mapped sequence (if any) for this PDB entry which is in
618        * the alignment
619        */
620       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
621       for (int s = 0; s < seqCountForPdbFile; s++)
622       {
623         for (StructureMapping mapping : mappings)
624         {
625           final SequenceI theSequence = getSequence()[pdbfnum][s];
626           if (mapping.getSequence() == theSequence
627                   && alignment.findIndex(theSequence) > -1)
628           {
629             if (refStructure < 0)
630             {
631               refStructure = pdbfnum;
632             }
633             for (int r = 0; r < alignment.getWidth(); r++)
634             {
635               if (!matched.get(r))
636               {
637                 continue;
638               }
639               int pos = getMappedPosition(theSequence, r, mapping);
640               if (pos < 1 || pos == lastPos)
641               {
642                 matched.clear(r);
643                 continue;
644               }
645               lastPos = pos;
646               structures[pdbfnum].pdbResNo[r] = pos;
647             }
648             String chain = mapping.getChain();
649             if (chain != null && chain.trim().length() > 0)
650             {
651               structures[pdbfnum].chain = chain;
652             }
653             structures[pdbfnum].pdbId = mapping.getPdbId();
654             structures[pdbfnum].isRna = theSequence.getRNA() != null;
655
656             /*
657              * move on to next pdb file (ignore sequences for other chains
658              * for the same structure)
659              */
660             s = seqCountForPdbFile;
661             break;
662           }
663         }
664       }
665     }
666     return refStructure;
667   }
668
669   /**
670    * Returns true if the structure viewer has loaded all of the files of
671    * interest (identified by the file mapping having been set up), or false if
672    * any are still not loaded after a timeout interval.
673    * 
674    * @param files
675    */
676   protected boolean waitForFileLoad(String[] files)
677   {
678     /*
679      * give up after 10 secs plus 1 sec per file
680      */
681     long starttime = System.currentTimeMillis();
682     long endTime = 10000 + 1000 * files.length + starttime;
683     String notLoaded = null;
684
685     boolean waiting = true;
686     while (waiting && System.currentTimeMillis() < endTime)
687     {
688       waiting = false;
689       for (String file : files)
690       {
691         notLoaded = file;
692         if (file == null)
693         {
694           continue;
695         }
696         try
697         {
698           StructureMapping[] sm = getSsm().getMapping(file);
699           if (sm == null || sm.length == 0)
700           {
701             waiting = true;
702           }
703         } catch (Throwable x)
704         {
705           waiting = true;
706         }
707       }
708     }
709
710     if (waiting)
711     {
712       System.err.println(
713               "Timed out waiting for structure viewer to load file "
714                       + notLoaded);
715       return false;
716     }
717     return true;
718   }
719
720   @Override
721   public boolean isListeningFor(SequenceI seq)
722   {
723     if (sequence != null)
724     {
725       for (SequenceI[] seqs : sequence)
726       {
727         if (seqs != null)
728         {
729           for (SequenceI s : seqs)
730           {
731             if (s == seq || (s.getDatasetSequence() != null
732                     && s.getDatasetSequence() == seq.getDatasetSequence()))
733             {
734               return true;
735             }
736           }
737         }
738       }
739     }
740     return false;
741   }
742
743   public boolean isFinishedInit()
744   {
745     return finishedInit;
746   }
747
748   public void setFinishedInit(boolean fi)
749   {
750     this.finishedInit = fi;
751   }
752
753   /**
754    * Returns the Jalview panel hosting the structure viewer (if any)
755    * 
756    * @return
757    */
758   public JalviewStructureDisplayI getViewer()
759   {
760     return null;
761   }
762
763   public abstract void setJalviewColourScheme(ColourSchemeI cs);
764
765   /**
766    * Constructs and sends a command to align structures against a reference
767    * structure, based on one or more sequence alignments. May optionally return
768    * an error or warning message for the alignment command.
769    * 
770    * @param alignments
771    *          an array of alignments to process
772    * @param structureIndices
773    *          an array of corresponding reference structures (index into pdb
774    *          file array); if a negative value is passed, the first PDB file
775    *          mapped to an alignment sequence is used as the reference for
776    *          superposition
777    * @param hiddenCols
778    *          an array of corresponding hidden columns for each alignment
779    * @return
780    */
781   public abstract String superposeStructures(AlignmentI[] alignments,
782           int[] structureIndices, HiddenColumns[] hiddenCols);
783
784   public abstract void setBackgroundColour(Color col);
785
786   protected abstract String[] getColourBySequenceCommands(
787           String[] files, AlignmentViewPanel avp);
788
789   /**
790    * returns the current sequenceRenderer that should be used to colour the
791    * structures
792    * 
793    * @param alignment
794    * 
795    * @return
796    */
797   public abstract SequenceRenderer getSequenceRenderer(
798           AlignmentViewPanel alignment);
799
800   protected abstract void colourBySequence(
801           String[] colourBySequenceCommands);
802
803   public abstract void colourByChain();
804
805   public abstract void colourByCharge();
806
807   /**
808    * Recolours the displayed structures, if they are coloured by sequence, or
809    * 'show only visible alignment' is selected. This supports updating structure
810    * colours on either change of alignment colours, or change to the visible
811    * region of the alignment.
812    */
813   public void updateStructureColours(AlignmentViewPanel alignmentv)
814   {
815     if (!isLoadingFinished())
816     {
817       return;
818     }
819
820     /*
821      * if structure is not coloured by sequence, but restricted to the alignment,
822      * then redraw it (but don't recolour it) in case hidden regions have changed
823      * (todo: specific messaging for change of hidden region only)
824      */
825     if (!colourBySequence)
826     {
827       if (isShowAlignmentOnly())
828       {
829         showStructures(alignmentv.getAlignViewport(), false);
830       }
831       return;
832     }
833     if (getSsm() == null)
834     {
835       return;
836     }
837     String[] files = getStructureFiles();
838
839     String[] colourBySequenceCommands = getColourBySequenceCommands(
840             files, alignmentv);
841     colourBySequence(colourBySequenceCommands);
842   }
843
844   public boolean hasFileLoadingError()
845   {
846     return fileLoadingError != null && fileLoadingError.length() > 0;
847   }
848
849   public abstract jalview.api.FeatureRenderer getFeatureRenderer(
850           AlignmentViewPanel alignment);
851
852   /**
853    * Sets the flag for whether only mapped visible residues in the alignment
854    * should be visible in the structure viewer
855    * 
856    * @param b
857    */
858   public void setShowAlignmentOnly(boolean b)
859   {
860     showAlignmentOnly = b;
861   }
862
863   /**
864    * Answers true if only residues mapped to the alignment should be shown in the
865    * structure viewer, else false
866    * 
867    * @return
868    */
869   public boolean isShowAlignmentOnly()
870   {
871     return showAlignmentOnly;
872   }
873
874   /**
875    * Sets the flag for hiding regions of structure which are hidden in the
876    * alignment (only applies when the structure viewer is restricted to the
877    * alignment only)
878    * 
879    * @param b
880    */
881   public void setHideHiddenRegions(boolean b)
882   {
883     hideHiddenRegions = b;
884   }
885
886   /**
887    * Answers true if regions hidden in the alignment should also be hidden in the
888    * structure viewer, else false (only applies when the structure viewer is
889    * restricted to the alignment only)
890    * 
891    * @return
892    */
893   public boolean isHideHiddenRegions()
894   {
895     return hideHiddenRegions;
896   }
897
898   /**
899    * Shows the structures in the viewer, without changing their colouring. This is
900    * to support toggling of whether the whole structure is shown, or only residues
901    * mapped to visible regions of the alignment.
902    * 
903    * @param alignViewportI
904    * @param refocus
905    *                         if true, refit the display to the viewer
906    */
907   public void showStructures(AlignViewportI alignViewportI, boolean refocus)
908   {
909     // override with implementation
910   }
911
912   @Override
913   public void updateColours(Object source)
914   {
915     AlignmentViewPanel ap = (AlignmentViewPanel) source;
916     // ignore events from panels not used to colour this view
917     if (!getViewer().isUsedforcolourby(ap))
918     {
919       return;
920     }
921     if (!isLoadingFromArchive())
922     {
923       updateStructureColours(ap);
924     }
925   }
926
927   /**
928    * Sets the list of chains to display (as "pdbid:chain"), where an empty list
929    * means show all
930    * 
931    * @param chains
932    */
933   public void setChainsToShow(List<String> chains)
934   {
935     chainsToShow = chains;
936   }
937
938   /**
939    * Answers true if the specified structure and chain are selected to be shown in
940    * the viewer, else false
941    * 
942    * @param pdbId
943    * @param chainId
944    * @return
945    */
946   protected boolean isShowChain(String pdbId, String chainId)
947   {
948     if (chainsToShow.isEmpty())
949     {
950       return true;
951     }
952     return chainsToShow.contains(pdbId + ":" + chainId);
953   }
954
955   @Override
956   public abstract String[] getStructureFiles();
957
958   /**
959    * Builds a model of residues mapped from sequences to show on structure, taking
960    * into account user choices of
961    * <ul>
962    * <li>which chains are shown</li>
963    * <li>whether all structure is shown, or only that mapped to the alignment</li>
964    * <li>whether hidden regions of the alignment are hidden (excluded) or grayed
965    * out (included)</li>
966    * </ul>
967    * 
968    * @param av
969    * @return
970    */
971   protected AtomSpecModel getShownResidues(AlignViewportI av)
972   {
973     AlignmentI alignment = av.getAlignment();
974     final int width = alignment.getWidth();
975   
976     String[] files = getStructureFiles();
977   
978     AtomSpecModel model = new AtomSpecModel();
979   
980     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
981     {
982       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
983   
984       /*
985        * Find the first mapped sequence (if any) for this PDB entry which is in
986        * the alignment
987        */
988       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
989       for (int s = 0; s < seqCountForPdbFile; s++)
990       {
991         for (StructureMapping mapping : mappings)
992         {
993           final SequenceI theSequence = getSequence()[pdbfnum][s];
994           if (mapping.getSequence() == theSequence
995                   && alignment.findIndex(theSequence) > -1)
996           {
997             String chainCd = mapping.getChain();
998             if (!isShowChain(mapping.getPdbId(), chainCd))
999             {
1000               continue;
1001             }
1002             Iterator<int[]> visible;
1003             if (isShowAlignmentOnly() && isHideHiddenRegions())
1004             {
1005               visible = alignment.getHiddenColumns()
1006                     .getVisContigsIterator(0, width, true);
1007             }
1008             else
1009             {
1010               visible = Collections.singletonList(new int[] { 0, width })
1011                       .iterator();
1012             }
1013             while (visible.hasNext())
1014             {
1015               int[] visibleRegion = visible.next();
1016               int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1017               int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1018               List<int[]> residueRanges = mapping
1019                       .getPDBResNumRanges(seqStartPos, seqEndPos);
1020               if (!residueRanges.isEmpty())
1021               {
1022                 for (int[] range : residueRanges)
1023                 {
1024                   model.addRange(pdbfnum, range[0], range[1], chainCd);
1025                 }
1026               }
1027             }
1028           }
1029         }
1030       }
1031     }
1032   
1033     return model;
1034   }
1035
1036   /**
1037    * Answers a default structure model specification which is simply the string
1038    * form of the model number. Override if needed to specify submodels.
1039    * 
1040    * @param model
1041    * @return
1042    */
1043   public String getModelSpec(int model)
1044   {
1045     return String.valueOf(model);
1046   }
1047
1048   /**
1049    * Returns a list of chains mapped in this viewer. Note this list is not
1050    * currently scoped per structure.
1051    * 
1052    * @return
1053    */
1054   public List<String> getChainNames()
1055   {
1056     return chainNames;
1057   }
1058
1059   /**
1060    * Send a command to resize and/or centre the structure display
1061    */
1062   public void focusView()
1063   {
1064   }
1065 }