2380ac978cb9e777482f76270676d892b3faa933
[jalview.git] / src / jalview / renderer / AnnotationRenderer.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.renderer;
22
23 import java.awt.BasicStroke;
24 import java.awt.Color;
25 import java.awt.Font;
26 import java.awt.FontMetrics;
27 import java.awt.Graphics;
28 import java.awt.Graphics2D;
29 import java.awt.Image;
30 import java.awt.RenderingHints;
31 import java.awt.Stroke;
32 import java.awt.geom.AffineTransform;
33 import java.awt.image.ImageObserver;
34 import java.util.BitSet;
35 import java.util.Hashtable;
36
37 import org.jfree.graphics2d.svg.SVGGraphics2D;
38 import org.jibble.epsgraphics.EpsGraphics2D;
39
40 import jalview.analysis.AAFrequency;
41 import jalview.analysis.CodingUtils;
42 import jalview.analysis.Rna;
43 import jalview.analysis.StructureFrequency;
44 import jalview.api.AlignViewportI;
45 import jalview.bin.Cache;
46 import jalview.bin.Console;
47 import jalview.datamodel.AlignmentAnnotation;
48 import jalview.datamodel.Annotation;
49 import jalview.datamodel.ColumnSelection;
50 import jalview.datamodel.HiddenColumns;
51 import jalview.datamodel.ProfilesI;
52 import jalview.renderer.api.AnnotationRendererFactoryI;
53 import jalview.renderer.api.AnnotationRowRendererI;
54 import jalview.schemes.ColourSchemeI;
55 import jalview.schemes.NucleotideColourScheme;
56 import jalview.schemes.ResidueProperties;
57 import jalview.schemes.ZappoColourScheme;
58 import jalview.util.Platform;
59
60 public class AnnotationRenderer
61 {
62   private static final int UPPER_TO_LOWER = 'a' - 'A'; // 32
63
64   private static final int CHAR_A = 'A'; // 65
65
66   private static final int CHAR_Z = 'Z'; // 90
67
68   /**
69    * flag indicating if timing and redraw parameter info should be output
70    */
71   private final boolean debugRedraw;
72
73   private int charWidth, endRes, charHeight;
74
75   private boolean validCharWidth, hasHiddenColumns;
76
77   private FontMetrics fm;
78
79   private final boolean USE_FILL_ROUND_RECT = Platform.isAMacAndNotJS();
80
81   boolean av_renderHistogram = true, av_renderProfile = true,
82           av_normaliseProfile = false;
83
84   ResidueShaderI profcolour = null;
85
86   private ColumnSelection columnSelection;
87
88   private HiddenColumns hiddenColumns;
89
90   private ProfilesI hconsensus;
91
92   private Hashtable<String, Object>[] complementConsensus;
93
94   private Hashtable<String, Object>[] hStrucConsensus;
95
96   private boolean av_ignoreGapsConsensus;
97
98   private boolean vectorRendition = false;
99
100   private boolean glyphLineDrawn = false;
101
102   /**
103    * attributes set from AwtRenderPanelI
104    */
105   /**
106    * old image used when data is currently being calculated and cannot be
107    * rendered
108    */
109   private Image fadedImage;
110
111   /**
112    * panel being rendered into
113    */
114   private ImageObserver annotationPanel;
115
116   /**
117    * width of image to render in panel
118    */
119   private int imgWidth;
120
121   /**
122    * offset to beginning of visible area
123    */
124   private int sOffset;
125
126   /**
127    * offset to end of visible area
128    */
129   private int visHeight;
130
131   /**
132    * indicate if the renderer should only render the visible portion of the
133    * annotation given the current view settings
134    */
135   private boolean useClip = true;
136
137   /**
138    * master flag indicating if renderer should ever try to clip. not enabled for
139    * jalview 2.8.1
140    */
141   private boolean canClip = false;
142
143   public AnnotationRenderer()
144   {
145     this(false);
146   }
147
148   /**
149    * Create a new annotation Renderer
150    * 
151    * @param debugRedraw
152    *          flag indicating if timing and redraw parameter info should be
153    *          output
154    */
155   public AnnotationRenderer(boolean debugRedraw)
156   {
157     this.debugRedraw = debugRedraw;
158   }
159
160   /**
161    * Remove any references and resources when this object is no longer required
162    */
163   public void dispose()
164   {
165     hiddenColumns = null;
166     hconsensus = null;
167     complementConsensus = null;
168     hStrucConsensus = null;
169     fadedImage = null;
170     annotationPanel = null;
171     rendererFactoryI = null;
172   }
173
174   void drawStemAnnot(Graphics g, Annotation[] row_annotations, int lastSSX,
175           int x, int y, int iconOffset, int startRes, int column,
176           boolean validRes, boolean validEnd)
177   {
178     g.setColor(STEM_COLOUR);
179     int sCol = (lastSSX / charWidth)
180             + hiddenColumns.visibleToAbsoluteColumn(startRes);
181     int x1 = lastSSX;
182     int x2 = (x * charWidth);
183
184     char dc = (column == 0 || row_annotations[column - 1] == null) ? ' '
185             : row_annotations[column - 1].secondaryStructure;
186
187     boolean diffupstream = sCol == 0 || row_annotations[sCol - 1] == null
188             || dc != row_annotations[sCol - 1].secondaryStructure;
189     boolean diffdownstream = !validRes || !validEnd
190             || row_annotations[column] == null
191             || dc != row_annotations[column].secondaryStructure;
192
193     if (column > 0 && Rna.isClosingParenthesis(dc))
194     {
195       if (diffupstream)
196       // if (validRes && column>1 && row_annotations[column-2]!=null &&
197       // dc.equals(row_annotations[column-2].displayCharacter))
198       {
199         /*
200          * if new annotation with a closing base pair half of the stem, 
201          * display a backward arrow
202          */
203         fillPolygon(g, new int[] { lastSSX + 5, lastSSX + 5, lastSSX },
204                 new int[]
205                 { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset },
206                 3);
207         x1 += 5;
208       }
209       if (diffdownstream)
210       {
211         x2 -= 1;
212       }
213     }
214     else
215     {
216       // display a forward arrow
217       if (diffdownstream)
218       {
219         /*
220          * if annotation ending with an opeing base pair half of the stem, 
221          * display a forward arrow
222          */
223         fillPolygon(g, new int[] { x2 - 5, x2 - 5, x2 },
224                 new int[]
225                 { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset },
226                 3);
227         x2 -= 5;
228       }
229       if (diffupstream)
230       {
231         x1 += 1;
232       }
233     }
234     // draw arrow body
235     fillRect(g, x1, y + 4 + iconOffset, x2 - x1, 7);
236   }
237
238   void drawNotCanonicalAnnot(Graphics g, Color nonCanColor,
239           Annotation[] row_annotations, int lastSSX, int x, int y,
240           int iconOffset, int startRes, int column, boolean validRes,
241           boolean validEnd)
242   {
243     // Console.info(nonCanColor);
244
245     int sCol = (lastSSX / charWidth)
246             + hiddenColumns.visibleToAbsoluteColumn(startRes);
247     int x1 = lastSSX;
248     int x2 = (x * charWidth);
249
250     String dc = (column == 0 || row_annotations[column - 1] == null) ? ""
251             : row_annotations[column - 1].displayCharacter;
252
253     boolean diffupstream = sCol == 0 || row_annotations[sCol - 1] == null
254             || !dc.equals(row_annotations[sCol - 1].displayCharacter);
255     boolean diffdownstream = !validRes || !validEnd
256             || row_annotations[column] == null
257             || !dc.equals(row_annotations[column].displayCharacter);
258     // Console.info("Column "+column+" diff up:
259     // "+diffupstream+"
260     // down:"+diffdownstream);
261     // If a closing base pair half of the stem, display a backward arrow
262     if (diffupstream || diffdownstream)
263     {
264       // draw glyphline under arrow
265       drawGlyphLine(g, lastSSX, x, y, iconOffset);
266     }
267     g.setColor(nonCanColor);
268     if (column > 0 && Rna.isClosingParenthesis(dc))
269     {
270
271       if (diffupstream)
272       // if (validRes && column>1 && row_annotations[column-2]!=null &&
273       // dc.equals(row_annotations[column-2].displayCharacter))
274       {
275         fillPolygon(g, new int[] { lastSSX + 5, lastSSX + 5, lastSSX },
276                 new int[]
277                 { y + iconOffset + 1, y + 13 + iconOffset,
278                     y + 7 + iconOffset },
279                 3);
280         x1 += 5;
281       }
282       if (diffdownstream)
283       {
284         x2 -= 1;
285       }
286     }
287     else
288     {
289
290       // display a forward arrow
291       if (diffdownstream)
292       {
293         fillPolygon(g, new int[] { x2 - 6, x2 - 6, x2 - 1 },
294                 new int[]
295                 { y + iconOffset + 1, y + 13 + iconOffset,
296                     y + 7 + iconOffset },
297                 3);
298         x2 -= 5;
299       }
300       if (diffupstream)
301       {
302         x1 += 1;
303       }
304     }
305     // draw arrow body
306     unsetAntialias(g);
307     fillRect(g, x1, y + 4 + iconOffset, x2 - x1, 6);
308   }
309
310   // public void updateFromAnnotationPanel(FontMetrics annotFM, AlignViewportI
311   // av)
312   public void updateFromAwtRenderPanel(AwtRenderPanelI annotPanel,
313           AlignViewportI av)
314   {
315     fm = annotPanel.getFontMetrics();
316     annotationPanel = annotPanel;
317     fadedImage = annotPanel.getFadedImage();
318     imgWidth = annotPanel.getFadedImageWidth();
319     // visible area for rendering
320     int[] bounds = annotPanel.getVisibleVRange();
321     if (bounds != null)
322     {
323       sOffset = bounds[0];
324       visHeight = bounds[1];
325       if (visHeight == 0)
326       {
327         useClip = false;
328       }
329       else
330       {
331         useClip = canClip;
332       }
333     }
334     else
335     {
336       useClip = false;
337     }
338
339     rendererFactoryI = AnnotationRendererFactory.getRendererFactory();
340     updateFromAlignViewport(av);
341   }
342
343   public void updateFromAlignViewport(AlignViewportI av)
344   {
345     charWidth = av.getCharWidth();
346     endRes = av.getRanges().getEndRes();
347     charHeight = av.getCharHeight();
348     hasHiddenColumns = av.hasHiddenColumns();
349     validCharWidth = av.isValidCharWidth();
350     av_renderHistogram = av.isShowConsensusHistogram();
351     av_renderProfile = av.isShowSequenceLogo();
352     av_normaliseProfile = av.isNormaliseSequenceLogo();
353     profcolour = av.getResidueShading();
354     if (profcolour == null || profcolour.getColourScheme() == null)
355     {
356       /*
357        * Use default colour for sequence logo if 
358        * the alignment has no colourscheme set
359        * (would like to use user preference but n/a for applet)
360        */
361       ColourSchemeI col = av.getAlignment().isNucleotide()
362               ? new NucleotideColourScheme()
363               : new ZappoColourScheme();
364       profcolour = new ResidueShader(col);
365     }
366     columnSelection = av.getColumnSelection();
367     hiddenColumns = av.getAlignment().getHiddenColumns();
368     hconsensus = av.getSequenceConsensusHash();
369     complementConsensus = av.getComplementConsensusHash();
370     hStrucConsensus = av.getRnaStructureConsensusHash();
371     av_ignoreGapsConsensus = av.isIgnoreGapsConsensus();
372   }
373
374   /**
375    * Returns profile data; the first element is the profile type, the second is
376    * the number of distinct values, the third the total count, and the remainder
377    * depend on the profile type.
378    * 
379    * @param aa
380    * @param column
381    * @return
382    */
383   int[] getProfileFor(AlignmentAnnotation aa, int column)
384   {
385     // TODO : consider refactoring the global alignment calculation
386     // properties/rendering attributes as a global 'alignment group' which holds
387     // all vis settings for the alignment as a whole rather than a subset
388     //
389     if (aa.autoCalculated && (aa.label.startsWith("Consensus")
390             || aa.label.startsWith("cDNA Consensus")))
391     {
392       boolean forComplement = aa.label.startsWith("cDNA Consensus");
393       if (aa.groupRef != null && aa.groupRef.consensusData != null
394               && aa.groupRef.isShowSequenceLogo())
395       {
396         // TODO? group consensus for cDNA complement
397         return AAFrequency.extractProfile(
398                 aa.groupRef.consensusData.get(column),
399                 aa.groupRef.getIgnoreGapsConsensus());
400       }
401       // TODO extend annotation row to enable dynamic and static profile data to
402       // be stored
403       if (aa.groupRef == null && aa.sequenceRef == null)
404       {
405         if (forComplement)
406         {
407           return AAFrequency.extractCdnaProfile(complementConsensus[column],
408                   av_ignoreGapsConsensus);
409         }
410         else
411         {
412           return AAFrequency.extractProfile(hconsensus.get(column),
413                   av_ignoreGapsConsensus);
414         }
415       }
416     }
417     else
418     {
419       if (aa.autoCalculated && aa.label.startsWith("StrucConsensus"))
420       {
421         // TODO implement group structure consensus
422         /*
423          * if (aa.groupRef != null && aa.groupRef.consensusData != null &&
424          * aa.groupRef.isShowSequenceLogo()) { //TODO check what happens for
425          * group selections return StructureFrequency.extractProfile(
426          * aa.groupRef.consensusData[column], aa.groupRef
427          * .getIgnoreGapsConsensus()); }
428          */
429         // TODO extend annotation row to enable dynamic and static profile data
430         // to
431         // be stored
432         if (aa.groupRef == null && aa.sequenceRef == null
433                 && hStrucConsensus != null
434                 && hStrucConsensus.length > column)
435         {
436           return StructureFrequency.extractProfile(hStrucConsensus[column],
437                   av_ignoreGapsConsensus);
438         }
439       }
440     }
441     return null;
442   }
443
444   boolean rna = false;
445
446   private AnnotationRendererFactoryI rendererFactoryI;
447
448   /**
449    * Render the annotation rows associated with an alignment.
450    * 
451    * @param annotPanel
452    *          container frame
453    * @param av
454    *          data and view settings to render
455    * @param g
456    *          destination for graphics
457    * @param activeRow
458    *          row where a mouse event occured (or -1)
459    * @param startRes
460    *          first column that will be drawn
461    * @param endRes
462    *          last column that will be drawn
463    * @return true if the fadedImage was used for any alignment annotation rows
464    *         currently being calculated
465    */
466   public boolean drawComponent(AwtRenderPanelI annotPanel,
467           AlignViewportI av, Graphics g, int activeRow, int startRes,
468           int endRes)
469   {
470     if (g instanceof EpsGraphics2D || g instanceof SVGGraphics2D)
471     {
472       this.setVectorRendition(true);
473     }
474     Graphics2D g2d = (Graphics2D) g;
475     // flag used for vector rendition
476     this.glyphLineDrawn = false;
477
478     long stime = System.currentTimeMillis();
479     boolean usedFaded = false;
480     // NOTES:
481     // AnnotationPanel needs to implement: ImageObserver, access to
482     // AlignViewport
483     updateFromAwtRenderPanel(annotPanel, av);
484     fm = g.getFontMetrics();
485     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
486     // int temp = 0;
487     if (aa == null)
488     {
489       return false;
490     }
491     int x = 0, y = 0;
492     int column = 0;
493     char lastSS;
494     int lastSSX;
495     int iconOffset = 0;
496     boolean validRes = false;
497     boolean validEnd = false;
498     boolean labelAllCols = false;
499     // boolean centreColLabels;
500     // boolean centreColLabelsDef = av.isCentreColumnLabels();
501     boolean scaleColLabel = false;
502     final AlignmentAnnotation consensusAnnot = av
503             .getAlignmentConsensusAnnotation();
504     final AlignmentAnnotation structConsensusAnnot = av
505             .getAlignmentStrucConsensusAnnotation();
506     final AlignmentAnnotation complementConsensusAnnot = av
507             .getComplementConsensusAnnotation();
508
509     BitSet graphGroupDrawn = new BitSet();
510     int charOffset = 0; // offset for a label
511     // \u03B2 \u03B1
512     // debug ints
513     int yfrom = 0, f_i = 0, yto = 0, f_to = 0;
514     boolean clipst = false, clipend = false;
515     for (int i = 0; i < aa.length; i++)
516     {
517       AlignmentAnnotation row = aa[i];
518       boolean renderHistogram = true;
519       boolean renderProfile = false;
520       boolean normaliseProfile = false;
521       boolean isRNA = row.isRNA();
522
523       // check if this is a consensus annotation row and set the display
524       // settings appropriately
525       // TODO: generalise this to have render styles for consensus/profile
526       // data
527       if (row.groupRef != null && row == row.groupRef.getConsensus())
528       {
529         renderHistogram = row.groupRef.isShowConsensusHistogram();
530         renderProfile = row.groupRef.isShowSequenceLogo();
531         normaliseProfile = row.groupRef.isNormaliseSequenceLogo();
532       }
533       else if (row == consensusAnnot || row == structConsensusAnnot
534               || row == complementConsensusAnnot)
535       {
536         renderHistogram = av_renderHistogram;
537         renderProfile = av_renderProfile;
538         normaliseProfile = av_normaliseProfile;
539       }
540
541       Annotation[] row_annotations = row.annotations;
542       if (!row.visible)
543       {
544         continue;
545       }
546       // centreColLabels = row.centreColLabels || centreColLabelsDef;
547       labelAllCols = row.showAllColLabels;
548       scaleColLabel = row.scaleColLabel;
549       lastSS = ' ';
550       lastSSX = 0;
551
552       if (!useClip || ((y - charHeight) < visHeight
553               && (y + row.height + charHeight * 2) >= sOffset))
554       {// if_in_visible_region
555         if (!clipst)
556         {
557           clipst = true;
558           yfrom = y;
559           f_i = i;
560         }
561         yto = y;
562         f_to = i;
563         if (row.graph > 0)
564         {
565           if (row.graphGroup > -1 && graphGroupDrawn.get(row.graphGroup))
566           {
567             continue;
568           }
569
570           // this is so that we draw the characters below the graph
571           y += row.height;
572
573           if (row.hasText)
574           {
575             iconOffset = charHeight - fm.getDescent();
576             y -= charHeight;
577           }
578         }
579         else if (row.hasText)
580         {
581           iconOffset = charHeight - fm.getDescent();
582
583         }
584         else
585         {
586           iconOffset = 0;
587         }
588
589         if (row.autoCalculated && av.isCalculationInProgress(row))
590         {
591           y += charHeight;
592           usedFaded = true;
593           g.drawImage(fadedImage, 0, y - row.height, imgWidth, y, 0,
594                   y - row.height, imgWidth, y, annotationPanel);
595           g.setColor(Color.black);
596           // g.drawString("Calculating "+aa[i].label+"....",20, y-row.height/2);
597
598           continue;
599         }
600
601         /*
602          * else if (annotationPanel.av.updatingConservation &&
603          * aa[i].label.equals("Conservation")) {
604          * 
605          * y += charHeight; g.drawImage(annotationPanel.fadedImage, 0, y -
606          * row.height, annotationPanel.imgWidth, y, 0, y - row.height,
607          * annotationPanel.imgWidth, y, annotationPanel);
608          * 
609          * g.setColor(Color.black); //
610          * g.drawString("Calculating Conservation.....",20, y-row.height/2);
611          * 
612          * continue; } else if (annotationPanel.av.updatingConservation &&
613          * aa[i].label.equals("Quality")) {
614          * 
615          * y += charHeight; g.drawImage(annotationPanel.fadedImage, 0, y -
616          * row.height, annotationPanel.imgWidth, y, 0, y - row.height,
617          * annotationPanel.imgWidth, y, annotationPanel);
618          * g.setColor(Color.black); // /
619          * g.drawString("Calculating Quality....",20, y-row.height/2);
620          * 
621          * continue; }
622          */
623
624         // first pass sets up state for drawing continuation from left-hand
625         // column
626         // of startRes
627         x = (startRes == 0) ? 0 : -1;
628         while (x < endRes - startRes)
629         {
630           if (hasHiddenColumns)
631           {
632             column = hiddenColumns.visibleToAbsoluteColumn(startRes + x);
633             if (column > row_annotations.length - 1)
634             {
635               break;
636             }
637           }
638           else
639           {
640             column = startRes + x;
641           }
642
643           if ((row_annotations == null)
644                   || (row_annotations.length <= column)
645                   || (row_annotations[column] == null))
646           {
647             validRes = false;
648           }
649           else
650           {
651             validRes = true;
652           }
653           final String displayChar = validRes
654                   ? row_annotations[column].displayCharacter
655                   : null;
656           if (x > -1)
657           {
658             unsetAntialias(g);
659             if (activeRow == i)
660             {
661               g.setColor(Color.red);
662
663               if (columnSelection != null)
664               {
665                 if (columnSelection.contains(column))
666                 {
667                   fillRect(g, x * charWidth, y, charWidth, charHeight);
668                 }
669               }
670             }
671             if (row.getInvalidStrucPos() > x)
672             {
673               g.setColor(Color.orange);
674               fillRect(g, x * charWidth, y, charWidth, charHeight);
675             }
676             else if (row.getInvalidStrucPos() == x)
677             {
678               g.setColor(Color.orange.darker());
679               fillRect(g, x * charWidth, y, charWidth, charHeight);
680             }
681             if (validCharWidth && validRes && displayChar != null
682                     && (displayChar.length() > 0))
683             {
684               // Graphics2D gg = (g);
685               float fmWidth = fm.charsWidth(displayChar.toCharArray(), 0,
686                       displayChar.length());
687
688               /*
689                * shrink label width to fit in column, if that is
690                * both configured and necessary
691                */
692               boolean scaledToFit = false;
693               float fmScaling = 1f;
694               if (scaleColLabel && fmWidth > charWidth)
695               {
696                 scaledToFit = true;
697                 fmScaling = charWidth;
698                 fmScaling /= fmWidth;
699                 // and update the label's width to reflect the scaling.
700                 fmWidth = charWidth;
701               }
702
703               charOffset = (int) ((charWidth - fmWidth) / 2f);
704
705               if (row_annotations[column].colour == null)
706               {
707                 g2d.setColor(Color.black);
708               }
709               else
710               {
711                 g2d.setColor(row_annotations[column].colour);
712               }
713
714               /*
715                * draw the label, unless it is the same secondary structure
716                * symbol (excluding RNA Helix) as the previous column
717                */
718               final int xPos = (x * charWidth) + charOffset;
719               final int yPos = y + iconOffset;
720
721               /*
722                * translate to drawing position _before_ applying any scaling
723                */
724               g2d.translate(xPos, yPos);
725               if (scaledToFit)
726               {
727                 /*
728                  * use a scaling transform to make the label narrower
729                  * (JalviewJS doesn't have Font.deriveFont(AffineTransform))
730                  */
731                 g2d.transform(
732                         AffineTransform.getScaleInstance(fmScaling, 1.0));
733               }
734               setAntialias(g);
735               if (column == 0 || row.graph > 0)
736               {
737                 g2d.drawString(displayChar, 0, 0);
738               }
739               else if (row_annotations[column - 1] == null || (labelAllCols
740                       || !displayChar.equals(
741                               row_annotations[column - 1].displayCharacter)
742                       || (displayChar.length() < 2
743                               && row_annotations[column].secondaryStructure == ' ')))
744               {
745                 g2d.drawString(displayChar, 0, 0);
746               }
747               if (scaledToFit)
748               {
749                 /*
750                  * undo scaling before translating back 
751                  * (restoring saved transform does NOT work in JS PDFGraphics!)
752                  */
753                 g2d.transform(AffineTransform
754                         .getScaleInstance(1D / fmScaling, 1.0));
755               }
756               g2d.translate(-xPos, -yPos);
757             }
758           }
759           if (row.hasIcons)
760           {
761             char ss = validRes ? row_annotations[column].secondaryStructure
762                     : '-';
763
764             if (ss == '(')
765             {
766               // distinguish between forward/backward base-pairing
767               if (displayChar.indexOf(')') > -1)
768               {
769
770                 ss = ')';
771
772               }
773             }
774             if (ss == '[')
775             {
776               if ((displayChar.indexOf(']') > -1))
777               {
778                 ss = ']';
779
780               }
781             }
782             if (ss == '{')
783             {
784               // distinguish between forward/backward base-pairing
785               if (displayChar.indexOf('}') > -1)
786               {
787                 ss = '}';
788
789               }
790             }
791             if (ss == '<')
792             {
793               // distinguish between forward/backward base-pairing
794               if (displayChar.indexOf('<') > -1)
795               {
796                 ss = '>';
797
798               }
799             }
800             if (isRNA && (ss >= CHAR_A) && (ss <= CHAR_Z))
801             {
802               // distinguish between forward/backward base-pairing
803               int ssLowerCase = ss + UPPER_TO_LOWER;
804               // TODO would .equals() be safer here? or charAt(0)?
805               if (displayChar.indexOf(ssLowerCase) > -1)
806               {
807                 ss = (char) ssLowerCase;
808               }
809             }
810
811             if (!validRes || (ss != lastSS))
812             {
813
814               if (x > -1)
815               {
816
817                 // int nb_annot = x - temp;
818                 // Console.info("\t type :"+lastSS+"\t x
819                 // :"+x+"\t nbre
820                 // annot :"+nb_annot);
821                 switch (lastSS)
822                 {
823                 case '(': // Stem case for RNA secondary structure
824                 case ')': // and opposite direction
825                   drawStemAnnot(g, row_annotations, lastSSX, x, y,
826                           iconOffset, startRes, column, validRes, validEnd);
827                   // temp = x;
828                   break;
829
830                 case 'H':
831                   if (!isRNA)
832                   {
833                     drawHelixAnnot(g, row_annotations, lastSSX, x, y,
834                             iconOffset, startRes, column, validRes,
835                             validEnd);
836                     break;
837                   }
838                   // no break if isRNA - falls through to drawNotCanonicalAnnot!
839                 case 'E':
840                   if (!isRNA)
841                   {
842                     drawSheetAnnot(g, row_annotations, lastSSX, x, y,
843                             iconOffset, startRes, column, validRes,
844                             validEnd);
845                     break;
846                   }
847                   // no break if isRNA - fall through to drawNotCanonicalAnnot!
848
849                 case '{':
850                 case '}':
851                 case '[':
852                 case ']':
853                 case '>':
854                 case '<':
855                 case 'A':
856                 case 'a':
857                 case 'B':
858                 case 'b':
859                 case 'C':
860                 case 'c':
861                 case 'D':
862                 case 'd':
863                 case 'e':
864                 case 'F':
865                 case 'f':
866                 case 'G':
867                 case 'g':
868                 case 'h':
869                 case 'I':
870                 case 'i':
871                 case 'J':
872                 case 'j':
873                 case 'K':
874                 case 'k':
875                 case 'L':
876                 case 'l':
877                 case 'M':
878                 case 'm':
879                 case 'N':
880                 case 'n':
881                 case 'O':
882                 case 'o':
883                 case 'P':
884                 case 'p':
885                 case 'Q':
886                 case 'q':
887                 case 'R':
888                 case 'r':
889                 case 'S':
890                 case 's':
891                 case 'T':
892                 case 't':
893                 case 'U':
894                 case 'u':
895                 case 'V':
896                 case 'v':
897                 case 'W':
898                 case 'w':
899                 case 'X':
900                 case 'x':
901                 case 'Y':
902                 case 'y':
903                 case 'Z':
904                 case 'z':
905
906                   Color nonCanColor = getNotCanonicalColor(lastSS);
907                   drawNotCanonicalAnnot(g, nonCanColor, row_annotations,
908                           lastSSX, x, y, iconOffset, startRes, column,
909                           validRes, validEnd);
910                   // temp = x;
911                   break;
912                 default:
913                   if (isVectorRendition())
914                   {
915                     // draw single full width glyphline
916                     drawGlyphLine(g, lastSSX, endRes - x, y, iconOffset);
917                     // disable more glyph lines
918                     this.glyphLineDrawn = true;
919                   }
920                   else
921                   {
922                     drawGlyphLine(g, lastSSX, x, y, iconOffset);
923                   }
924                   break;
925                 }
926               }
927               if (validRes)
928               {
929                 lastSS = ss;
930               }
931               else
932               {
933                 lastSS = ' ';
934               }
935               if (x > -1)
936               {
937                 lastSSX = (x * charWidth);
938               }
939             }
940           }
941           column++;
942           x++;
943         }
944         if (column >= row_annotations.length)
945         {
946           column = row_annotations.length - 1;
947           validEnd = false;
948         }
949         else
950         {
951           validEnd = true;
952         }
953         if ((row_annotations == null) || (row_annotations.length <= column)
954                 || (row_annotations[column] == null))
955         {
956           validRes = false;
957         }
958         else
959         {
960           validRes = true;
961         }
962         // x ++;
963
964         if (row.hasIcons)
965         {
966           switch (lastSS)
967           {
968
969           case 'H':
970             if (!isRNA)
971             {
972               drawHelixAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
973                       startRes, column, validRes, validEnd);
974               break;
975             }
976             // no break if isRNA - fall through to drawNotCanonicalAnnot!
977
978           case 'E':
979             if (!isRNA)
980             {
981               drawSheetAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
982                       startRes, column, validRes, validEnd);
983               break;
984             }
985             // no break if isRNA - fall through to drawNotCanonicalAnnot!
986
987           case '(':
988           case ')': // Stem case for RNA secondary structure
989
990             drawStemAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
991                     startRes, column, validRes, validEnd);
992
993             break;
994           case '{':
995           case '}':
996           case '[':
997           case ']':
998           case '>':
999           case '<':
1000           case 'A':
1001           case 'a':
1002           case 'B':
1003           case 'b':
1004           case 'C':
1005           case 'c':
1006           case 'D':
1007           case 'd':
1008           case 'e':
1009           case 'F':
1010           case 'f':
1011           case 'G':
1012           case 'g':
1013           case 'h':
1014           case 'I':
1015           case 'i':
1016           case 'J':
1017           case 'j':
1018           case 'K':
1019           case 'k':
1020           case 'L':
1021           case 'l':
1022           case 'M':
1023           case 'm':
1024           case 'N':
1025           case 'n':
1026           case 'O':
1027           case 'o':
1028           case 'P':
1029           case 'p':
1030           case 'Q':
1031           case 'q':
1032           case 'R':
1033           case 'r':
1034           case 'T':
1035           case 't':
1036           case 'U':
1037           case 'u':
1038           case 'V':
1039           case 'v':
1040           case 'W':
1041           case 'w':
1042           case 'X':
1043           case 'x':
1044           case 'Y':
1045           case 'y':
1046           case 'Z':
1047           case 'z':
1048             // Console.info(lastSS);
1049             Color nonCanColor = getNotCanonicalColor(lastSS);
1050             drawNotCanonicalAnnot(g, nonCanColor, row_annotations, lastSSX,
1051                     x, y, iconOffset, startRes, column, validRes, validEnd);
1052             break;
1053           default:
1054             if (isVectorRendition())
1055             {
1056               // draw single full width glyphline
1057               drawGlyphLine(g, lastSSX, endRes - x, y, iconOffset);
1058               // disable more glyph lines
1059               this.glyphLineDrawn = true;
1060             }
1061             else
1062             {
1063               drawGlyphLine(g, lastSSX, x, y, iconOffset);
1064             }
1065             break;
1066           }
1067         }
1068
1069         if (row.graph > 0 && row.graphHeight > 0)
1070         {
1071           if (row.graph == AlignmentAnnotation.LINE_GRAPH)
1072           {
1073             if (row.graphGroup > -1 && !graphGroupDrawn.get(row.graphGroup))
1074             {
1075               // TODO: JAL-1291 revise rendering model so the graphGroup map is
1076               // computed efficiently for all visible labels
1077               float groupmax = -999999, groupmin = 9999999;
1078               for (int gg = 0; gg < aa.length; gg++)
1079               {
1080                 if (aa[gg].graphGroup != row.graphGroup)
1081                 {
1082                   continue;
1083                 }
1084
1085                 if (aa[gg] != row)
1086                 {
1087                   aa[gg].visible = false;
1088                 }
1089                 if (aa[gg].graphMax > groupmax)
1090                 {
1091                   groupmax = aa[gg].graphMax;
1092                 }
1093                 if (aa[gg].graphMin < groupmin)
1094                 {
1095                   groupmin = aa[gg].graphMin;
1096                 }
1097               }
1098
1099               for (int gg = 0; gg < aa.length; gg++)
1100               {
1101                 if (aa[gg].graphGroup == row.graphGroup)
1102                 {
1103                   drawLineGraph(g, aa[gg], aa[gg].annotations, startRes,
1104                           endRes, y, groupmin, groupmax, row.graphHeight);
1105                 }
1106               }
1107
1108               graphGroupDrawn.set(row.graphGroup);
1109             }
1110             else
1111             {
1112               drawLineGraph(g, row, row_annotations, startRes, endRes, y,
1113                       row.graphMin, row.graphMax, row.graphHeight);
1114             }
1115           }
1116           else if (row.graph == AlignmentAnnotation.BAR_GRAPH)
1117           {
1118             drawBarGraph(g, row, row_annotations, startRes, endRes,
1119                     row.graphMin, row.graphMax, y, renderHistogram,
1120                     renderProfile, normaliseProfile);
1121           }
1122           else
1123           {
1124             AnnotationRowRendererI renderer = rendererFactoryI
1125                     .getRendererFor(row);
1126             if (renderer != null)
1127             {
1128               renderer.renderRow(g, charWidth, charHeight, hasHiddenColumns,
1129                       av, hiddenColumns, columnSelection, row,
1130                       row_annotations, startRes, endRes, row.graphMin,
1131                       row.graphMax, y);
1132             }
1133             if (debugRedraw)
1134             {
1135               if (renderer == null)
1136               {
1137                 System.err
1138                         .println("No renderer found for " + row.toString());
1139               }
1140               else
1141               {
1142                 Console.warn(
1143                         "rendered with " + renderer.getClass().toString());
1144               }
1145             }
1146
1147           }
1148         }
1149       }
1150       else
1151       {
1152         if (clipst && !clipend)
1153         {
1154           clipend = true;
1155         }
1156       } // end if_in_visible_region
1157       if (row.graph > 0 && row.hasText)
1158       {
1159         y += charHeight;
1160       }
1161
1162       if (row.graph == 0)
1163       {
1164         y += aa[i].height;
1165       }
1166     }
1167     if (debugRedraw)
1168     {
1169       if (canClip)
1170       {
1171         if (clipst)
1172         {
1173           Console.warn("Start clip at : " + yfrom + " (index " + f_i + ")");
1174         }
1175         if (clipend)
1176         {
1177           Console.warn("End clip at : " + yto + " (index " + f_to + ")");
1178         }
1179       }
1180       ;
1181       Console.warn("Annotation Rendering time:"
1182               + (System.currentTimeMillis() - stime));
1183     }
1184     ;
1185
1186     return !usedFaded;
1187   }
1188
1189   public static final Color GLYPHLINE_COLOR = Color.gray;
1190
1191   public static final Color SHEET_COLOUR = Color.green;
1192
1193   public static final Color HELIX_COLOUR = Color.red;
1194
1195   public static final Color STEM_COLOUR = Color.blue;
1196
1197   // private Color sdNOTCANONICAL_COLOUR;
1198
1199   void drawGlyphLine(Graphics g, int lastSSX, int x, int y, int iconOffset)
1200   {
1201     if (glyphLineDrawn)
1202     {
1203       // if we've drawn a single long glyphline for an export, don't draw the
1204       // bits
1205       return;
1206     }
1207     unsetAntialias(g);
1208     g.setColor(GLYPHLINE_COLOR);
1209     g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth) - lastSSX, 2);
1210   }
1211
1212   void drawSheetAnnot(Graphics g, Annotation[] row,
1213
1214           int lastSSX, int x, int y, int iconOffset, int startRes,
1215           int column, boolean validRes, boolean validEnd)
1216   {
1217     if (!validEnd || !validRes || row == null || row[column] == null
1218             || row[column].secondaryStructure != 'E')
1219     {
1220       // draw the glyphline underneath
1221       drawGlyphLine(g, lastSSX, x, y, iconOffset);
1222
1223       g.setColor(SHEET_COLOUR);
1224       fillRect(g, lastSSX, y + 4 + iconOffset,
1225               (x * charWidth) - lastSSX - 4, 6);
1226       fillPolygon(g,
1227               new int[]
1228               { (x * charWidth) - 6, (x * charWidth) - 6,
1229                   (x * charWidth - 1) },
1230               new int[]
1231               { y + iconOffset + 1, y + 13 + iconOffset,
1232                   y + 7 + iconOffset },
1233               3);
1234     }
1235     else
1236     {
1237       g.setColor(SHEET_COLOUR);
1238       fillRect(g, lastSSX, y + 4 + iconOffset, (x * charWidth) - lastSSX,
1239               6);
1240     }
1241   }
1242
1243   void drawHelixAnnot(Graphics g, Annotation[] row, int lastSSX, int x,
1244           int y, int iconOffset, int startRes, int column, boolean validRes,
1245           boolean validEnd)
1246   {
1247     int sCol = (lastSSX / charWidth)
1248             + hiddenColumns.visibleToAbsoluteColumn(startRes);
1249     int x1 = lastSSX;
1250     int x2 = (x * charWidth);
1251
1252     if (USE_FILL_ROUND_RECT || isVectorRendition())
1253     {
1254       // draw glyph line behind helix (visible in EPS or SVG output)
1255       drawGlyphLine(g, lastSSX, x, y, iconOffset);
1256
1257       g.setColor(HELIX_COLOUR);
1258       setAntialias(g);
1259       int ofs = charWidth / 2;
1260       // Off by 1 offset when drawing rects and ovals
1261       // to offscreen image on the MAC
1262       fillRoundRect(g, lastSSX, y + 3 + iconOffset, x2 - x1 - 1, 8, 8, 8);
1263       if (sCol == 0 || row[sCol - 1] == null
1264               || row[sCol - 1].secondaryStructure != 'H')
1265       {
1266       }
1267       else
1268       {
1269         // g.setColor(Color.orange);
1270         fillRoundRect(g, lastSSX, y + 3 + iconOffset, x2 - x1 - ofs, 8, 0,
1271                 0);
1272       }
1273       if (!validRes || row[column] == null
1274               || row[column].secondaryStructure != 'H')
1275       {
1276
1277       }
1278       else
1279       {
1280         // g.setColor(Color.magenta);
1281         fillRoundRect(g, lastSSX + ofs, y + 3 + iconOffset, x2 - x1 - ofs,
1282                 8, 0, 0);
1283       }
1284
1285       return;
1286     }
1287
1288     boolean leftEnd = sCol == 0 || row[sCol - 1] == null
1289             || row[sCol - 1].secondaryStructure != 'H';
1290     boolean rightEnd = !validRes || row[column] == null
1291             || row[column].secondaryStructure != 'H';
1292
1293     if (leftEnd || rightEnd)
1294     {
1295       drawGlyphLine(g, lastSSX, x, y, iconOffset);
1296     }
1297     g.setColor(HELIX_COLOUR);
1298
1299     if (leftEnd)
1300     {
1301       fillArc(g, lastSSX, y + 3 + iconOffset, charWidth, 8, 90, 180);
1302       x1 += charWidth / 2;
1303     }
1304
1305     if (rightEnd)
1306     {
1307       fillArc(g, ((x - 1) * charWidth), y + 3 + iconOffset, charWidth, 8,
1308               270, 180);
1309       x2 -= charWidth / 2;
1310     }
1311
1312     fillRect(g, x1, y + 3 + iconOffset, x2 - x1, 8);
1313   }
1314
1315   void drawLineGraph(Graphics g, AlignmentAnnotation _aa,
1316           Annotation[] aa_annotations, int sRes, int eRes, int y, float min,
1317           float max, int graphHeight)
1318   {
1319     if (sRes > aa_annotations.length)
1320     {
1321       return;
1322     }
1323     Stroke roundStroke = new BasicStroke(1, BasicStroke.CAP_ROUND,
1324             BasicStroke.JOIN_ROUND);
1325     Stroke squareStroke = new BasicStroke(1, BasicStroke.CAP_SQUARE,
1326             BasicStroke.JOIN_MITER);
1327     Graphics2D g2d = (Graphics2D) g;
1328     Stroke prevStroke = g2d.getStroke();
1329     g2d.setStroke(roundStroke);
1330
1331     int x = 0;
1332
1333     // Adjustment for fastpaint to left
1334     if (eRes < endRes)
1335     {
1336       eRes++;
1337     }
1338
1339     eRes = Math.min(eRes, aa_annotations.length);
1340
1341     if (sRes == 0)
1342     {
1343       x++;
1344     }
1345
1346     int y1 = y, y2 = y;
1347     float range = max - min;
1348
1349     // //Draw origin
1350     if (min < 0)
1351     {
1352       y2 = y - (int) ((0 - min / range) * graphHeight);
1353     }
1354
1355     g.setColor(Color.gray);
1356     drawLine(g, squareStroke, x * charWidth - charWidth, y2,
1357             (eRes - sRes) * charWidth, y2);
1358
1359     eRes = Math.min(eRes, aa_annotations.length);
1360
1361     int column;
1362     int aaMax = aa_annotations.length - 1;
1363
1364     while (x < eRes - sRes)
1365     {
1366       column = sRes + x;
1367       if (hasHiddenColumns)
1368       {
1369         column = hiddenColumns.visibleToAbsoluteColumn(column);
1370       }
1371
1372       if (column > aaMax)
1373       {
1374         break;
1375       }
1376
1377       if (aa_annotations[column] == null)
1378       {
1379         x++;
1380         continue;
1381       }
1382
1383       if (aa_annotations[column].colour == null)
1384       {
1385         g.setColor(Color.black);
1386       }
1387       else
1388       {
1389         g.setColor(aa_annotations[column].colour);
1390       }
1391
1392       if (aa_annotations[column - 1] == null
1393               && aa_annotations.length > column + 1
1394               && aa_annotations[column + 1] == null)
1395       {
1396         // standalone value
1397         y1 = y - (int) (((aa_annotations[column].value - min) / range)
1398                 * graphHeight);
1399         drawLine(g, x * charWidth + charWidth / 4, y1,
1400                 x * charWidth + 3 * charWidth / 4, y1);
1401         x++;
1402         continue;
1403       }
1404
1405       if (aa_annotations[column - 1] == null)
1406       {
1407         x++;
1408         continue;
1409       }
1410
1411       y1 = y - (int) (((aa_annotations[column - 1].value - min) / range)
1412               * graphHeight);
1413       y2 = y - (int) (((aa_annotations[column].value - min) / range)
1414               * graphHeight);
1415
1416       drawLine(g, (x - 1) * charWidth + charWidth / 2, y1,
1417               x * charWidth + charWidth / 2, y2);
1418       x++;
1419     }
1420
1421     if (_aa.threshold != null)
1422     {
1423       g.setColor(_aa.threshold.colour);
1424       Graphics2D g2 = (Graphics2D) g;
1425       Stroke s = new BasicStroke(1, BasicStroke.CAP_SQUARE,
1426               BasicStroke.JOIN_ROUND, 3f, new float[]
1427               { 5f, 3f }, 0f);
1428
1429       y2 = (int) (y - ((_aa.threshold.value - min) / range) * graphHeight);
1430       drawLine(g, s, 0, y2, (eRes - sRes) * charWidth, y2);
1431     }
1432     g2d.setStroke(prevStroke);
1433   }
1434
1435   @SuppressWarnings("unused")
1436   void drawBarGraph(Graphics g, AlignmentAnnotation _aa,
1437           Annotation[] aa_annotations, int sRes, int eRes, float min,
1438           float max, int y, boolean renderHistogram, boolean renderProfile,
1439           boolean normaliseProfile)
1440   {
1441     if (sRes > aa_annotations.length)
1442     {
1443       return;
1444     }
1445     Font ofont = g.getFont();
1446     eRes = Math.min(eRes, aa_annotations.length);
1447
1448     int x = 0, y1 = y, y2 = y;
1449
1450     float range = max - min;
1451
1452     if (min < 0)
1453     {
1454       y2 = y - (int) ((0 - min / (range)) * _aa.graphHeight);
1455     }
1456
1457     g.setColor(Color.gray);
1458
1459     drawLine(g, x, y2, (eRes - sRes) * charWidth, y2);
1460
1461     int column;
1462     int aaMax = aa_annotations.length - 1;
1463     while (x < eRes - sRes)
1464     {
1465       column = sRes + x;
1466       if (hasHiddenColumns)
1467       {
1468         column = hiddenColumns.visibleToAbsoluteColumn(column);
1469       }
1470
1471       if (column > aaMax)
1472       {
1473         break;
1474       }
1475
1476       if (aa_annotations[column] == null)
1477       {
1478         x++;
1479         continue;
1480       }
1481       if (aa_annotations[column].colour == null)
1482       {
1483         g.setColor(Color.black);
1484       }
1485       else
1486       {
1487         g.setColor(aa_annotations[column].colour);
1488       }
1489
1490       y1 = y - (int) (((aa_annotations[column].value - min) / (range))
1491               * _aa.graphHeight);
1492
1493       if (renderHistogram)
1494       {
1495         if (y1 - y2 > 0)
1496         {
1497           fillRect(g, x * charWidth, y2, charWidth, y1 - y2);
1498         }
1499         else
1500         {
1501           fillRect(g, x * charWidth, y1, charWidth, y2 - y1);
1502         }
1503       }
1504       // draw profile if available
1505       if (renderProfile)
1506       {
1507
1508         /*
1509          * {profile type, #values, total count, char1, pct1, char2, pct2...}
1510          */
1511         int profl[] = getProfileFor(_aa, column);
1512
1513         // just try to draw the logo if profl is not null
1514         if (profl != null && profl[2] != 0)
1515         {
1516           boolean isStructureProfile = profl[0] == AlignmentAnnotation.STRUCTURE_PROFILE;
1517           boolean isCdnaProfile = profl[0] == AlignmentAnnotation.CDNA_PROFILE;
1518           float ht = normaliseProfile ? y - _aa.graphHeight : y1;
1519           final double normaliseFactor = normaliseProfile ? _aa.graphHeight
1520                   : (y2 - y1);
1521
1522           /**
1523            * Render a single base for a sequence profile, a base pair for
1524            * structure profile, and a triplet for a cdna profile
1525            */
1526           char[] dc = new char[isStructureProfile ? 2
1527                   : (isCdnaProfile ? 3 : 1)];
1528
1529           // lm is not necessary - we can just use fm - could be off by no more
1530           // than 0.5 px
1531           // LineMetrics lm = g.getFontMetrics(ofont).getLineMetrics("Q", g);
1532           // Console.info(asc + " " + dec + " " + (asc -
1533           // lm.getAscent())
1534           // + " " + (dec - lm.getDescent()));
1535
1536           double asc = fm.getAscent();
1537           double dec = fm.getDescent();
1538           double fht = fm.getHeight();
1539
1540           double scale = 1f / (normaliseProfile ? profl[2] : 100f);
1541           // float ofontHeight = 1f / fm.getAscent();// magnify to fill box
1542
1543           /*
1544            * Traverse the character(s)/percentage data in the array
1545            */
1546
1547           float ht2 = ht;
1548
1549           // profl[1] is the number of values in the profile
1550           for (int i = 0, c = 3, last = profl[1]; i < last; i++)
1551           {
1552
1553             String s;
1554             if (isStructureProfile)
1555             {
1556               // todo can we encode a structure pair as an int, like codons?
1557               dc[0] = (char) profl[c++];
1558               dc[1] = (char) profl[c++];
1559               s = new String(dc);
1560             }
1561             else if (isCdnaProfile)
1562             {
1563               CodingUtils.decodeCodon2(profl[c++], dc);
1564               s = new String(dc);
1565             }
1566             else
1567             {
1568               dc[0] = (char) profl[c++];
1569               s = new String(dc);
1570             }
1571             // next profl[] position is profile % for the character(s)
1572
1573             int percent = profl[c++];
1574             if (percent == 0)
1575             {
1576               // failsafe in case a count rounds down to 0%
1577               continue;
1578             }
1579             double newHeight = normaliseFactor * scale * percent;
1580
1581             /*
1582              * Set character colour as per alignment colour scheme; use the
1583              * codon translation if a cDNA profile
1584              */
1585             Color colour = null;
1586             if (isCdnaProfile)
1587             {
1588               final String codonTranslation = ResidueProperties
1589                       .codonTranslate(s);
1590               colour = profcolour.findColour(codonTranslation.charAt(0),
1591                       column, null);
1592             }
1593             else
1594             {
1595               colour = profcolour.findColour(dc[0], column, null);
1596             }
1597             g.setColor(colour == Color.white ? Color.lightGray : colour);
1598
1599             // Debug - render boxes around characters
1600             // g.setColor(Color.red);
1601             // g.drawRect(x*av.charWidth, (int)ht, av.charWidth,
1602             // (int)(scl));
1603             // g.setColor(profcolour.findColour(dc[0]).darker());
1604
1605             double sx = 1f * charWidth / fm.charsWidth(dc, 0, dc.length);
1606             double sy = newHeight / asc;
1607             double newAsc = asc * sy;
1608             double newDec = dec * sy;
1609             // it is not necessary to recalculate lm for the new font.
1610             // note: lm.getBaselineOffsets()[lm.getBaselineIndex()]) must be 0
1611             // by definition. Was:
1612             // int hght = (int) (ht + (newAsc - newDec);
1613             // - lm.getBaselineOffsets()[lm.getBaselineIndex()]));
1614
1615             if (Platform.isJS())
1616             {
1617               /*
1618                * SwingJS does not implement font.deriveFont()
1619                * so use a scaling transform to draw instead,
1620                * this is off by a very small amount
1621                */
1622               final int hght = (int) (ht2 + (newAsc - newDec));
1623               Graphics2D gg = (Graphics2D) g;
1624               int xShift = (int) Math.round(x * charWidth / sx);
1625               int yShift = (int) Math.round(hght / sy);
1626               gg.transform(AffineTransform.getScaleInstance(sx, sy));
1627               gg.drawString(s, xShift, yShift);
1628               gg.transform(
1629                       AffineTransform.getScaleInstance(1D / sx, 1D / sy));
1630               ht2 += newHeight;
1631             }
1632             else
1633             /**
1634              * Java only
1635              * 
1636              * @j2sIgnore
1637              */
1638             {
1639               // Java ('normal') method is to scale the font to fit
1640
1641               final int hght = (int) (ht + (newAsc - newDec));
1642               Font font = ofont
1643                       .deriveFont(AffineTransform.getScaleInstance(sx, sy));
1644               g.setFont(font);
1645               g.drawChars(dc, 0, dc.length, x * charWidth, hght);
1646               g.setFont(ofont);
1647
1648               ht += newHeight;
1649             }
1650           }
1651         }
1652       }
1653       x++;
1654     }
1655     if (_aa.threshold != null)
1656     {
1657       g.setColor(_aa.threshold.colour);
1658       Stroke s = new BasicStroke(1, BasicStroke.CAP_SQUARE,
1659               BasicStroke.JOIN_ROUND, 3f, new float[]
1660               { 5f, 3f }, 0f);
1661
1662       y2 = (int) (y
1663               - ((_aa.threshold.value - min) / range) * _aa.graphHeight);
1664       drawLine(g, s, 0, y2, (eRes - sRes) * charWidth, y2);
1665     }
1666   }
1667
1668   // used by overview window
1669   public void drawGraph(Graphics g, AlignmentAnnotation _aa,
1670           Annotation[] aa_annotations, int width, int y, int sRes, int eRes)
1671   {
1672     eRes = Math.min(eRes, aa_annotations.length);
1673     g.setColor(Color.white);
1674     fillRect(g, 0, 0, width, y);
1675     g.setColor(new Color(0, 0, 180));
1676
1677     int x = 0, height;
1678
1679     for (int j = sRes; j < eRes; j++)
1680     {
1681       if (aa_annotations[j] != null)
1682       {
1683         if (aa_annotations[j].colour == null)
1684         {
1685           g.setColor(Color.black);
1686         }
1687         else
1688         {
1689           g.setColor(aa_annotations[j].colour);
1690         }
1691
1692         height = (int) ((aa_annotations[j].value / _aa.graphMax) * y);
1693         if (height > y)
1694         {
1695           height = y;
1696         }
1697
1698         fillRect(g, x, y - height, charWidth, height);
1699       }
1700       x += charWidth;
1701     }
1702   }
1703
1704   Color getNotCanonicalColor(char lastss)
1705   {
1706     switch (lastss)
1707     {
1708     case '{':
1709     case '}':
1710       return new Color(255, 125, 5);
1711
1712     case '[':
1713     case ']':
1714       return new Color(245, 115, 10);
1715
1716     case '>':
1717     case '<':
1718       return new Color(235, 135, 15);
1719
1720     case 'A':
1721     case 'a':
1722       return new Color(225, 105, 20);
1723
1724     case 'B':
1725     case 'b':
1726       return new Color(215, 145, 30);
1727
1728     case 'C':
1729     case 'c':
1730       return new Color(205, 95, 35);
1731
1732     case 'D':
1733     case 'd':
1734       return new Color(195, 155, 45);
1735
1736     case 'E':
1737     case 'e':
1738       return new Color(185, 85, 55);
1739
1740     case 'F':
1741     case 'f':
1742       return new Color(175, 165, 65);
1743
1744     case 'G':
1745     case 'g':
1746       return new Color(170, 75, 75);
1747
1748     case 'H':
1749     case 'h':
1750       return new Color(160, 175, 85);
1751
1752     case 'I':
1753     case 'i':
1754       return new Color(150, 65, 95);
1755
1756     case 'J':
1757     case 'j':
1758       return new Color(140, 185, 105);
1759
1760     case 'K':
1761     case 'k':
1762       return new Color(130, 55, 110);
1763
1764     case 'L':
1765     case 'l':
1766       return new Color(120, 195, 120);
1767
1768     case 'M':
1769     case 'm':
1770       return new Color(110, 45, 130);
1771
1772     case 'N':
1773     case 'n':
1774       return new Color(100, 205, 140);
1775
1776     case 'O':
1777     case 'o':
1778       return new Color(90, 35, 150);
1779
1780     case 'P':
1781     case 'p':
1782       return new Color(85, 215, 160);
1783
1784     case 'Q':
1785     case 'q':
1786       return new Color(75, 25, 170);
1787
1788     case 'R':
1789     case 'r':
1790       return new Color(65, 225, 180);
1791
1792     case 'S':
1793     case 's':
1794       return new Color(55, 15, 185);
1795
1796     case 'T':
1797     case 't':
1798       return new Color(45, 235, 195);
1799
1800     case 'U':
1801     case 'u':
1802       return new Color(35, 5, 205);
1803
1804     case 'V':
1805     case 'v':
1806       return new Color(25, 245, 215);
1807
1808     case 'W':
1809     case 'w':
1810       return new Color(15, 0, 225);
1811
1812     case 'X':
1813     case 'x':
1814       return new Color(10, 255, 235);
1815
1816     case 'Y':
1817     case 'y':
1818       return new Color(5, 150, 245);
1819
1820     case 'Z':
1821     case 'z':
1822       return new Color(0, 80, 255);
1823
1824     default:
1825       Console.info("This is not a interaction : " + lastss);
1826       return null;
1827
1828     }
1829   }
1830
1831   private void fillPolygon(Graphics g, int[] xpoints, int[] ypoints, int n)
1832   {
1833     setAntialias(g);
1834     g.fillPolygon(xpoints, ypoints, n);
1835   }
1836
1837   /*
1838   private void fillRect(Graphics g, int a, int b, int c, int d)
1839   {
1840     fillRect(g, false, a, b, c, d);
1841   }*/
1842
1843   private void fillRect(Graphics g, int a, int b, int c, int d)
1844   {
1845     unsetAntialias(g);
1846     g.fillRect(a, b, c, d);
1847   }
1848
1849   private void fillRoundRect(Graphics g, int a, int b, int c, int d, int e,
1850           int f)
1851   {
1852     setAntialias(g);
1853     g.fillRoundRect(a, b, c, d, e, f);
1854   }
1855
1856   private void fillArc(Graphics g, int a, int b, int c, int d, int e, int f)
1857   {
1858     setAntialias(g);
1859     g.fillArc(a, b, c, d, e, f);
1860   }
1861
1862   private void drawLine(Graphics g, Stroke s, int a, int b, int c, int d)
1863   {
1864     Graphics2D g2d = (Graphics2D) g;
1865     Stroke p = g2d.getStroke();
1866     g2d.setStroke(s);
1867     drawLine(g, a, b, c, d);
1868     g2d.setStroke(p);
1869   }
1870
1871   private void drawLine(Graphics g, int a, int b, int c, int d)
1872   {
1873     setAntialias(g);
1874     g.drawLine(a, b, c, d);
1875   }
1876
1877   private void setAntialias(Graphics g)
1878   {
1879     if (isVectorRendition())
1880     {
1881       // no need to antialias vector drawings
1882       return;
1883     }
1884     if (Cache.getDefault("ANTI_ALIAS", true))
1885     {
1886       Graphics2D g2d = (Graphics2D) g;
1887       g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1888               RenderingHints.VALUE_ANTIALIAS_ON);
1889     }
1890   }
1891
1892   private void unsetAntialias(Graphics g)
1893   {
1894     if (isVectorRendition())
1895     {
1896       // no need to antialias vector drawings
1897       return;
1898     }
1899     Graphics2D g2d = (Graphics2D) g;
1900     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1901             RenderingHints.VALUE_ANTIALIAS_OFF);
1902   }
1903
1904   public void setVectorRendition(boolean b)
1905   {
1906     vectorRendition = b;
1907   }
1908
1909   public boolean isVectorRendition()
1910   {
1911     return vectorRendition;
1912   }
1913 }