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