JAL-1292 avoid exception by using bitset of arbitrary width for remembering which...
[jalview.git] / src / jalview / renderer / AnnotationRenderer.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.renderer;
19
20 import jalview.analysis.AAFrequency;
21 import jalview.analysis.StructureFrequency;
22 import jalview.api.AlignViewportI;
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.ColumnSelection;
26 import jalview.schemes.ColourSchemeI;
27
28 import java.awt.BasicStroke;
29 import java.awt.Color;
30 import java.awt.Font;
31 import java.awt.FontMetrics;
32 import java.awt.Graphics;
33 import java.awt.Graphics2D;
34 import java.awt.Image;
35 import java.awt.font.LineMetrics;
36 import java.awt.geom.AffineTransform;
37 import java.awt.image.ImageObserver;
38 import java.util.BitSet;
39 import java.util.Hashtable;
40
41 import com.stevesoft.pat.Regex;
42
43 public class AnnotationRenderer
44 {
45
46   public AnnotationRenderer()
47   {
48     // TODO Auto-generated constructor stub
49   }
50
51   public void drawStemAnnot(Graphics g, Annotation[] row_annotations,
52           int lastSSX, int x, int y, int iconOffset, int startRes,
53           int column, boolean validRes, boolean validEnd)
54   {
55     g.setColor(STEM_COLOUR);
56     int sCol = (lastSSX / charWidth) + startRes;
57     int x1 = lastSSX;
58     int x2 = (x * charWidth);
59     Regex closeparen = new Regex("(\\))");
60
61     String dc = (column == 0 || row_annotations[column - 1] == null) ? ""
62             : row_annotations[column - 1].displayCharacter;
63
64     boolean diffupstream = sCol == 0 || row_annotations[sCol - 1] == null
65             || !dc.equals(row_annotations[sCol - 1].displayCharacter);
66     boolean diffdownstream = !validRes || !validEnd
67             || row_annotations[column] == null
68             || !dc.equals(row_annotations[column].displayCharacter);
69     // System.out.println("Column "+column+" diff up: "+diffupstream+" down:"+diffdownstream);
70     // If a closing base pair half of the stem, display a backward arrow
71     if (column > 0 && closeparen.search(dc))
72     {
73       if (diffupstream)
74       // if (validRes && column>1 && row_annotations[column-2]!=null &&
75       // dc.equals(row_annotations[column-2].displayCharacter))
76       {
77         g.fillPolygon(new int[]
78         { lastSSX + 5, lastSSX + 5, lastSSX }, new int[]
79         { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset }, 3);
80         x1 += 5;
81       }
82       if (diffdownstream)
83       {
84         x2 -= 1;
85       }
86     }
87     else
88     {
89       // display a forward arrow
90       if (diffdownstream)
91       {
92         g.fillPolygon(new int[]
93         { x2 - 5, x2 - 5, x2 }, new int[]
94         { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset }, 3);
95         x2 -= 5;
96       }
97       if (diffupstream)
98       {
99         x1 += 1;
100       }
101     }
102     // draw arrow body
103     g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 7);
104   }
105
106   private int charWidth, endRes, charHeight;
107
108   private boolean validCharWidth, hasHiddenColumns;
109
110   private FontMetrics fm;
111
112   private final boolean MAC = new jalview.util.Platform().isAMac();
113
114   boolean av_renderHistogram = true, av_renderProfile = true,
115           av_normaliseProfile = false;
116
117   ColourSchemeI profcolour = null;
118
119   private ColumnSelection columnSelection;
120
121   private Hashtable[] hconsensus;
122
123   private Hashtable[] hStrucConsensus;
124
125   private boolean av_ignoreGapsConsensus;
126
127   /**
128    * attributes set from AwtRenderPanelI
129    */
130   /**
131    * old image used when data is currently being calculated and cannot be
132    * rendered
133    */
134   private Image fadedImage;
135
136   /**
137    * panel being rendered into
138    */
139   private ImageObserver annotationPanel;
140
141   /**
142    * width of image to render in panel
143    */
144   private int imgWidth;
145
146   // public void updateFromAnnotationPanel(FontMetrics annotFM, AlignViewportI
147   // av)
148   public void updateFromAwtRenderPanel(AwtRenderPanelI annotPanel,
149           AlignViewportI av)
150   {
151     fm = annotPanel.getFontMetrics();
152     annotationPanel = annotPanel;
153     fadedImage = annotPanel.getFadedImage();
154     imgWidth = annotPanel.getFadedImageWidth();
155     updateFromAlignViewport(av);
156   }
157
158   public void updateFromAlignViewport(AlignViewportI av)
159   {
160     charWidth = av.getCharWidth();
161     endRes = av.getEndRes();
162     charHeight = av.getCharHeight();
163     hasHiddenColumns = av.hasHiddenColumns();
164     validCharWidth = av.isValidCharWidth();
165     av_renderHistogram = av.isShowConsensusHistogram();
166     av_renderProfile = av.isShowSequenceLogo();
167     av_normaliseProfile = av.isNormaliseSequenceLogo();
168     profcolour = av.getGlobalColourScheme();
169     if (profcolour == null)
170     {
171       // Set the default colour for sequence logo if the alignnent has no
172       // colourscheme set
173       profcolour = av.getAlignment().isNucleotide() ? new jalview.schemes.NucleotideColourScheme()
174               : new jalview.schemes.ZappoColourScheme();
175     }
176     columnSelection = av.getColumnSelection();
177     hconsensus = av.getSequenceConsensusHash();// hconsensus;
178     hStrucConsensus = av.getRnaStructureConsensusHash(); // hStrucConsensus;
179     av_ignoreGapsConsensus = av.getIgnoreGapsConsensus();
180   }
181
182   public int[] getProfileFor(AlignmentAnnotation aa, int column)
183   {
184     // TODO : consider refactoring the global alignment calculation
185     // properties/rendering attributes as a global 'alignment group' which holds
186     // all vis settings for the alignment as a whole rather than a subset
187     //
188     if (aa.autoCalculated && aa.label.startsWith("Consensus"))
189     {
190       if (aa.groupRef != null && aa.groupRef.consensusData != null
191               && aa.groupRef.isShowSequenceLogo())
192       {
193         return AAFrequency.extractProfile(
194                 aa.groupRef.consensusData[column],
195                 aa.groupRef.getIgnoreGapsConsensus());
196       }
197       // TODO extend annotation row to enable dynamic and static profile data to
198       // be stored
199       if (aa.groupRef == null && aa.sequenceRef == null && av_renderProfile)
200       {
201         return AAFrequency.extractProfile(hconsensus[column],
202                 av_ignoreGapsConsensus);
203       }
204     }
205     else
206     {
207       if (aa.autoCalculated && aa.label.startsWith("StrucConsensus"))
208       {
209         // TODO implement group structure consensus
210         /*
211          * if (aa.groupRef != null && aa.groupRef.consensusData != null &&
212          * aa.groupRef.isShowSequenceLogo()) { //TODO check what happens for
213          * group selections return StructureFrequency.extractProfile(
214          * aa.groupRef.consensusData[column], aa.groupRef
215          * .getIgnoreGapsConsensus()); }
216          */
217         // TODO extend annotation row to enable dynamic and static profile data
218         // to
219         // be stored
220         if (aa.groupRef == null && aa.sequenceRef == null
221                 && av_renderProfile && hStrucConsensus != null
222                 && hStrucConsensus.length > column)
223         {
224           return StructureFrequency.extractProfile(hStrucConsensus[column],
225                   av_ignoreGapsConsensus);
226         }
227       }
228     }
229     return null;
230   }
231
232   /**
233    * Render the annotation rows associated with an alignment.
234    * 
235    * @param annotPanel
236    *          container frame
237    * @param av
238    *          data and view settings to render
239    * @param g
240    *          destination for graphics
241    * @param activeRow
242    *          row where a mouse event occured (or -1)
243    * @param startRes
244    *          first column that will be drawn
245    * @param endRes
246    *          last column that will be drawn
247    * @return true if the fadedImage was used for any alignment annotation rows
248    *         currently being calculated
249    */
250   public boolean drawComponent(AwtRenderPanelI annotPanel,
251           AlignViewportI av, Graphics g, int activeRow, int startRes,
252           int endRes)
253   {
254     boolean usedFaded = false;
255     // NOTES:
256     // AnnotationPanel needs to implement: ImageObserver, access to
257     // AlignViewport
258     updateFromAwtRenderPanel(annotPanel, av);
259     fm = g.getFontMetrics();
260     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
261     if (aa==null)
262     {
263       return false;
264     }
265     int x = 0, y = 0;
266     int column = 0;
267     char lastSS;
268     int lastSSX;
269     int iconOffset = 0;
270     boolean validRes = false;
271     boolean validEnd = false;
272     boolean labelAllCols = false;
273     boolean centreColLabels, centreColLabelsDef = av
274             .getCentreColumnLabels();
275     boolean scaleColLabel = false;
276
277     BitSet graphGroupDrawn = new BitSet();
278     int charOffset = 0; // offset for a label
279     float fmWidth, fmScaling = 1f; // scaling for a label to fit it into a
280     // column.
281     Font ofont = g.getFont();
282     // \u03B2 \u03B1
283     for (int i = 0; i < aa.length; i++)
284     {
285       AlignmentAnnotation row = aa[i];
286       Annotation[] row_annotations = row.annotations;
287       if (!row.visible)
288       {
289         continue;
290       }
291       centreColLabels = row.centreColLabels || centreColLabelsDef;
292       labelAllCols = row.showAllColLabels;
293       scaleColLabel = row.scaleColLabel;
294       lastSS = ' ';
295       lastSSX = 0;
296       if (row.graph > 0)
297       {
298         if (row.graphGroup > -1 && graphGroupDrawn.get(row.graphGroup)) {
299           continue;
300         }
301
302         // this is so that we draw the characters below the graph
303         y += row.height;
304
305         if (row.hasText)
306         {
307           iconOffset = charHeight - fm.getDescent();
308           y -= charHeight;
309         }
310       }
311       else if (row.hasText)
312       {
313         iconOffset = charHeight - fm.getDescent();
314
315       }
316       else
317       {
318         iconOffset = 0;
319       }
320
321       if (row.autoCalculated && av.isCalculationInProgress(row))
322       {
323         y += charHeight;
324         usedFaded = true;
325         g.drawImage(fadedImage, 0, y - row.height, imgWidth, y, 0, y
326                 - row.height, imgWidth, y, annotationPanel);
327         g.setColor(Color.black);
328         // g.drawString("Calculating "+aa[i].label+"....",20, y-row.height/2);
329
330         continue;
331       }
332
333       /*
334        * else if (annotationPanel.av.updatingConservation &&
335        * aa[i].label.equals("Conservation")) {
336        * 
337        * y += charHeight; g.drawImage(annotationPanel.fadedImage, 0, y -
338        * row.height, annotationPanel.imgWidth, y, 0, y - row.height,
339        * annotationPanel.imgWidth, y, annotationPanel);
340        * 
341        * g.setColor(Color.black); //
342        * g.drawString("Calculating Conservation.....",20, y-row.height/2);
343        * 
344        * continue; } else if (annotationPanel.av.updatingConservation &&
345        * aa[i].label.equals("Quality")) {
346        * 
347        * y += charHeight; g.drawImage(annotationPanel.fadedImage, 0, y -
348        * row.height, annotationPanel.imgWidth, y, 0, y - row.height,
349        * annotationPanel.imgWidth, y, annotationPanel); g.setColor(Color.black);
350        * // / g.drawString("Calculating Quality....",20, y-row.height/2);
351        * 
352        * continue; }
353        */
354       // first pass sets up state for drawing continuation from left-hand column
355       // of startRes
356       x = (startRes == 0) ? 0 : -1;
357       while (x < endRes - startRes)
358       {
359         if (hasHiddenColumns)
360         {
361           column = columnSelection.adjustForHiddenColumns(startRes + x);
362           if (column > row_annotations.length - 1)
363           {
364             break;
365           }
366         }
367         else
368         {
369           column = startRes + x;
370         }
371
372         if ((row_annotations == null) || (row_annotations.length <= column)
373                 || (row_annotations[column] == null))
374         {
375           validRes = false;
376         }
377         else
378         {
379           validRes = true;
380         }
381         if (x > -1)
382         {
383           if (activeRow == i)
384           {
385             g.setColor(Color.red);
386
387             if (columnSelection != null)
388             {
389               for (int n = 0; n < columnSelection.size(); n++)
390               {
391                 int v = columnSelection.columnAt(n);
392
393                 if (v == column)
394                 {
395                   g.fillRect(x * charWidth, y, charWidth, charHeight);
396                 }
397               }
398             }
399           }
400           if (!row.isValidStruc())
401           {
402             g.setColor(Color.orange);
403             g.fillRect((int) row.getInvalidStrucPos() * charWidth, y,
404                     charWidth, charHeight);
405           }
406           if (validCharWidth
407                   && validRes
408                   && row_annotations[column].displayCharacter != null
409                   && (row_annotations[column].displayCharacter.length() > 0))
410           {
411
412             if (centreColLabels || scaleColLabel)
413             {
414               fmWidth = fm.charsWidth(
415                       row_annotations[column].displayCharacter
416                               .toCharArray(), 0,
417                       row_annotations[column].displayCharacter.length());
418
419               if (scaleColLabel)
420               {
421                 // justify the label and scale to fit in column
422                 if (fmWidth > charWidth)
423                 {
424                   // scale only if the current font isn't already small enough
425                   fmScaling = charWidth;
426                   fmScaling /= fmWidth;
427                   g.setFont(ofont.deriveFont(AffineTransform
428                           .getScaleInstance(fmScaling, 1.0)));
429                   // and update the label's width to reflect the scaling.
430                   fmWidth = charWidth;
431                 }
432               }
433             }
434             else
435             {
436               fmWidth = fm
437                       .charWidth(row_annotations[column].displayCharacter
438                               .charAt(0));
439             }
440             charOffset = (int) ((charWidth - fmWidth) / 2f);
441
442             if (row_annotations[column].colour == null)
443               g.setColor(Color.black);
444             else
445               g.setColor(row_annotations[column].colour);
446
447             if (column == 0 || row.graph > 0)
448             {
449               g.drawString(row_annotations[column].displayCharacter,
450                       (x * charWidth) + charOffset, y + iconOffset);
451             }
452             else if (row_annotations[column - 1] == null
453                     || (labelAllCols
454                             || !row_annotations[column].displayCharacter
455                                     .equals(row_annotations[column - 1].displayCharacter) || (row_annotations[column].displayCharacter
456                             .length() < 2 && row_annotations[column].secondaryStructure == ' ')))
457             {
458               g.drawString(row_annotations[column].displayCharacter, x
459                       * charWidth + charOffset, y + iconOffset);
460             }
461             g.setFont(ofont);
462           }
463         }
464         if (row.hasIcons)
465         {
466           char ss = validRes ? row_annotations[column].secondaryStructure
467                   : ' ';
468           if (ss == 'S')
469           {
470             // distinguish between forward/backward base-pairing
471             if (row_annotations[column].displayCharacter.indexOf(')') > -1)
472             {
473               ss = 's';
474             }
475           }
476           if (!validRes || (ss != lastSS))
477           {
478             if (x > -1)
479             {
480               switch (lastSS)
481               {
482               case 'H':
483                 drawHelixAnnot(g, row_annotations, lastSSX, x, y,
484                         iconOffset, startRes, column, validRes, validEnd);
485                 break;
486
487               case 'E':
488                 drawSheetAnnot(g, row_annotations, lastSSX, x, y,
489                         iconOffset, startRes, column, validRes, validEnd);
490                 break;
491
492               case 'S': // Stem case for RNA secondary structure
493               case 's': // and opposite direction
494                 drawStemAnnot(g, row_annotations, lastSSX, x, y,
495                         iconOffset, startRes, column, validRes, validEnd);
496                 break;
497
498               default:
499                 g.setColor(Color.gray);
500                 g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth)
501                         - lastSSX, 2);
502
503                 break;
504               }
505             }
506             if (validRes)
507             {
508               lastSS = ss;
509             }
510             else
511             {
512               lastSS = ' ';
513             }
514             if (x > -1)
515             {
516               lastSSX = (x * charWidth);
517             }
518           }
519         }
520         column++;
521         x++;
522       }
523       if (column >= row_annotations.length)
524       {
525         column = row_annotations.length - 1;
526         validEnd = false;
527       }
528       else
529       {
530         validEnd = true;
531       }
532       if ((row_annotations == null) || (row_annotations.length <= column)
533               || (row_annotations[column] == null))
534       {
535         validRes = false;
536       }
537       else
538       {
539         validRes = true;
540       }
541
542       // x ++;
543
544       if (row.hasIcons)
545       {
546         switch (lastSS)
547         {
548         case 'H':
549           drawHelixAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
550                   startRes, column, validRes, validEnd);
551           break;
552
553         case 'E':
554           drawSheetAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
555                   startRes, column, validRes, validEnd);
556           break;
557         case 's':
558         case 'S': // Stem case for RNA secondary structure
559           drawStemAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
560                   startRes, column, validRes, validEnd);
561           break;
562         default:
563           drawGlyphLine(g, row_annotations, lastSSX, x, y, iconOffset,
564                   startRes, column, validRes, validEnd);
565           break;
566         }
567       }
568
569       if (row.graph > 0 && row.graphHeight > 0)
570       {
571         if (row.graph == AlignmentAnnotation.LINE_GRAPH)
572         {
573           if (row.graphGroup > -1 && !graphGroupDrawn.get(row.graphGroup))
574           {
575             float groupmax = -999999, groupmin = 9999999;
576             for (int gg = 0; gg < aa.length; gg++)
577             {
578               if (aa[gg].graphGroup != row.graphGroup)
579               {
580                 continue;
581               }
582
583               if (aa[gg] != row)
584               {
585                 aa[gg].visible = false;
586               }
587               if (aa[gg].graphMax > groupmax)
588               {
589                 groupmax = aa[gg].graphMax;
590               }
591               if (aa[gg].graphMin < groupmin)
592               {
593                 groupmin = aa[gg].graphMin;
594               }
595             }
596
597             for (int gg = 0; gg < aa.length; gg++)
598             {
599               if (aa[gg].graphGroup == row.graphGroup)
600               {
601                 drawLineGraph(g, aa[gg], aa[gg].annotations, startRes,
602                         endRes, y, groupmin, groupmax, row.graphHeight);
603               }
604             }
605
606             graphGroupDrawn.set(row.graphGroup);
607           }
608           else
609           {
610             drawLineGraph(g, row, row_annotations, startRes, endRes, y,
611                     row.graphMin, row.graphMax, row.graphHeight);
612           }
613         }
614         else if (row.graph == AlignmentAnnotation.BAR_GRAPH)
615         {
616           drawBarGraph(g, row, row_annotations, startRes, endRes,
617                   row.graphMin, row.graphMax, y);
618         }
619       }
620
621       if (row.graph > 0 && row.hasText)
622       {
623         y += charHeight;
624       }
625
626       if (row.graph == 0)
627       {
628         y += aa[i].height;
629       }
630     }
631     return !usedFaded;
632   }
633
634   private final Color GLYPHLINE_COLOR = Color.gray;
635
636   private final Color SHEET_COLOUR = Color.green;
637
638   private final Color HELIX_COLOUR = Color.red;
639
640   private final Color STEM_COLOUR = Color.blue;
641
642   public void drawGlyphLine(Graphics g, Annotation[] row, int lastSSX,
643           int x, int y, int iconOffset, int startRes, int column,
644           boolean validRes, boolean validEnd)
645   {
646     g.setColor(GLYPHLINE_COLOR);
647     g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth) - lastSSX, 2);
648   }
649
650   public void drawSheetAnnot(Graphics g, Annotation[] row, int lastSSX,
651           int x, int y, int iconOffset, int startRes, int column,
652           boolean validRes, boolean validEnd)
653   {
654     g.setColor(SHEET_COLOUR);
655
656     if (!validEnd || !validRes || row == null || row[column] == null
657             || row[column].secondaryStructure != 'E')
658     {
659       g.fillRect(lastSSX, y + 4 + iconOffset,
660               (x * charWidth) - lastSSX - 4, 7);
661       g.fillPolygon(new int[]
662       { (x * charWidth) - 4, (x * charWidth) - 4, (x * charWidth) },
663               new int[]
664               { y + iconOffset, y + 14 + iconOffset, y + 7 + iconOffset },
665               3);
666     }
667     else
668     {
669       g.fillRect(lastSSX, y + 4 + iconOffset,
670               (x + 1) * charWidth - lastSSX, 7);
671     }
672
673   }
674
675   public void drawHelixAnnot(Graphics g, Annotation[] row, int lastSSX,
676           int x, int y, int iconOffset, int startRes, int column,
677           boolean validRes, boolean validEnd)
678   {
679     g.setColor(HELIX_COLOUR);
680
681     int sCol = (lastSSX / charWidth) + startRes;
682     int x1 = lastSSX;
683     int x2 = (x * charWidth);
684
685     if (MAC)
686     {
687       int ofs = charWidth / 2;
688       // Off by 1 offset when drawing rects and ovals
689       // to offscreen image on the MAC
690       g.fillRoundRect(lastSSX, y + 4 + iconOffset, x2 - x1, 8, 8, 8);
691       if (sCol == 0 || row[sCol - 1] == null
692               || row[sCol - 1].secondaryStructure != 'H')
693       {
694       }
695       else
696       {
697         // g.setColor(Color.orange);
698         g.fillRoundRect(lastSSX, y + 4 + iconOffset, x2 - x1 - ofs + 1, 8,
699                 0, 0);
700       }
701       if (!validRes || row[column] == null
702               || row[column].secondaryStructure != 'H')
703       {
704
705       }
706       else
707       {
708         // g.setColor(Color.magenta);
709         g.fillRoundRect(lastSSX + ofs, y + 4 + iconOffset, x2 - x1 - ofs
710                 + 1, 8, 0, 0);
711
712       }
713
714       return;
715     }
716
717     if (sCol == 0 || row[sCol - 1] == null
718             || row[sCol - 1].secondaryStructure != 'H')
719     {
720       g.fillArc(lastSSX, y + 4 + iconOffset, charWidth, 8, 90, 180);
721       x1 += charWidth / 2;
722     }
723
724     if (!validRes || row[column] == null
725             || row[column].secondaryStructure != 'H')
726     {
727       g.fillArc((x * charWidth) - charWidth, y + 4 + iconOffset, charWidth,
728               8, 270, 180);
729       x2 -= charWidth / 2;
730     }
731
732     g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 8);
733   }
734
735   public void drawLineGraph(Graphics g, AlignmentAnnotation _aa,
736           Annotation[] aa_annotations, int sRes, int eRes, int y,
737           float min, float max, int graphHeight)
738   {
739     if (sRes > aa_annotations.length)
740     {
741       return;
742     }
743
744     int x = 0;
745
746     // Adjustment for fastpaint to left
747     if (eRes < endRes)
748     {
749       eRes++;
750     }
751
752     eRes = Math.min(eRes, aa_annotations.length);
753
754     if (sRes == 0)
755     {
756       x++;
757     }
758
759     int y1 = y, y2 = y;
760     float range = max - min;
761
762     // //Draw origin
763     if (min < 0)
764     {
765       y2 = y - (int) ((0 - min / range) * graphHeight);
766     }
767
768     g.setColor(Color.gray);
769     g.drawLine(x - charWidth, y2, (eRes - sRes + 1) * charWidth, y2);
770
771     eRes = Math.min(eRes, aa_annotations.length);
772
773     int column;
774     int aaMax = aa_annotations.length - 1;
775
776     while (x < eRes - sRes)
777     {
778       column = sRes + x;
779       if (hasHiddenColumns)
780       {
781         column = columnSelection.adjustForHiddenColumns(column);
782       }
783
784       if (column > aaMax)
785       {
786         break;
787       }
788
789       if (aa_annotations[column] == null
790               || aa_annotations[column - 1] == null)
791       {
792         x++;
793         continue;
794       }
795
796       if (aa_annotations[column].colour == null)
797         g.setColor(Color.black);
798       else
799         g.setColor(aa_annotations[column].colour);
800
801       y1 = y
802               - (int) (((aa_annotations[column - 1].value - min) / range) * graphHeight);
803       y2 = y
804               - (int) (((aa_annotations[column].value - min) / range) * graphHeight);
805
806       g.drawLine(x * charWidth - charWidth / 2, y1, x * charWidth
807               + charWidth / 2, y2);
808       x++;
809     }
810
811     if (_aa.threshold != null)
812     {
813       g.setColor(_aa.threshold.colour);
814       Graphics2D g2 = (Graphics2D) g;
815       g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
816               BasicStroke.JOIN_ROUND, 3f, new float[]
817               { 5f, 3f }, 0f));
818
819       y2 = (int) (y - ((_aa.threshold.value - min) / range) * graphHeight);
820       g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
821       g2.setStroke(new BasicStroke());
822     }
823   }
824
825   public void drawBarGraph(Graphics g, AlignmentAnnotation _aa,
826           Annotation[] aa_annotations, int sRes, int eRes, float min,
827           float max, int y)
828   {
829     if (sRes > aa_annotations.length)
830     {
831       return;
832     }
833     Font ofont = g.getFont();
834     eRes = Math.min(eRes, aa_annotations.length);
835
836     int x = 0, y1 = y, y2 = y;
837
838     float range = max - min;
839
840     if (min < 0)
841     {
842       y2 = y - (int) ((0 - min / (range)) * _aa.graphHeight);
843     }
844
845     g.setColor(Color.gray);
846
847     g.drawLine(x, y2, (eRes - sRes) * charWidth, y2);
848
849     int column;
850     int aaMax = aa_annotations.length - 1;
851     boolean renderHistogram = true, renderProfile = true, normaliseProfile = false;
852     // if (aa.autoCalculated && aa.label.startsWith("Consensus"))
853     {
854       // TODO: generalise this to have render styles for consensus/profile data
855       if (_aa.groupRef != null)
856       {
857         renderHistogram = _aa.groupRef.isShowConsensusHistogram();
858         renderProfile = _aa.groupRef.isShowSequenceLogo();
859         normaliseProfile = _aa.groupRef.isNormaliseSequenceLogo();
860       }
861       else
862       {
863         renderHistogram = av_renderHistogram;
864         renderProfile = av_renderProfile;
865         normaliseProfile = av_normaliseProfile;
866       }
867     }
868     while (x < eRes - sRes)
869     {
870       column = sRes + x;
871       if (hasHiddenColumns)
872       {
873         column = columnSelection.adjustForHiddenColumns(column);
874       }
875
876       if (column > aaMax)
877       {
878         break;
879       }
880
881       if (aa_annotations[column] == null)
882       {
883         x++;
884         continue;
885       }
886       if (aa_annotations[column].colour == null)
887         g.setColor(Color.black);
888       else
889         g.setColor(aa_annotations[column].colour);
890
891       y1 = y
892               - (int) (((aa_annotations[column].value - min) / (range)) * _aa.graphHeight);
893
894       if (renderHistogram)
895       {
896         if (y1 - y2 > 0)
897         {
898           g.fillRect(x * charWidth, y2, charWidth, y1 - y2);
899         }
900         else
901         {
902           g.fillRect(x * charWidth, y1, charWidth, y2 - y1);
903         }
904       }
905       // draw profile if available
906       if (renderProfile)
907       {
908
909         int profl[] = getProfileFor(_aa, column);
910         // just try to draw the logo if profl is not null
911         if (profl != null && profl[1] != 0)
912         {
913           float ht = normaliseProfile ? y - _aa.graphHeight : y1;
914           double htn = normaliseProfile ? _aa.graphHeight : (y2 - y1);// aa.graphHeight;
915           double hght;
916           float wdth;
917           double ht2 = 0;
918           char[] dc;
919
920           /**
921            * profl.length == 74 indicates that the profile of a secondary
922            * structure conservation row was accesed. Therefore dc gets length 2,
923            * to have space for a basepair instead of just a single nucleotide
924            */
925           if (profl.length == 74)
926           {
927             dc = new char[2];
928           }
929           else
930           {
931             dc = new char[1];
932           }
933           LineMetrics lm = g.getFontMetrics(ofont).getLineMetrics("Q", g);
934           double scale = 1f / (normaliseProfile ? profl[1] : 100f);
935           float ofontHeight = 1f / lm.getAscent();// magnify to fill box
936           double scl = 0.0;
937           for (int c = 2; c < profl[0];)
938           {
939             dc[0] = (char) profl[c++];
940
941             if (_aa.label.startsWith("StrucConsensus"))
942             {
943               dc[1] = (char) profl[c++];
944             }
945
946             wdth = charWidth;
947             wdth /= fm.charsWidth(dc, 0, dc.length);
948
949             ht += scl;
950             {
951               scl = htn * scale * profl[c++];
952               lm = ofont.getLineMetrics(dc, 0, 1, g.getFontMetrics()
953                       .getFontRenderContext());
954               g.setFont(ofont.deriveFont(AffineTransform.getScaleInstance(
955                       wdth, scl / lm.getAscent())));
956               lm = g.getFontMetrics().getLineMetrics(dc, 0, 1, g);
957
958               // Debug - render boxes around characters
959               // g.setColor(Color.red);
960               // g.drawRect(x*av.charWidth, (int)ht, av.charWidth,
961               // (int)(scl));
962               // g.setColor(profcolour.findColour(dc[0]).darker());
963               g.setColor(profcolour.findColour(dc[0], column, null));
964
965               hght = (ht + (scl - lm.getDescent() - lm.getBaselineOffsets()[lm
966                       .getBaselineIndex()]));
967
968               g.drawChars(dc, 0, dc.length, x * charWidth, (int) hght);
969             }
970           }
971           g.setFont(ofont);
972         }
973       }
974       x++;
975     }
976     if (_aa.threshold != null)
977     {
978       g.setColor(_aa.threshold.colour);
979       Graphics2D g2 = (Graphics2D) g;
980       g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
981               BasicStroke.JOIN_ROUND, 3f, new float[]
982               { 5f, 3f }, 0f));
983
984       y2 = (int) (y - ((_aa.threshold.value - min) / range)
985               * _aa.graphHeight);
986       g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
987       g2.setStroke(new BasicStroke());
988     }
989   }
990
991   // used by overview window
992   public void drawGraph(Graphics g, AlignmentAnnotation _aa,
993           Annotation[] aa_annotations, int width, int y, int sRes, int eRes)
994   {
995     eRes = Math.min(eRes, aa_annotations.length);
996     g.setColor(Color.white);
997     g.fillRect(0, 0, width, y);
998     g.setColor(new Color(0, 0, 180));
999
1000     int x = 0, height;
1001
1002     for (int j = sRes; j < eRes; j++)
1003     {
1004       if (aa_annotations[j] != null)
1005       {
1006         if (aa_annotations[j].colour == null)
1007           g.setColor(Color.black);
1008         else
1009           g.setColor(aa_annotations[j].colour);
1010
1011         height = (int) ((aa_annotations[j].value / _aa.graphMax) * y);
1012         if (height > y)
1013         {
1014           height = y;
1015         }
1016
1017         g.fillRect(x, y - height, charWidth, height);
1018       }
1019       x += charWidth;
1020     }
1021   }
1022 }