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