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