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