5348aaa0d75a34ba8bc8e937210583445576105e
[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     boolean rna = av.getAlignment().isNucleotide();
301     columnSelection = av.getColumnSelection();
302     hconsensus = av.getSequenceConsensusHash();// hconsensus;
303     hStrucConsensus = av.getRnaStructureConsensusHash(); // hStrucConsensus;
304     av_ignoreGapsConsensus = av.getIgnoreGapsConsensus();
305   }
306
307   public int[] getProfileFor(AlignmentAnnotation aa, int column)
308   {
309     // TODO : consider refactoring the global alignment calculation
310     // properties/rendering attributes as a global 'alignment group' which holds
311     // all vis settings for the alignment as a whole rather than a subset
312     //
313     if (aa.autoCalculated && aa.label.startsWith("Consensus"))
314     {
315       if (aa.groupRef != null && aa.groupRef.consensusData != null
316               && aa.groupRef.isShowSequenceLogo())
317       {
318         return AAFrequency.extractProfile(
319                 aa.groupRef.consensusData[column],
320                 aa.groupRef.getIgnoreGapsConsensus());
321       }
322       // TODO extend annotation row to enable dynamic and static profile data to
323       // be stored
324       if (aa.groupRef == null && aa.sequenceRef == null)
325       {
326         return AAFrequency.extractProfile(hconsensus[column],
327                 av_ignoreGapsConsensus);
328       }
329     }
330     else
331     {
332       if (aa.autoCalculated && aa.label.startsWith("StrucConsensus"))
333       {
334         // TODO implement group structure consensus
335         /*
336          * if (aa.groupRef != null && aa.groupRef.consensusData != null &&
337          * aa.groupRef.isShowSequenceLogo()) { //TODO check what happens for
338          * group selections return StructureFrequency.extractProfile(
339          * aa.groupRef.consensusData[column], aa.groupRef
340          * .getIgnoreGapsConsensus()); }
341          */
342         // TODO extend annotation row to enable dynamic and static profile data
343         // to
344         // be stored
345         if (aa.groupRef == null && aa.sequenceRef == null
346                 && hStrucConsensus != null
347                 && hStrucConsensus.length > column)
348         {
349           return StructureFrequency.extractProfile(hStrucConsensus[column],
350                   av_ignoreGapsConsensus);
351         }
352       }
353     }
354     return null;
355   }
356
357   boolean rna = false;
358
359   /**
360    * Render the annotation rows associated with an alignment.
361    * 
362    * @param annotPanel
363    *          container frame
364    * @param av
365    *          data and view settings to render
366    * @param g
367    *          destination for graphics
368    * @param activeRow
369    *          row where a mouse event occured (or -1)
370    * @param startRes
371    *          first column that will be drawn
372    * @param endRes
373    *          last column that will be drawn
374    * @return true if the fadedImage was used for any alignment annotation rows
375    *         currently being calculated
376    */
377   public boolean drawComponent(AwtRenderPanelI annotPanel,
378           AlignViewportI av, Graphics g, int activeRow, int startRes,
379           int endRes)
380   {
381     long stime = System.currentTimeMillis();
382     boolean usedFaded = false;
383     // NOTES:
384     // AnnotationPanel needs to implement: ImageObserver, access to
385     // AlignViewport
386     updateFromAwtRenderPanel(annotPanel, av);
387     fm = g.getFontMetrics();
388     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
389     int temp = 0;
390     if (aa == null)
391     {
392       return false;
393     }
394     int x = 0, y = 0;
395     int column = 0;
396     char lastSS;
397     int lastSSX;
398     int iconOffset = 0;
399     boolean validRes = false;
400     boolean validEnd = false;
401     boolean labelAllCols = false;
402     boolean centreColLabels, centreColLabelsDef = av
403             .getCentreColumnLabels();
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.isValidStruc())
578             {
579               g.setColor(Color.orange);
580               g.fillRect((int) row.getInvalidStrucPos() * charWidth, y,
581                       charWidth, charHeight);
582             }
583             if (validCharWidth
584                     && validRes
585                     && row_annotations[column].displayCharacter != null
586                     && (row_annotations[column].displayCharacter.length() > 0))
587             {
588
589               if (centreColLabels || scaleColLabel)
590               {
591                 fmWidth = fm.charsWidth(
592                         row_annotations[column].displayCharacter
593                                 .toCharArray(), 0,
594                         row_annotations[column].displayCharacter.length());
595
596                 if (scaleColLabel)
597                 {
598                   // justify the label and scale to fit in column
599                   if (fmWidth > charWidth)
600                   {
601                     // scale only if the current font isn't already small enough
602                     fmScaling = charWidth;
603                     fmScaling /= fmWidth;
604                     g.setFont(ofont.deriveFont(AffineTransform
605                             .getScaleInstance(fmScaling, 1.0)));
606                     // and update the label's width to reflect the scaling.
607                     fmWidth = charWidth;
608                   }
609                 }
610               }
611               else
612               {
613                 fmWidth = fm
614                         .charWidth(row_annotations[column].displayCharacter
615                                 .charAt(0));
616               }
617               charOffset = (int) ((charWidth - fmWidth) / 2f);
618
619               if (row_annotations[column].colour == null)
620               {
621                 g.setColor(Color.black);
622               }
623               else
624               {
625                 g.setColor(row_annotations[column].colour);
626               }
627
628               if (column == 0 || row.graph > 0)
629               {
630                 g.drawString(row_annotations[column].displayCharacter,
631                         (x * charWidth) + charOffset, y + iconOffset);
632               }
633               else if (row_annotations[column - 1] == null
634                       || (labelAllCols
635                               || !row_annotations[column].displayCharacter
636                                       .equals(row_annotations[column - 1].displayCharacter) || (row_annotations[column].displayCharacter
637                               .length() < 2 && row_annotations[column].secondaryStructure == ' ')))
638               {
639                 g.drawString(row_annotations[column].displayCharacter, x
640                         * charWidth + charOffset, y + iconOffset);
641               }
642               g.setFont(ofont);
643             }
644           }
645           if (row.hasIcons)
646           {
647             char ss = validRes ? row_annotations[column].secondaryStructure
648                     : '-';
649
650             if (ss == '(')
651             {
652               // distinguish between forward/backward base-pairing
653               if (row_annotations[column].displayCharacter.indexOf(')') > -1)
654               {
655
656                 ss = ')';
657
658               }
659             }
660             if (ss == '[')
661             {
662               if ((row_annotations[column].displayCharacter.indexOf(']') > -1))
663               {
664                 ss = ']';
665
666               }
667             }
668             if (ss == '{')
669             {
670               // distinguish between forward/backward base-pairing
671               if (row_annotations[column].displayCharacter.indexOf('}') > -1)
672               {
673                 ss = '}';
674
675               }
676             }
677             if (ss == '<')
678             {
679               // distinguish between forward/backward base-pairing
680               if (row_annotations[column].displayCharacter.indexOf('<') > -1)
681               {
682                 ss = '>';
683
684               }
685             }
686             if (ss >= 65)
687             {
688               // distinguish between forward/backward base-pairing
689               if (row_annotations[column].displayCharacter.indexOf(ss + 32) > -1)
690               {
691
692                 ss = (char) (ss + 32);
693
694               }
695             }
696
697             if (!validRes || (ss != lastSS))
698             {
699
700               if (x > -1)
701               {
702
703                 int nb_annot = x - temp;
704                 // System.out.println("\t type :"+lastSS+"\t x :"+x+"\t nbre annot :"+nb_annot);
705                 switch (lastSS)
706                 {
707                 case '(': // Stem case for RNA secondary structure
708                 case ')': // and opposite direction
709                   drawStemAnnot(g, row_annotations, lastSSX, x, y,
710                           iconOffset, startRes, column, validRes, validEnd);
711                   temp = x;
712                   break;
713
714                 case 'H':
715                   if (!isRNA)
716                   {
717                     drawHelixAnnot(g, row_annotations, lastSSX, x, y,
718                             iconOffset, startRes, column, validRes,
719                             validEnd);
720                     break;
721                   }
722
723                 case 'E':
724                   if (!isRNA)
725                   {
726                     drawSheetAnnot(g, row_annotations, lastSSX, x, y,
727                             iconOffset, startRes, column, validRes,
728                             validEnd);
729                     break;
730                   }
731
732                 case '{':
733                 case '}':
734                 case '[':
735                 case ']':
736                 case '>':
737                 case '<':
738                 case 'A':
739                 case 'a':
740                 case 'B':
741                 case 'b':
742                 case 'C':
743                 case 'c':
744                 case 'D':
745                 case 'd':
746                 case 'e':
747                 case 'F':
748                 case 'f':
749                 case 'G':
750                 case 'g':
751                 case 'h':
752                 case 'I':
753                 case 'i':
754                 case 'J':
755                 case 'j':
756                 case 'K':
757                 case 'k':
758                 case 'L':
759                 case 'l':
760                 case 'M':
761                 case 'm':
762                 case 'N':
763                 case 'n':
764                 case 'O':
765                 case 'o':
766                 case 'P':
767                 case 'p':
768                 case 'Q':
769                 case 'q':
770                 case 'R':
771                 case 'r':
772                 case 'S':
773                 case 's':
774                 case 'T':
775                 case 't':
776                 case 'U':
777                 case 'u':
778                 case 'V':
779                 case 'v':
780                 case 'W':
781                 case 'w':
782                 case 'X':
783                 case 'x':
784                 case 'Y':
785                 case 'y':
786                 case 'Z':
787                 case 'z':
788
789                   Color nonCanColor = getNotCanonicalColor(lastSS);
790                   drawNotCanonicalAnnot(g, nonCanColor, row_annotations,
791                           lastSSX, x, y, iconOffset, startRes, column,
792                           validRes, validEnd);
793                   temp = x;
794                   break;
795                 default:
796                   g.setColor(Color.gray);
797                   g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth)
798                           - lastSSX, 2);
799                   temp = x;
800                   break;
801                 }
802               }
803               if (validRes)
804               {
805                 lastSS = ss;
806               }
807               else
808               {
809                 lastSS = ' ';
810               }
811               if (x > -1)
812               {
813                 lastSSX = (x * charWidth);
814               }
815             }
816           }
817           column++;
818           x++;
819         }
820         if (column >= row_annotations.length)
821         {
822           column = row_annotations.length - 1;
823           validEnd = false;
824         }
825         else
826         {
827           validEnd = true;
828         }
829         if ((row_annotations == null) || (row_annotations.length <= column)
830                 || (row_annotations[column] == null))
831         {
832           validRes = false;
833         }
834         else
835         {
836           validRes = true;
837         }
838
839         // x ++;
840
841         if (row.hasIcons)
842         {
843           switch (lastSS)
844           {
845
846           case 'H':
847             if (!isRNA)
848             {
849               drawHelixAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
850                       startRes, column, validRes, validEnd);
851               break;
852             }
853
854           case 'E':
855             if (!isRNA)
856             {
857               drawSheetAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
858                       startRes, column, validRes, validEnd);
859               break;
860             }
861
862           case '(':
863           case ')': // Stem case for RNA secondary structure
864
865             drawStemAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
866                     startRes, column, validRes, validEnd);
867
868             break;
869           case '{':
870           case '}':
871           case '[':
872           case ']':
873           case '>':
874           case '<':
875           case 'A':
876           case 'a':
877           case 'B':
878           case 'b':
879           case 'C':
880           case 'c':
881           case 'D':
882           case 'd':
883           case 'e':
884           case 'F':
885           case 'f':
886           case 'G':
887           case 'g':
888           case 'h':
889           case 'I':
890           case 'i':
891           case 'J':
892           case 'j':
893           case 'K':
894           case 'k':
895           case 'L':
896           case 'l':
897           case 'M':
898           case 'm':
899           case 'N':
900           case 'n':
901           case 'O':
902           case 'o':
903           case 'P':
904           case 'p':
905           case 'Q':
906           case 'q':
907           case 'R':
908           case 'r':
909           case 'T':
910           case 't':
911           case 'U':
912           case 'u':
913           case 'V':
914           case 'v':
915           case 'W':
916           case 'w':
917           case 'X':
918           case 'x':
919           case 'Y':
920           case 'y':
921           case 'Z':
922           case 'z':
923             // System.out.println(lastSS);
924             Color nonCanColor = getNotCanonicalColor(lastSS);
925             drawNotCanonicalAnnot(g, nonCanColor, row_annotations, lastSSX,
926                     x, y, iconOffset, startRes, column, validRes, validEnd);
927             break;
928           default:
929             drawGlyphLine(g, row_annotations, lastSSX, x, y, iconOffset,
930                     startRes, column, validRes, validEnd);
931             break;
932           }
933         }
934
935         if (row.graph > 0 && row.graphHeight > 0)
936         {
937           if (row.graph == AlignmentAnnotation.LINE_GRAPH)
938           {
939             if (row.graphGroup > -1 && !graphGroupDrawn.get(row.graphGroup))
940             {
941               // TODO: JAL-1291 revise rendering model so the graphGroup map is
942               // computed efficiently for all visible labels
943               float groupmax = -999999, groupmin = 9999999;
944               for (int gg = 0; gg < aa.length; gg++)
945               {
946                 if (aa[gg].graphGroup != row.graphGroup)
947                 {
948                   continue;
949                 }
950
951                 if (aa[gg] != row)
952                 {
953                   aa[gg].visible = false;
954                 }
955                 if (aa[gg].graphMax > groupmax)
956                 {
957                   groupmax = aa[gg].graphMax;
958                 }
959                 if (aa[gg].graphMin < groupmin)
960                 {
961                   groupmin = aa[gg].graphMin;
962                 }
963               }
964
965               for (int gg = 0; gg < aa.length; gg++)
966               {
967                 if (aa[gg].graphGroup == row.graphGroup)
968                 {
969                   drawLineGraph(g, aa[gg], aa[gg].annotations, startRes,
970                           endRes, y, groupmin, groupmax, row.graphHeight);
971                 }
972               }
973
974               graphGroupDrawn.set(row.graphGroup);
975             }
976             else
977             {
978               drawLineGraph(g, row, row_annotations, startRes, endRes, y,
979                       row.graphMin, row.graphMax, row.graphHeight);
980             }
981           }
982           else if (row.graph == AlignmentAnnotation.BAR_GRAPH)
983           {
984             drawBarGraph(g, row, row_annotations, startRes, endRes,
985                     row.graphMin, row.graphMax, y, renderHistogram,
986                     renderProfile, normaliseProfile);
987           }
988         }
989       }
990       else
991       {
992         if (clipst && !clipend)
993         {
994           clipend = true;
995         }
996       }// end if_in_visible_region
997       if (row.graph > 0 && row.hasText)
998       {
999         y += charHeight;
1000       }
1001
1002       if (row.graph == 0)
1003       {
1004         y += aa[i].height;
1005       }
1006     }
1007     if (debugRedraw)
1008     {
1009       if (canClip)
1010       {
1011         if (clipst)
1012         {
1013           System.err.println("Start clip at : " + yfrom + " (index " + f_i
1014                   + ")");
1015         }
1016         if (clipend)
1017         {
1018           System.err.println("End clip at : " + yto + " (index " + f_to
1019                   + ")");
1020         }
1021       }
1022       ;
1023       System.err.println("Annotation Rendering time:"
1024               + (System.currentTimeMillis() - stime));
1025     }
1026     ;
1027
1028     return !usedFaded;
1029   }
1030
1031   public static final Color GLYPHLINE_COLOR = Color.gray;
1032
1033   public static final Color SHEET_COLOUR = Color.green;
1034
1035   public static final Color HELIX_COLOUR = Color.red;
1036
1037   public static final Color STEM_COLOUR = Color.blue;
1038
1039   private Color sdNOTCANONICAL_COLOUR;
1040
1041   public void drawGlyphLine(Graphics g, Annotation[] row, int lastSSX,
1042           int x, int y, int iconOffset, int startRes, int column,
1043           boolean validRes, boolean validEnd)
1044   {
1045     g.setColor(GLYPHLINE_COLOR);
1046     g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth) - lastSSX, 2);
1047   }
1048
1049   public void drawSheetAnnot(Graphics g, Annotation[] row,
1050
1051   int lastSSX, int x, int y, int iconOffset, int startRes, int column,
1052           boolean validRes, boolean validEnd)
1053   {
1054     g.setColor(SHEET_COLOUR);
1055
1056     if (!validEnd || !validRes || row == null || row[column] == null
1057             || row[column].secondaryStructure != 'E')
1058     {
1059       g.fillRect(lastSSX, y + 4 + iconOffset,
1060               (x * charWidth) - lastSSX - 4, 7);
1061       g.fillPolygon(new int[]
1062       { (x * charWidth) - 4, (x * charWidth) - 4, (x * charWidth) },
1063               new int[]
1064               { y + iconOffset, y + 14 + iconOffset, y + 7 + iconOffset },
1065               3);
1066     }
1067     else
1068     {
1069       g.fillRect(lastSSX, y + 4 + iconOffset,
1070               (x + 1) * charWidth - lastSSX, 7);
1071     }
1072
1073   }
1074
1075   public void drawHelixAnnot(Graphics g, Annotation[] row, int lastSSX,
1076           int x, int y, int iconOffset, int startRes, int column,
1077           boolean validRes, boolean validEnd)
1078   {
1079     g.setColor(HELIX_COLOUR);
1080
1081     int sCol = (lastSSX / charWidth) + startRes;
1082     int x1 = lastSSX;
1083     int x2 = (x * charWidth);
1084
1085     if (MAC)
1086     {
1087       int ofs = charWidth / 2;
1088       // Off by 1 offset when drawing rects and ovals
1089       // to offscreen image on the MAC
1090       g.fillRoundRect(lastSSX, y + 4 + iconOffset, x2 - x1, 8, 8, 8);
1091       if (sCol == 0 || row[sCol - 1] == null
1092               || row[sCol - 1].secondaryStructure != 'H')
1093       {
1094       }
1095       else
1096       {
1097         // g.setColor(Color.orange);
1098         g.fillRoundRect(lastSSX, y + 4 + iconOffset, x2 - x1 - ofs + 1, 8,
1099                 0, 0);
1100       }
1101       if (!validRes || row[column] == null
1102               || row[column].secondaryStructure != 'H')
1103       {
1104
1105       }
1106       else
1107       {
1108         // g.setColor(Color.magenta);
1109         g.fillRoundRect(lastSSX + ofs, y + 4 + iconOffset, x2 - x1 - ofs
1110                 + 1, 8, 0, 0);
1111
1112       }
1113
1114       return;
1115     }
1116
1117     if (sCol == 0 || row[sCol - 1] == null
1118             || row[sCol - 1].secondaryStructure != 'H')
1119     {
1120       g.fillArc(lastSSX, y + 4 + iconOffset, charWidth, 8, 90, 180);
1121       x1 += charWidth / 2;
1122     }
1123
1124     if (!validRes || row[column] == null
1125             || row[column].secondaryStructure != 'H')
1126     {
1127       g.fillArc((x * charWidth) - charWidth, y + 4 + iconOffset, charWidth,
1128               8, 270, 180);
1129       x2 -= charWidth / 2;
1130     }
1131
1132     g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 8);
1133   }
1134
1135   public void drawLineGraph(Graphics g, AlignmentAnnotation _aa,
1136           Annotation[] aa_annotations, int sRes, int eRes, int y,
1137           float min, float max, int graphHeight)
1138   {
1139     if (sRes > aa_annotations.length)
1140     {
1141       return;
1142     }
1143
1144     int x = 0;
1145
1146     // Adjustment for fastpaint to left
1147     if (eRes < endRes)
1148     {
1149       eRes++;
1150     }
1151
1152     eRes = Math.min(eRes, aa_annotations.length);
1153
1154     if (sRes == 0)
1155     {
1156       x++;
1157     }
1158
1159     int y1 = y, y2 = y;
1160     float range = max - min;
1161
1162     // //Draw origin
1163     if (min < 0)
1164     {
1165       y2 = y - (int) ((0 - min / range) * graphHeight);
1166     }
1167
1168     g.setColor(Color.gray);
1169     g.drawLine(x - charWidth, y2, (eRes - sRes + 1) * charWidth, y2);
1170
1171     eRes = Math.min(eRes, aa_annotations.length);
1172
1173     int column;
1174     int aaMax = aa_annotations.length - 1;
1175
1176     while (x < eRes - sRes)
1177     {
1178       column = sRes + x;
1179       if (hasHiddenColumns)
1180       {
1181         column = columnSelection.adjustForHiddenColumns(column);
1182       }
1183
1184       if (column > aaMax)
1185       {
1186         break;
1187       }
1188
1189       if (aa_annotations[column] == null
1190               || aa_annotations[column - 1] == null)
1191       {
1192         x++;
1193         continue;
1194       }
1195
1196       if (aa_annotations[column].colour == null)
1197       {
1198         g.setColor(Color.black);
1199       }
1200       else
1201       {
1202         g.setColor(aa_annotations[column].colour);
1203       }
1204
1205       y1 = y
1206               - (int) (((aa_annotations[column - 1].value - min) / range) * graphHeight);
1207       y2 = y
1208               - (int) (((aa_annotations[column].value - min) / range) * graphHeight);
1209
1210       g.drawLine(x * charWidth - charWidth / 2, y1, x * charWidth
1211               + charWidth / 2, y2);
1212       x++;
1213     }
1214
1215     if (_aa.threshold != null)
1216     {
1217       g.setColor(_aa.threshold.colour);
1218       Graphics2D g2 = (Graphics2D) g;
1219       g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
1220               BasicStroke.JOIN_ROUND, 3f, new float[]
1221               { 5f, 3f }, 0f));
1222
1223       y2 = (int) (y - ((_aa.threshold.value - min) / range) * graphHeight);
1224       g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
1225       g2.setStroke(new BasicStroke());
1226     }
1227   }
1228
1229   public void drawBarGraph(Graphics g, AlignmentAnnotation _aa,
1230           Annotation[] aa_annotations, int sRes, int eRes, float min,
1231           float max, int y, boolean renderHistogram, boolean renderProfile,
1232           boolean normaliseProfile)
1233   {
1234     if (sRes > aa_annotations.length)
1235     {
1236       return;
1237     }
1238     Font ofont = g.getFont();
1239     eRes = Math.min(eRes, aa_annotations.length);
1240
1241     int x = 0, y1 = y, y2 = y;
1242
1243     float range = max - min;
1244
1245     if (min < 0)
1246     {
1247       y2 = y - (int) ((0 - min / (range)) * _aa.graphHeight);
1248     }
1249
1250     g.setColor(Color.gray);
1251
1252     g.drawLine(x, y2, (eRes - sRes) * charWidth, y2);
1253
1254     int column;
1255     int aaMax = aa_annotations.length - 1;
1256     while (x < eRes - sRes)
1257     {
1258       column = sRes + x;
1259       if (hasHiddenColumns)
1260       {
1261         column = columnSelection.adjustForHiddenColumns(column);
1262       }
1263
1264       if (column > aaMax)
1265       {
1266         break;
1267       }
1268
1269       if (aa_annotations[column] == null)
1270       {
1271         x++;
1272         continue;
1273       }
1274       if (aa_annotations[column].colour == null)
1275       {
1276         g.setColor(Color.black);
1277       }
1278       else
1279       {
1280         g.setColor(aa_annotations[column].colour);
1281       }
1282
1283       y1 = y
1284               - (int) (((aa_annotations[column].value - min) / (range)) * _aa.graphHeight);
1285
1286       if (renderHistogram)
1287       {
1288         if (y1 - y2 > 0)
1289         {
1290           g.fillRect(x * charWidth, y2, charWidth, y1 - y2);
1291         }
1292         else
1293         {
1294           g.fillRect(x * charWidth, y1, charWidth, y2 - y1);
1295         }
1296       }
1297       // draw profile if available
1298       if (renderProfile)
1299       {
1300
1301         int profl[] = getProfileFor(_aa, column);
1302         // just try to draw the logo if profl is not null
1303         if (profl != null && profl[1] != 0)
1304         {
1305           float ht = normaliseProfile ? y - _aa.graphHeight : y1;
1306           double htn = normaliseProfile ? _aa.graphHeight : (y2 - y1);// aa.graphHeight;
1307           double hght;
1308           float wdth;
1309           double ht2 = 0;
1310           char[] dc;
1311
1312           /**
1313            * profl.length == 74 indicates that the profile of a secondary
1314            * structure conservation row was accesed. Therefore dc gets length 2,
1315            * to have space for a basepair instead of just a single nucleotide
1316            */
1317           if (profl.length == 74)
1318           {
1319             dc = new char[2];
1320           }
1321           else
1322           {
1323             dc = new char[1];
1324           }
1325           LineMetrics lm = g.getFontMetrics(ofont).getLineMetrics("Q", g);
1326           double scale = 1f / (normaliseProfile ? profl[1] : 100f);
1327           float ofontHeight = 1f / lm.getAscent();// magnify to fill box
1328           double scl = 0.0;
1329           for (int c = 2; c < profl[0];)
1330           {
1331             dc[0] = (char) profl[c++];
1332
1333             if (_aa.label.startsWith("StrucConsensus"))
1334             {
1335               dc[1] = (char) profl[c++];
1336             }
1337
1338             wdth = charWidth;
1339             wdth /= fm.charsWidth(dc, 0, dc.length);
1340
1341             ht += scl;
1342             {
1343               scl = htn * scale * profl[c++];
1344               lm = ofont.getLineMetrics(dc, 0, 1, g.getFontMetrics()
1345                       .getFontRenderContext());
1346               g.setFont(ofont.deriveFont(AffineTransform.getScaleInstance(
1347                       wdth, scl / lm.getAscent())));
1348               lm = g.getFontMetrics().getLineMetrics(dc, 0, 1, g);
1349
1350               // Debug - render boxes around characters
1351               // g.setColor(Color.red);
1352               // g.drawRect(x*av.charWidth, (int)ht, av.charWidth,
1353               // (int)(scl));
1354               // g.setColor(profcolour.findColour(dc[0]).darker());
1355               g.setColor(profcolour.findColour(dc[0], column, null));
1356
1357               hght = (ht + (scl - lm.getDescent() - lm.getBaselineOffsets()[lm
1358                       .getBaselineIndex()]));
1359
1360               g.drawChars(dc, 0, dc.length, x * charWidth, (int) hght);
1361             }
1362           }
1363           g.setFont(ofont);
1364         }
1365       }
1366       x++;
1367     }
1368     if (_aa.threshold != null)
1369     {
1370       g.setColor(_aa.threshold.colour);
1371       Graphics2D g2 = (Graphics2D) g;
1372       g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
1373               BasicStroke.JOIN_ROUND, 3f, new float[]
1374               { 5f, 3f }, 0f));
1375
1376       y2 = (int) (y - ((_aa.threshold.value - min) / range)
1377               * _aa.graphHeight);
1378       g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
1379       g2.setStroke(new BasicStroke());
1380     }
1381   }
1382
1383   // used by overview window
1384   public void drawGraph(Graphics g, AlignmentAnnotation _aa,
1385           Annotation[] aa_annotations, int width, int y, int sRes, int eRes)
1386   {
1387     eRes = Math.min(eRes, aa_annotations.length);
1388     g.setColor(Color.white);
1389     g.fillRect(0, 0, width, y);
1390     g.setColor(new Color(0, 0, 180));
1391
1392     int x = 0, height;
1393
1394     for (int j = sRes; j < eRes; j++)
1395     {
1396       if (aa_annotations[j] != null)
1397       {
1398         if (aa_annotations[j].colour == null)
1399         {
1400           g.setColor(Color.black);
1401         }
1402         else
1403         {
1404           g.setColor(aa_annotations[j].colour);
1405         }
1406
1407         height = (int) ((aa_annotations[j].value / _aa.graphMax) * y);
1408         if (height > y)
1409         {
1410           height = y;
1411         }
1412
1413         g.fillRect(x, y - height, charWidth, height);
1414       }
1415       x += charWidth;
1416     }
1417   }
1418
1419   Color getNotCanonicalColor(char lastss)
1420   {
1421     switch (lastss)
1422     {
1423     case '{':
1424     case '}':
1425       return new Color(255, 125, 5);
1426
1427     case '[':
1428     case ']':
1429       return new Color(245, 115, 10);
1430
1431     case '>':
1432     case '<':
1433       return new Color(235, 135, 15);
1434
1435     case 'A':
1436     case 'a':
1437       return new Color(225, 105, 20);
1438
1439     case 'B':
1440     case 'b':
1441       return new Color(215, 145, 30);
1442
1443     case 'C':
1444     case 'c':
1445       return new Color(205, 95, 35);
1446
1447     case 'D':
1448     case 'd':
1449       return new Color(195, 155, 45);
1450
1451     case 'E':
1452     case 'e':
1453       return new Color(185, 85, 55);
1454
1455     case 'F':
1456     case 'f':
1457       return new Color(175, 165, 65);
1458
1459     case 'G':
1460     case 'g':
1461       return new Color(170, 75, 75);
1462
1463     case 'H':
1464     case 'h':
1465       return new Color(160, 175, 85);
1466
1467     case 'I':
1468     case 'i':
1469       return new Color(150, 65, 95);
1470
1471     case 'J':
1472     case 'j':
1473       return new Color(140, 185, 105);
1474
1475     case 'K':
1476     case 'k':
1477       return new Color(130, 55, 110);
1478
1479     case 'L':
1480     case 'l':
1481       return new Color(120, 195, 120);
1482
1483     case 'M':
1484     case 'm':
1485       return new Color(110, 45, 130);
1486
1487     case 'N':
1488     case 'n':
1489       return new Color(100, 205, 140);
1490
1491     case 'O':
1492     case 'o':
1493       return new Color(90, 35, 150);
1494
1495     case 'P':
1496     case 'p':
1497       return new Color(85, 215, 160);
1498
1499     case 'Q':
1500     case 'q':
1501       return new Color(75, 25, 170);
1502
1503     case 'R':
1504     case 'r':
1505       return new Color(65, 225, 180);
1506
1507     case 'S':
1508     case 's':
1509       return new Color(55, 15, 185);
1510
1511     case 'T':
1512     case 't':
1513       return new Color(45, 235, 195);
1514
1515     case 'U':
1516     case 'u':
1517       return new Color(35, 5, 205);
1518
1519     case 'V':
1520     case 'v':
1521       return new Color(25, 245, 215);
1522
1523     case 'W':
1524     case 'w':
1525       return new Color(15, 0, 225);
1526
1527     case 'X':
1528     case 'x':
1529       return new Color(10, 255, 235);
1530
1531     case 'Y':
1532     case 'y':
1533       return new Color(5, 150, 245);
1534
1535     case 'Z':
1536     case 'z':
1537       return new Color(0, 80, 255);
1538
1539     default:
1540       System.out.println("This is not a interaction : " + lastss);
1541       return null;
1542
1543     }
1544   }
1545 }