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