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