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