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