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