Merge branch 'develop' into features/JAL-845splitPaneMergeDevelop
[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 jalview.analysis.AAFrequency;
24 import jalview.analysis.StructureFrequency;
25 import jalview.api.AlignViewportI;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.Annotation;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.schemes.ColourSchemeI;
30 import jalview.schemes.ResidueProperties;
31
32 import java.awt.BasicStroke;
33 import java.awt.Color;
34 import java.awt.Font;
35 import java.awt.FontMetrics;
36 import java.awt.Graphics;
37 import java.awt.Graphics2D;
38 import java.awt.Image;
39 import java.awt.font.LineMetrics;
40 import java.awt.geom.AffineTransform;
41 import java.awt.image.ImageObserver;
42 import java.util.BitSet;
43 import java.util.Hashtable;
44
45 import com.stevesoft.pat.Regex;
46
47 public class AnnotationRenderer
48 {
49   /**
50    * flag indicating if timing and redraw parameter info should be output
51    */
52   private final boolean debugRedraw;
53
54   public AnnotationRenderer()
55   {
56     this(false);
57   }
58
59   /**
60    * Create a new annotation Renderer
61    * 
62    * @param debugRedraw
63    *          flag indicating if timing and redraw parameter info should be
64    *          output
65    */
66   public AnnotationRenderer(boolean debugRedraw)
67   {
68     this.debugRedraw = debugRedraw;
69   }
70
71   public void drawStemAnnot(Graphics g, Annotation[] row_annotations,
72           int lastSSX, int x, int y, int iconOffset, int startRes,
73           int column, boolean validRes, boolean validEnd)
74   {
75     g.setColor(STEM_COLOUR);
76     int sCol = (lastSSX / charWidth) + startRes;
77     int x1 = lastSSX;
78     int x2 = (x * charWidth);
79     Regex closeparen = new Regex("(\\))");
80
81     char dc = (column == 0 || row_annotations[column - 1] == null) ? ' '
82             : row_annotations[column - 1].secondaryStructure;
83
84     boolean diffupstream = sCol == 0 || row_annotations[sCol - 1] == null
85             || dc != row_annotations[sCol - 1].secondaryStructure;
86     boolean diffdownstream = !validRes || !validEnd
87             || row_annotations[column] == null
88             || dc != row_annotations[column].secondaryStructure;
89     // System.out.println("Column "+column+" diff up: "+diffupstream+" down:"+diffdownstream);
90     // If a closing base pair half of the stem, display a backward arrow
91     if (column > 0 && ResidueProperties.isCloseParenRNA(dc))
92     {
93
94       if (diffupstream)
95       // if (validRes && column>1 && row_annotations[column-2]!=null &&
96       // dc.equals(row_annotations[column-2].displayCharacter))
97       {
98         g.fillPolygon(new int[]
99         { lastSSX + 5, lastSSX + 5, lastSSX }, new int[]
100         { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset }, 3);
101         x1 += 5;
102       }
103       if (diffdownstream)
104       {
105         x2 -= 1;
106       }
107     }
108     else
109     {
110
111       // display a forward arrow
112       if (diffdownstream)
113       {
114         g.fillPolygon(new int[]
115         { x2 - 5, x2 - 5, x2 }, new int[]
116         { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset }, 3);
117         x2 -= 5;
118       }
119       if (diffupstream)
120       {
121         x1 += 1;
122       }
123     }
124     // draw arrow body
125     g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 7);
126   }
127
128   private int charWidth, endRes, charHeight;
129
130   private boolean validCharWidth, hasHiddenColumns;
131
132   private FontMetrics fm;
133
134   private final boolean MAC = new jalview.util.Platform().isAMac();
135
136   boolean av_renderHistogram = true, av_renderProfile = true,
137           av_normaliseProfile = false;
138
139   ColourSchemeI profcolour = null;
140
141   private ColumnSelection columnSelection;
142
143   private Hashtable[] hconsensus;
144
145   private Hashtable[] hStrucConsensus;
146
147   private boolean av_ignoreGapsConsensus;
148
149   /**
150    * attributes set from AwtRenderPanelI
151    */
152   /**
153    * old image used when data is currently being calculated and cannot be
154    * rendered
155    */
156   private Image fadedImage;
157
158   /**
159    * panel being rendered into
160    */
161   private ImageObserver annotationPanel;
162
163   /**
164    * width of image to render in panel
165    */
166   private int imgWidth;
167
168   /**
169    * offset to beginning of visible area
170    */
171   private int sOffset;
172
173   /**
174    * offset to end of visible area
175    */
176   private int visHeight;
177
178   /**
179    * indicate if the renderer should only render the visible portion of the
180    * annotation given the current view settings
181    */
182   private boolean useClip = true;
183
184   /**
185    * master flag indicating if renderer should ever try to clip. not enabled for
186    * jalview 2.8.1
187    */
188   private boolean canClip = false;
189
190   public void drawNotCanonicalAnnot(Graphics g, Color nonCanColor,
191           Annotation[] row_annotations, int lastSSX, int x, int y,
192           int iconOffset, int startRes, int column, boolean validRes,
193           boolean validEnd)
194   {
195     // System.out.println(nonCanColor);
196
197     g.setColor(nonCanColor);
198     int sCol = (lastSSX / charWidth) + startRes;
199     int x1 = lastSSX;
200     int x2 = (x * charWidth);
201     Regex closeparen = new Regex("}|]|<|[a-z]");
202
203     String dc = (column == 0 || row_annotations[column - 1] == null) ? ""
204             : row_annotations[column - 1].displayCharacter;
205
206     boolean diffupstream = sCol == 0 || row_annotations[sCol - 1] == null
207             || !dc.equals(row_annotations[sCol - 1].displayCharacter);
208     boolean diffdownstream = !validRes || !validEnd
209             || row_annotations[column] == null
210             || !dc.equals(row_annotations[column].displayCharacter);
211     // System.out.println("Column "+column+" diff up: "+diffupstream+" down:"+diffdownstream);
212     // If a closing base pair half of the stem, display a backward arrow
213     if (column > 0 && closeparen.search(dc))// closeletter_b.search(dc)||closeletter_c.search(dc)||closeletter_d.search(dc)||closecrochet.search(dc))
214                                             // )
215     {
216
217       if (diffupstream)
218       // if (validRes && column>1 && row_annotations[column-2]!=null &&
219       // dc.equals(row_annotations[column-2].displayCharacter))
220       {
221         g.fillPolygon(new int[]
222         { lastSSX + 5, lastSSX + 5, lastSSX }, new int[]
223         { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset }, 3);
224         x1 += 5;
225       }
226       if (diffdownstream)
227       {
228         x2 -= 1;
229       }
230     }
231     else
232     {
233
234       // display a forward arrow
235       if (diffdownstream)
236       {
237         g.fillPolygon(new int[]
238         { x2 - 5, x2 - 5, x2 }, new int[]
239         { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset }, 3);
240         x2 -= 5;
241       }
242       if (diffupstream)
243       {
244         x1 += 1;
245       }
246     }
247     // draw arrow body
248     g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 7);
249   }
250
251   // public void updateFromAnnotationPanel(FontMetrics annotFM, AlignViewportI
252   // av)
253   public void updateFromAwtRenderPanel(AwtRenderPanelI annotPanel,
254           AlignViewportI av)
255   {
256     fm = annotPanel.getFontMetrics();
257     annotationPanel = annotPanel;
258     fadedImage = annotPanel.getFadedImage();
259     imgWidth = annotPanel.getFadedImageWidth();
260     // visible area for rendering
261     int[] bounds = annotPanel.getVisibleVRange();
262     if (bounds != null)
263     {
264       sOffset = bounds[0];
265       visHeight = bounds[1];
266       if (visHeight == 0)
267       {
268         useClip = false;
269       }
270       else
271       {
272         useClip = canClip;
273       }
274     }
275     else
276     {
277       useClip = false;
278     }
279
280     updateFromAlignViewport(av);
281   }
282
283   public void updateFromAlignViewport(AlignViewportI av)
284   {
285     charWidth = av.getCharWidth();
286     endRes = av.getEndRes();
287     charHeight = av.getCharHeight();
288     hasHiddenColumns = av.hasHiddenColumns();
289     validCharWidth = av.isValidCharWidth();
290     av_renderHistogram = av.isShowConsensusHistogram();
291     av_renderProfile = av.isShowSequenceLogo();
292     av_normaliseProfile = av.isNormaliseSequenceLogo();
293     profcolour = av.getGlobalColourScheme();
294     if (profcolour == null)
295     {
296       // Set the default colour for sequence logo if the alignnent has no
297       // colourscheme set
298       profcolour = av.getAlignment().isNucleotide() ? new jalview.schemes.NucleotideColourScheme()
299               : new jalview.schemes.ZappoColourScheme();
300     }
301     boolean rna = av.getAlignment().isNucleotide();
302     columnSelection = av.getColumnSelection();
303     hconsensus = av.getSequenceConsensusHash();// hconsensus;
304     hStrucConsensus = av.getRnaStructureConsensusHash(); // hStrucConsensus;
305     av_ignoreGapsConsensus = av.isIgnoreGapsConsensus();
306   }
307
308   public int[] getProfileFor(AlignmentAnnotation aa, int column)
309   {
310     // TODO : consider refactoring the global alignment calculation
311     // properties/rendering attributes as a global 'alignment group' which holds
312     // all vis settings for the alignment as a whole rather than a subset
313     //
314     if (aa.autoCalculated && aa.label.startsWith("Consensus"))
315     {
316       if (aa.groupRef != null && aa.groupRef.consensusData != null
317               && aa.groupRef.isShowSequenceLogo())
318       {
319         return AAFrequency.extractProfile(
320                 aa.groupRef.consensusData[column],
321                 aa.groupRef.getIgnoreGapsConsensus());
322       }
323       // TODO extend annotation row to enable dynamic and static profile data to
324       // be stored
325       if (aa.groupRef == null && aa.sequenceRef == null)
326       {
327         return AAFrequency.extractProfile(hconsensus[column],
328                 av_ignoreGapsConsensus);
329       }
330     }
331     else
332     {
333       if (aa.autoCalculated && aa.label.startsWith("StrucConsensus"))
334       {
335         // TODO implement group structure consensus
336         /*
337          * if (aa.groupRef != null && aa.groupRef.consensusData != null &&
338          * aa.groupRef.isShowSequenceLogo()) { //TODO check what happens for
339          * group selections return StructureFrequency.extractProfile(
340          * aa.groupRef.consensusData[column], aa.groupRef
341          * .getIgnoreGapsConsensus()); }
342          */
343         // TODO extend annotation row to enable dynamic and static profile data
344         // to
345         // be stored
346         if (aa.groupRef == null && aa.sequenceRef == null
347                 && hStrucConsensus != null
348                 && hStrucConsensus.length > column)
349         {
350           return StructureFrequency.extractProfile(hStrucConsensus[column],
351                   av_ignoreGapsConsensus);
352         }
353       }
354     }
355     return null;
356   }
357
358   boolean rna = false;
359
360   /**
361    * Render the annotation rows associated with an alignment.
362    * 
363    * @param annotPanel
364    *          container frame
365    * @param av
366    *          data and view settings to render
367    * @param g
368    *          destination for graphics
369    * @param activeRow
370    *          row where a mouse event occured (or -1)
371    * @param startRes
372    *          first column that will be drawn
373    * @param endRes
374    *          last column that will be drawn
375    * @return true if the fadedImage was used for any alignment annotation rows
376    *         currently being calculated
377    */
378   public boolean drawComponent(AwtRenderPanelI annotPanel,
379           AlignViewportI av, Graphics g, int activeRow, int startRes,
380           int endRes)
381   {
382     long stime = System.currentTimeMillis();
383     boolean usedFaded = false;
384     // NOTES:
385     // AnnotationPanel needs to implement: ImageObserver, access to
386     // AlignViewport
387     updateFromAwtRenderPanel(annotPanel, av);
388     fm = g.getFontMetrics();
389     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
390     int temp = 0;
391     if (aa == null)
392     {
393       return false;
394     }
395     int x = 0, y = 0;
396     int column = 0;
397     char lastSS;
398     int lastSSX;
399     int iconOffset = 0;
400     boolean validRes = false;
401     boolean validEnd = false;
402     boolean labelAllCols = false;
403     boolean centreColLabels, centreColLabelsDef = av.isCentreColumnLabels();
404     boolean scaleColLabel = false;
405     AlignmentAnnotation consensusAnnot = av
406             .getAlignmentConsensusAnnotation(), structConsensusAnnot = av
407             .getAlignmentStrucConsensusAnnotation();
408     boolean renderHistogram = true, renderProfile = true, normaliseProfile = false, isRNA = rna;
409
410     BitSet graphGroupDrawn = new BitSet();
411     int charOffset = 0; // offset for a label
412     float fmWidth, fmScaling = 1f; // scaling for a label to fit it into a
413     // column.
414     Font ofont = g.getFont();
415     // \u03B2 \u03B1
416     // debug ints
417     int yfrom = 0, f_i = 0, yto = 0, f_to = 0;
418     boolean clipst = false, clipend = false;
419     for (int i = 0; i < aa.length; i++)
420     {
421       AlignmentAnnotation row = aa[i];
422       isRNA = row.isRNA();
423       {
424         // check if this is a consensus annotation row and set the display
425         // settings appropriately
426         // TODO: generalise this to have render styles for consensus/profile
427         // data
428         if (row.groupRef != null && row == row.groupRef.getConsensus())
429         {
430           renderHistogram = row.groupRef.isShowConsensusHistogram();
431           renderProfile = row.groupRef.isShowSequenceLogo();
432           normaliseProfile = row.groupRef.isNormaliseSequenceLogo();
433         }
434         else if (row == consensusAnnot || row == structConsensusAnnot)
435         {
436           renderHistogram = av_renderHistogram;
437           renderProfile = av_renderProfile;
438           normaliseProfile = av_normaliseProfile;
439         }
440         else
441         {
442           renderHistogram = true;
443           // don't need to set render/normaliseProfile since they are not
444           // currently used in any other annotation track renderer
445         }
446       }
447       Annotation[] row_annotations = row.annotations;
448       if (!row.visible)
449       {
450         continue;
451       }
452       centreColLabels = row.centreColLabels || centreColLabelsDef;
453       labelAllCols = row.showAllColLabels;
454       scaleColLabel = row.scaleColLabel;
455       lastSS = ' ';
456       lastSSX = 0;
457
458       if (!useClip
459               || ((y - charHeight) < visHeight && (y + row.height + charHeight * 2) >= sOffset))
460       {// if_in_visible_region
461         if (!clipst)
462         {
463           clipst = true;
464           yfrom = y;
465           f_i = i;
466         }
467         yto = y;
468         f_to = i;
469         if (row.graph > 0)
470         {
471           if (row.graphGroup > -1 && graphGroupDrawn.get(row.graphGroup))
472           {
473             continue;
474           }
475
476           // this is so that we draw the characters below the graph
477           y += row.height;
478
479           if (row.hasText)
480           {
481             iconOffset = charHeight - fm.getDescent();
482             y -= charHeight;
483           }
484         }
485         else if (row.hasText)
486         {
487           iconOffset = charHeight - fm.getDescent();
488
489         }
490         else
491         {
492           iconOffset = 0;
493         }
494
495         if (row.autoCalculated && av.isCalculationInProgress(row))
496         {
497           y += charHeight;
498           usedFaded = true;
499           g.drawImage(fadedImage, 0, y - row.height, imgWidth, y, 0, y
500                   - row.height, imgWidth, y, annotationPanel);
501           g.setColor(Color.black);
502           // g.drawString("Calculating "+aa[i].label+"....",20, y-row.height/2);
503
504           continue;
505         }
506
507         /*
508          * else if (annotationPanel.av.updatingConservation &&
509          * aa[i].label.equals("Conservation")) {
510          * 
511          * y += charHeight; g.drawImage(annotationPanel.fadedImage, 0, y -
512          * row.height, annotationPanel.imgWidth, y, 0, y - row.height,
513          * annotationPanel.imgWidth, y, annotationPanel);
514          * 
515          * g.setColor(Color.black); //
516          * g.drawString("Calculating Conservation.....",20, y-row.height/2);
517          * 
518          * continue; } else if (annotationPanel.av.updatingConservation &&
519          * aa[i].label.equals("Quality")) {
520          * 
521          * y += charHeight; g.drawImage(annotationPanel.fadedImage, 0, y -
522          * row.height, annotationPanel.imgWidth, y, 0, y - row.height,
523          * annotationPanel.imgWidth, y, annotationPanel);
524          * g.setColor(Color.black); // /
525          * g.drawString("Calculating Quality....",20, y-row.height/2);
526          * 
527          * continue; }
528          */
529         // first pass sets up state for drawing continuation from left-hand
530         // column
531         // of startRes
532         x = (startRes == 0) ? 0 : -1;
533         while (x < endRes - startRes)
534         {
535           if (hasHiddenColumns)
536           {
537             column = columnSelection.adjustForHiddenColumns(startRes + x);
538             if (column > row_annotations.length - 1)
539             {
540               break;
541             }
542           }
543           else
544           {
545             column = startRes + x;
546           }
547
548           if ((row_annotations == null)
549                   || (row_annotations.length <= column)
550                   || (row_annotations[column] == null))
551           {
552             validRes = false;
553           }
554           else
555           {
556             validRes = true;
557           }
558           if (x > -1)
559           {
560             if (activeRow == i)
561             {
562               g.setColor(Color.red);
563
564               if (columnSelection != null)
565               {
566                 for (int n = 0; n < columnSelection.size(); n++)
567                 {
568                   int v = columnSelection.columnAt(n);
569
570                   if (v == column)
571                   {
572                     g.fillRect(x * charWidth, y, charWidth, charHeight);
573                   }
574                 }
575               }
576             }
577             if (row.getInvalidStrucPos() > x)
578             {
579               g.setColor(Color.orange);
580               g.fillRect(x * charWidth, y, charWidth, charHeight);
581             }
582             else if (row.getInvalidStrucPos() == x)
583             {
584               g.setColor(Color.orange.darker());
585               g.fillRect(x * charWidth, y, charWidth, charHeight);
586             }
587             if (validCharWidth
588                     && validRes
589                     && row_annotations[column].displayCharacter != null
590                     && (row_annotations[column].displayCharacter.length() > 0))
591             {
592
593               if (centreColLabels || scaleColLabel)
594               {
595                 fmWidth = fm.charsWidth(
596                         row_annotations[column].displayCharacter
597                                 .toCharArray(), 0,
598                         row_annotations[column].displayCharacter.length());
599
600                 if (scaleColLabel)
601                 {
602                   // justify the label and scale to fit in column
603                   if (fmWidth > charWidth)
604                   {
605                     // scale only if the current font isn't already small enough
606                     fmScaling = charWidth;
607                     fmScaling /= fmWidth;
608                     g.setFont(ofont.deriveFont(AffineTransform
609                             .getScaleInstance(fmScaling, 1.0)));
610                     // and update the label's width to reflect the scaling.
611                     fmWidth = charWidth;
612                   }
613                 }
614               }
615               else
616               {
617                 fmWidth = fm
618                         .charWidth(row_annotations[column].displayCharacter
619                                 .charAt(0));
620               }
621               charOffset = (int) ((charWidth - fmWidth) / 2f);
622
623               if (row_annotations[column].colour == null)
624               {
625                 g.setColor(Color.black);
626               }
627               else
628               {
629                 g.setColor(row_annotations[column].colour);
630               }
631
632               if (column == 0 || row.graph > 0)
633               {
634                 g.drawString(row_annotations[column].displayCharacter,
635                         (x * charWidth) + charOffset, y + iconOffset);
636               }
637               else if (row_annotations[column - 1] == null
638                       || (labelAllCols
639                               || !row_annotations[column].displayCharacter
640                                       .equals(row_annotations[column - 1].displayCharacter) || (row_annotations[column].displayCharacter
641                               .length() < 2 && row_annotations[column].secondaryStructure == ' ')))
642               {
643                 g.drawString(row_annotations[column].displayCharacter, x
644                         * charWidth + charOffset, y + iconOffset);
645               }
646               g.setFont(ofont);
647             }
648           }
649           if (row.hasIcons)
650           {
651             char ss = validRes ? row_annotations[column].secondaryStructure
652                     : '-';
653
654             if (ss == '(')
655             {
656               // distinguish between forward/backward base-pairing
657               if (row_annotations[column].displayCharacter.indexOf(')') > -1)
658               {
659
660                 ss = ')';
661
662               }
663             }
664             if (ss == '[')
665             {
666               if ((row_annotations[column].displayCharacter.indexOf(']') > -1))
667               {
668                 ss = ']';
669
670               }
671             }
672             if (ss == '{')
673             {
674               // distinguish between forward/backward base-pairing
675               if (row_annotations[column].displayCharacter.indexOf('}') > -1)
676               {
677                 ss = '}';
678
679               }
680             }
681             if (ss == '<')
682             {
683               // distinguish between forward/backward base-pairing
684               if (row_annotations[column].displayCharacter.indexOf('<') > -1)
685               {
686                 ss = '>';
687
688               }
689             }
690             if (ss >= 65)
691             {
692               // distinguish between forward/backward base-pairing
693               if (row_annotations[column].displayCharacter.indexOf(ss + 32) > -1)
694               {
695
696                 ss = (char) (ss + 32);
697
698               }
699             }
700
701             if (!validRes || (ss != lastSS))
702             {
703
704               if (x > -1)
705               {
706
707                 int nb_annot = x - temp;
708                 // System.out.println("\t type :"+lastSS+"\t x :"+x+"\t nbre annot :"+nb_annot);
709                 switch (lastSS)
710                 {
711                 case '(': // Stem case for RNA secondary structure
712                 case ')': // and opposite direction
713                   drawStemAnnot(g, row_annotations, lastSSX, x, y,
714                           iconOffset, startRes, column, validRes, validEnd);
715                   temp = x;
716                   break;
717
718                 case 'H':
719                   if (!isRNA)
720                   {
721                     drawHelixAnnot(g, row_annotations, lastSSX, x, y,
722                             iconOffset, startRes, column, validRes,
723                             validEnd);
724                     break;
725                   }
726
727                 case 'E':
728                   if (!isRNA)
729                   {
730                     drawSheetAnnot(g, row_annotations, lastSSX, x, y,
731                             iconOffset, startRes, column, validRes,
732                             validEnd);
733                     break;
734                   }
735
736                 case '{':
737                 case '}':
738                 case '[':
739                 case ']':
740                 case '>':
741                 case '<':
742                 case 'A':
743                 case 'a':
744                 case 'B':
745                 case 'b':
746                 case 'C':
747                 case 'c':
748                 case 'D':
749                 case 'd':
750                 case 'e':
751                 case 'F':
752                 case 'f':
753                 case 'G':
754                 case 'g':
755                 case 'h':
756                 case 'I':
757                 case 'i':
758                 case 'J':
759                 case 'j':
760                 case 'K':
761                 case 'k':
762                 case 'L':
763                 case 'l':
764                 case 'M':
765                 case 'm':
766                 case 'N':
767                 case 'n':
768                 case 'O':
769                 case 'o':
770                 case 'P':
771                 case 'p':
772                 case 'Q':
773                 case 'q':
774                 case 'R':
775                 case 'r':
776                 case 'S':
777                 case 's':
778                 case 'T':
779                 case 't':
780                 case 'U':
781                 case 'u':
782                 case 'V':
783                 case 'v':
784                 case 'W':
785                 case 'w':
786                 case 'X':
787                 case 'x':
788                 case 'Y':
789                 case 'y':
790                 case 'Z':
791                 case 'z':
792
793                   Color nonCanColor = getNotCanonicalColor(lastSS);
794                   drawNotCanonicalAnnot(g, nonCanColor, row_annotations,
795                           lastSSX, x, y, iconOffset, startRes, column,
796                           validRes, validEnd);
797                   temp = x;
798                   break;
799                 default:
800                   g.setColor(Color.gray);
801                   g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth)
802                           - lastSSX, 2);
803                   temp = x;
804                   break;
805                 }
806               }
807               if (validRes)
808               {
809                 lastSS = ss;
810               }
811               else
812               {
813                 lastSS = ' ';
814               }
815               if (x > -1)
816               {
817                 lastSSX = (x * charWidth);
818               }
819             }
820           }
821           column++;
822           x++;
823         }
824         if (column >= row_annotations.length)
825         {
826           column = row_annotations.length - 1;
827           validEnd = false;
828         }
829         else
830         {
831           validEnd = true;
832         }
833         if ((row_annotations == null) || (row_annotations.length <= column)
834                 || (row_annotations[column] == null))
835         {
836           validRes = false;
837         }
838         else
839         {
840           validRes = true;
841         }
842
843         // x ++;
844
845         if (row.hasIcons)
846         {
847           switch (lastSS)
848           {
849
850           case 'H':
851             if (!isRNA)
852             {
853               drawHelixAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
854                       startRes, column, validRes, validEnd);
855               break;
856             }
857
858           case 'E':
859             if (!isRNA)
860             {
861               drawSheetAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
862                       startRes, column, validRes, validEnd);
863               break;
864             }
865
866           case '(':
867           case ')': // Stem case for RNA secondary structure
868
869             drawStemAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
870                     startRes, column, validRes, validEnd);
871
872             break;
873           case '{':
874           case '}':
875           case '[':
876           case ']':
877           case '>':
878           case '<':
879           case 'A':
880           case 'a':
881           case 'B':
882           case 'b':
883           case 'C':
884           case 'c':
885           case 'D':
886           case 'd':
887           case 'e':
888           case 'F':
889           case 'f':
890           case 'G':
891           case 'g':
892           case 'h':
893           case 'I':
894           case 'i':
895           case 'J':
896           case 'j':
897           case 'K':
898           case 'k':
899           case 'L':
900           case 'l':
901           case 'M':
902           case 'm':
903           case 'N':
904           case 'n':
905           case 'O':
906           case 'o':
907           case 'P':
908           case 'p':
909           case 'Q':
910           case 'q':
911           case 'R':
912           case 'r':
913           case 'T':
914           case 't':
915           case 'U':
916           case 'u':
917           case 'V':
918           case 'v':
919           case 'W':
920           case 'w':
921           case 'X':
922           case 'x':
923           case 'Y':
924           case 'y':
925           case 'Z':
926           case 'z':
927             // System.out.println(lastSS);
928             Color nonCanColor = getNotCanonicalColor(lastSS);
929             drawNotCanonicalAnnot(g, nonCanColor, row_annotations, lastSSX,
930                     x, y, iconOffset, startRes, column, validRes, validEnd);
931             break;
932           default:
933             drawGlyphLine(g, row_annotations, lastSSX, x, y, iconOffset,
934                     startRes, column, validRes, validEnd);
935             break;
936           }
937         }
938
939         if (row.graph > 0 && row.graphHeight > 0)
940         {
941           if (row.graph == AlignmentAnnotation.LINE_GRAPH)
942           {
943             if (row.graphGroup > -1 && !graphGroupDrawn.get(row.graphGroup))
944             {
945               // TODO: JAL-1291 revise rendering model so the graphGroup map is
946               // computed efficiently for all visible labels
947               float groupmax = -999999, groupmin = 9999999;
948               for (int gg = 0; gg < aa.length; gg++)
949               {
950                 if (aa[gg].graphGroup != row.graphGroup)
951                 {
952                   continue;
953                 }
954
955                 if (aa[gg] != row)
956                 {
957                   aa[gg].visible = false;
958                 }
959                 if (aa[gg].graphMax > groupmax)
960                 {
961                   groupmax = aa[gg].graphMax;
962                 }
963                 if (aa[gg].graphMin < groupmin)
964                 {
965                   groupmin = aa[gg].graphMin;
966                 }
967               }
968
969               for (int gg = 0; gg < aa.length; gg++)
970               {
971                 if (aa[gg].graphGroup == row.graphGroup)
972                 {
973                   drawLineGraph(g, aa[gg], aa[gg].annotations, startRes,
974                           endRes, y, groupmin, groupmax, row.graphHeight);
975                 }
976               }
977
978               graphGroupDrawn.set(row.graphGroup);
979             }
980             else
981             {
982               drawLineGraph(g, row, row_annotations, startRes, endRes, y,
983                       row.graphMin, row.graphMax, row.graphHeight);
984             }
985           }
986           else if (row.graph == AlignmentAnnotation.BAR_GRAPH)
987           {
988             drawBarGraph(g, row, row_annotations, startRes, endRes,
989                     row.graphMin, row.graphMax, y, renderHistogram,
990                     renderProfile, normaliseProfile);
991           }
992         }
993       }
994       else
995       {
996         if (clipst && !clipend)
997         {
998           clipend = true;
999         }
1000       }// end if_in_visible_region
1001       if (row.graph > 0 && row.hasText)
1002       {
1003         y += charHeight;
1004       }
1005
1006       if (row.graph == 0)
1007       {
1008         y += aa[i].height;
1009       }
1010     }
1011     if (debugRedraw)
1012     {
1013       if (canClip)
1014       {
1015         if (clipst)
1016         {
1017           System.err.println("Start clip at : " + yfrom + " (index " + f_i
1018                   + ")");
1019         }
1020         if (clipend)
1021         {
1022           System.err.println("End clip at : " + yto + " (index " + f_to
1023                   + ")");
1024         }
1025       }
1026       ;
1027       System.err.println("Annotation Rendering time:"
1028               + (System.currentTimeMillis() - stime));
1029     }
1030     ;
1031
1032     return !usedFaded;
1033   }
1034
1035   public static final Color GLYPHLINE_COLOR = Color.gray;
1036
1037   public static final Color SHEET_COLOUR = Color.green;
1038
1039   public static final Color HELIX_COLOUR = Color.red;
1040
1041   public static final Color STEM_COLOUR = Color.blue;
1042
1043   private Color sdNOTCANONICAL_COLOUR;
1044
1045   public void drawGlyphLine(Graphics g, Annotation[] row, int lastSSX,
1046           int x, int y, int iconOffset, int startRes, int column,
1047           boolean validRes, boolean validEnd)
1048   {
1049     g.setColor(GLYPHLINE_COLOR);
1050     g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth) - lastSSX, 2);
1051   }
1052
1053   public void drawSheetAnnot(Graphics g, Annotation[] row,
1054
1055   int lastSSX, int x, int y, int iconOffset, int startRes, int column,
1056           boolean validRes, boolean validEnd)
1057   {
1058     g.setColor(SHEET_COLOUR);
1059
1060     if (!validEnd || !validRes || row == null || row[column] == null
1061             || row[column].secondaryStructure != 'E')
1062     {
1063       g.fillRect(lastSSX, y + 4 + iconOffset,
1064               (x * charWidth) - lastSSX - 4, 7);
1065       g.fillPolygon(new int[]
1066       { (x * charWidth) - 4, (x * charWidth) - 4, (x * charWidth) },
1067               new int[]
1068               { y + iconOffset, y + 14 + iconOffset, y + 7 + iconOffset },
1069               3);
1070     }
1071     else
1072     {
1073       g.fillRect(lastSSX, y + 4 + iconOffset,
1074               (x + 1) * charWidth - lastSSX, 7);
1075     }
1076
1077   }
1078
1079   public void drawHelixAnnot(Graphics g, Annotation[] row, int lastSSX,
1080           int x, int y, int iconOffset, int startRes, int column,
1081           boolean validRes, boolean validEnd)
1082   {
1083     g.setColor(HELIX_COLOUR);
1084
1085     int sCol = (lastSSX / charWidth) + startRes;
1086     int x1 = lastSSX;
1087     int x2 = (x * charWidth);
1088
1089     if (MAC)
1090     {
1091       int ofs = charWidth / 2;
1092       // Off by 1 offset when drawing rects and ovals
1093       // to offscreen image on the MAC
1094       g.fillRoundRect(lastSSX, y + 4 + iconOffset, x2 - x1, 8, 8, 8);
1095       if (sCol == 0 || row[sCol - 1] == null
1096               || row[sCol - 1].secondaryStructure != 'H')
1097       {
1098       }
1099       else
1100       {
1101         // g.setColor(Color.orange);
1102         g.fillRoundRect(lastSSX, y + 4 + iconOffset, x2 - x1 - ofs + 1, 8,
1103                 0, 0);
1104       }
1105       if (!validRes || row[column] == null
1106               || row[column].secondaryStructure != 'H')
1107       {
1108
1109       }
1110       else
1111       {
1112         // g.setColor(Color.magenta);
1113         g.fillRoundRect(lastSSX + ofs, y + 4 + iconOffset, x2 - x1 - ofs
1114                 + 1, 8, 0, 0);
1115
1116       }
1117
1118       return;
1119     }
1120
1121     if (sCol == 0 || row[sCol - 1] == null
1122             || row[sCol - 1].secondaryStructure != 'H')
1123     {
1124       g.fillArc(lastSSX, y + 4 + iconOffset, charWidth, 8, 90, 180);
1125       x1 += charWidth / 2;
1126     }
1127
1128     if (!validRes || row[column] == null
1129             || row[column].secondaryStructure != 'H')
1130     {
1131       g.fillArc((x * charWidth) - charWidth, y + 4 + iconOffset, charWidth,
1132               8, 270, 180);
1133       x2 -= charWidth / 2;
1134     }
1135
1136     g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 8);
1137   }
1138
1139   public void drawLineGraph(Graphics g, AlignmentAnnotation _aa,
1140           Annotation[] aa_annotations, int sRes, int eRes, int y,
1141           float min, float max, int graphHeight)
1142   {
1143     if (sRes > aa_annotations.length)
1144     {
1145       return;
1146     }
1147
1148     int x = 0;
1149
1150     // Adjustment for fastpaint to left
1151     if (eRes < endRes)
1152     {
1153       eRes++;
1154     }
1155
1156     eRes = Math.min(eRes, aa_annotations.length);
1157
1158     if (sRes == 0)
1159     {
1160       x++;
1161     }
1162
1163     int y1 = y, y2 = y;
1164     float range = max - min;
1165
1166     // //Draw origin
1167     if (min < 0)
1168     {
1169       y2 = y - (int) ((0 - min / range) * graphHeight);
1170     }
1171
1172     g.setColor(Color.gray);
1173     g.drawLine(x - charWidth, y2, (eRes - sRes + 1) * charWidth, y2);
1174
1175     eRes = Math.min(eRes, aa_annotations.length);
1176
1177     int column;
1178     int aaMax = aa_annotations.length - 1;
1179
1180     while (x < eRes - sRes)
1181     {
1182       column = sRes + x;
1183       if (hasHiddenColumns)
1184       {
1185         column = columnSelection.adjustForHiddenColumns(column);
1186       }
1187
1188       if (column > aaMax)
1189       {
1190         break;
1191       }
1192
1193       if (aa_annotations[column] == null
1194               || aa_annotations[column - 1] == null)
1195       {
1196         x++;
1197         continue;
1198       }
1199
1200       if (aa_annotations[column].colour == null)
1201       {
1202         g.setColor(Color.black);
1203       }
1204       else
1205       {
1206         g.setColor(aa_annotations[column].colour);
1207       }
1208
1209       y1 = y
1210               - (int) (((aa_annotations[column - 1].value - min) / range) * graphHeight);
1211       y2 = y
1212               - (int) (((aa_annotations[column].value - min) / range) * graphHeight);
1213
1214       g.drawLine(x * charWidth - charWidth / 2, y1, x * charWidth
1215               + charWidth / 2, y2);
1216       x++;
1217     }
1218
1219     if (_aa.threshold != null)
1220     {
1221       g.setColor(_aa.threshold.colour);
1222       Graphics2D g2 = (Graphics2D) g;
1223       g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
1224               BasicStroke.JOIN_ROUND, 3f, new float[]
1225               { 5f, 3f }, 0f));
1226
1227       y2 = (int) (y - ((_aa.threshold.value - min) / range) * graphHeight);
1228       g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
1229       g2.setStroke(new BasicStroke());
1230     }
1231   }
1232
1233   public void drawBarGraph(Graphics g, AlignmentAnnotation _aa,
1234           Annotation[] aa_annotations, int sRes, int eRes, float min,
1235           float max, int y, boolean renderHistogram, boolean renderProfile,
1236           boolean normaliseProfile)
1237   {
1238     if (sRes > aa_annotations.length)
1239     {
1240       return;
1241     }
1242     Font ofont = g.getFont();
1243     eRes = Math.min(eRes, aa_annotations.length);
1244
1245     int x = 0, y1 = y, y2 = y;
1246
1247     float range = max - min;
1248
1249     if (min < 0)
1250     {
1251       y2 = y - (int) ((0 - min / (range)) * _aa.graphHeight);
1252     }
1253
1254     g.setColor(Color.gray);
1255
1256     g.drawLine(x, y2, (eRes - sRes) * charWidth, y2);
1257
1258     int column;
1259     int aaMax = aa_annotations.length - 1;
1260     while (x < eRes - sRes)
1261     {
1262       column = sRes + x;
1263       if (hasHiddenColumns)
1264       {
1265         column = columnSelection.adjustForHiddenColumns(column);
1266       }
1267
1268       if (column > aaMax)
1269       {
1270         break;
1271       }
1272
1273       if (aa_annotations[column] == null)
1274       {
1275         x++;
1276         continue;
1277       }
1278       if (aa_annotations[column].colour == null)
1279       {
1280         g.setColor(Color.black);
1281       }
1282       else
1283       {
1284         g.setColor(aa_annotations[column].colour);
1285       }
1286
1287       y1 = y
1288               - (int) (((aa_annotations[column].value - min) / (range)) * _aa.graphHeight);
1289
1290       if (renderHistogram)
1291       {
1292         if (y1 - y2 > 0)
1293         {
1294           g.fillRect(x * charWidth, y2, charWidth, y1 - y2);
1295         }
1296         else
1297         {
1298           g.fillRect(x * charWidth, y1, charWidth, y2 - y1);
1299         }
1300       }
1301       // draw profile if available
1302       if (renderProfile)
1303       {
1304
1305         int profl[] = getProfileFor(_aa, column);
1306         // just try to draw the logo if profl is not null
1307         if (profl != null && profl[1] != 0)
1308         {
1309           float ht = normaliseProfile ? y - _aa.graphHeight : y1;
1310           double htn = normaliseProfile ? _aa.graphHeight : (y2 - y1);// aa.graphHeight;
1311           double hght;
1312           float wdth;
1313           double ht2 = 0;
1314           char[] dc;
1315
1316           /**
1317            * profl.length == 74 indicates that the profile of a secondary
1318            * structure conservation row was accesed. Therefore dc gets length 2,
1319            * to have space for a basepair instead of just a single nucleotide
1320            */
1321           if (profl.length == 74)
1322           {
1323             dc = new char[2];
1324           }
1325           else
1326           {
1327             dc = new char[1];
1328           }
1329           LineMetrics lm = g.getFontMetrics(ofont).getLineMetrics("Q", g);
1330           double scale = 1f / (normaliseProfile ? profl[1] : 100f);
1331           float ofontHeight = 1f / lm.getAscent();// magnify to fill box
1332           double scl = 0.0;
1333           for (int c = 2; c < profl[0];)
1334           {
1335             dc[0] = (char) profl[c++];
1336
1337             if (_aa.label.startsWith("StrucConsensus"))
1338             {
1339               dc[1] = (char) profl[c++];
1340             }
1341
1342             wdth = charWidth;
1343             wdth /= fm.charsWidth(dc, 0, dc.length);
1344
1345             ht += scl;
1346             {
1347               scl = htn * scale * profl[c++];
1348               lm = ofont.getLineMetrics(dc, 0, 1, g.getFontMetrics()
1349                       .getFontRenderContext());
1350               g.setFont(ofont.deriveFont(AffineTransform.getScaleInstance(
1351                       wdth, scl / lm.getAscent())));
1352               lm = g.getFontMetrics().getLineMetrics(dc, 0, 1, g);
1353
1354               // Debug - render boxes around characters
1355               // g.setColor(Color.red);
1356               // g.drawRect(x*av.charWidth, (int)ht, av.charWidth,
1357               // (int)(scl));
1358               // g.setColor(profcolour.findColour(dc[0]).darker());
1359               g.setColor(profcolour.findColour(dc[0], column, null));
1360
1361               hght = (ht + (scl - lm.getDescent() - lm.getBaselineOffsets()[lm
1362                       .getBaselineIndex()]));
1363
1364               g.drawChars(dc, 0, dc.length, x * charWidth, (int) hght);
1365             }
1366           }
1367           g.setFont(ofont);
1368         }
1369       }
1370       x++;
1371     }
1372     if (_aa.threshold != null)
1373     {
1374       g.setColor(_aa.threshold.colour);
1375       Graphics2D g2 = (Graphics2D) g;
1376       g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
1377               BasicStroke.JOIN_ROUND, 3f, new float[]
1378               { 5f, 3f }, 0f));
1379
1380       y2 = (int) (y - ((_aa.threshold.value - min) / range)
1381               * _aa.graphHeight);
1382       g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
1383       g2.setStroke(new BasicStroke());
1384     }
1385   }
1386
1387   // used by overview window
1388   public void drawGraph(Graphics g, AlignmentAnnotation _aa,
1389           Annotation[] aa_annotations, int width, int y, int sRes, int eRes)
1390   {
1391     eRes = Math.min(eRes, aa_annotations.length);
1392     g.setColor(Color.white);
1393     g.fillRect(0, 0, width, y);
1394     g.setColor(new Color(0, 0, 180));
1395
1396     int x = 0, height;
1397
1398     for (int j = sRes; j < eRes; j++)
1399     {
1400       if (aa_annotations[j] != null)
1401       {
1402         if (aa_annotations[j].colour == null)
1403         {
1404           g.setColor(Color.black);
1405         }
1406         else
1407         {
1408           g.setColor(aa_annotations[j].colour);
1409         }
1410
1411         height = (int) ((aa_annotations[j].value / _aa.graphMax) * y);
1412         if (height > y)
1413         {
1414           height = y;
1415         }
1416
1417         g.fillRect(x, y - height, charWidth, height);
1418       }
1419       x += charWidth;
1420     }
1421   }
1422
1423   Color getNotCanonicalColor(char lastss)
1424   {
1425     switch (lastss)
1426     {
1427     case '{':
1428     case '}':
1429       return new Color(255, 125, 5);
1430
1431     case '[':
1432     case ']':
1433       return new Color(245, 115, 10);
1434
1435     case '>':
1436     case '<':
1437       return new Color(235, 135, 15);
1438
1439     case 'A':
1440     case 'a':
1441       return new Color(225, 105, 20);
1442
1443     case 'B':
1444     case 'b':
1445       return new Color(215, 145, 30);
1446
1447     case 'C':
1448     case 'c':
1449       return new Color(205, 95, 35);
1450
1451     case 'D':
1452     case 'd':
1453       return new Color(195, 155, 45);
1454
1455     case 'E':
1456     case 'e':
1457       return new Color(185, 85, 55);
1458
1459     case 'F':
1460     case 'f':
1461       return new Color(175, 165, 65);
1462
1463     case 'G':
1464     case 'g':
1465       return new Color(170, 75, 75);
1466
1467     case 'H':
1468     case 'h':
1469       return new Color(160, 175, 85);
1470
1471     case 'I':
1472     case 'i':
1473       return new Color(150, 65, 95);
1474
1475     case 'J':
1476     case 'j':
1477       return new Color(140, 185, 105);
1478
1479     case 'K':
1480     case 'k':
1481       return new Color(130, 55, 110);
1482
1483     case 'L':
1484     case 'l':
1485       return new Color(120, 195, 120);
1486
1487     case 'M':
1488     case 'm':
1489       return new Color(110, 45, 130);
1490
1491     case 'N':
1492     case 'n':
1493       return new Color(100, 205, 140);
1494
1495     case 'O':
1496     case 'o':
1497       return new Color(90, 35, 150);
1498
1499     case 'P':
1500     case 'p':
1501       return new Color(85, 215, 160);
1502
1503     case 'Q':
1504     case 'q':
1505       return new Color(75, 25, 170);
1506
1507     case 'R':
1508     case 'r':
1509       return new Color(65, 225, 180);
1510
1511     case 'S':
1512     case 's':
1513       return new Color(55, 15, 185);
1514
1515     case 'T':
1516     case 't':
1517       return new Color(45, 235, 195);
1518
1519     case 'U':
1520     case 'u':
1521       return new Color(35, 5, 205);
1522
1523     case 'V':
1524     case 'v':
1525       return new Color(25, 245, 215);
1526
1527     case 'W':
1528     case 'w':
1529       return new Color(15, 0, 225);
1530
1531     case 'X':
1532     case 'x':
1533       return new Color(10, 255, 235);
1534
1535     case 'Y':
1536     case 'y':
1537       return new Color(5, 150, 245);
1538
1539     case 'Z':
1540     case 'z':
1541       return new Color(0, 80, 255);
1542
1543     default:
1544       System.out.println("This is not a interaction : " + lastss);
1545       return null;
1546
1547     }
1548   }
1549 }