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