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