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