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