JAL-1841 robustness fix
[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.Rna;
26 import jalview.analysis.StructureFrequency;
27 import jalview.api.AlignViewportI;
28 import jalview.datamodel.AlignmentAnnotation;
29 import jalview.datamodel.Annotation;
30 import jalview.datamodel.ColumnSelection;
31 import jalview.schemes.ColourSchemeI;
32 import jalview.schemes.ResidueProperties;
33
34 import java.awt.BasicStroke;
35 import java.awt.Color;
36 import java.awt.Font;
37 import java.awt.FontMetrics;
38 import java.awt.Graphics;
39 import java.awt.Graphics2D;
40 import java.awt.Image;
41 import java.awt.font.LineMetrics;
42 import java.awt.geom.AffineTransform;
43 import java.awt.image.ImageObserver;
44 import java.util.BitSet;
45 import java.util.Hashtable;
46
47 public class AnnotationRenderer
48 {
49   private static final int UPPER_TO_LOWER = 'a' - 'A'; // 32
50
51   private static final int CHAR_A = 'A'; // 65
52
53   private static final int CHAR_Z = 'Z'; // 90
54
55   /**
56    * flag indicating if timing and redraw parameter info should be output
57    */
58   private final boolean debugRedraw;
59
60   public AnnotationRenderer()
61   {
62     this(false);
63   }
64
65   /**
66    * Create a new annotation Renderer
67    * 
68    * @param debugRedraw
69    *          flag indicating if timing and redraw parameter info should be
70    *          output
71    */
72   public AnnotationRenderer(boolean debugRedraw)
73   {
74     this.debugRedraw = debugRedraw;
75   }
76
77   void drawStemAnnot(Graphics g, Annotation[] row_annotations,
78           int lastSSX, int x, int y, int iconOffset, int startRes,
79           int column, boolean validRes, boolean validEnd)
80   {
81     g.setColor(STEM_COLOUR);
82     int sCol = (lastSSX / charWidth) + startRes;
83     int x1 = lastSSX;
84     int x2 = (x * charWidth);
85
86     char dc = (column == 0 || row_annotations[column - 1] == null) ? ' '
87             : row_annotations[column - 1].secondaryStructure;
88
89     boolean diffupstream = sCol == 0 || row_annotations[sCol - 1] == null
90             || dc != row_annotations[sCol - 1].secondaryStructure;
91     boolean diffdownstream = !validRes || !validEnd
92             || row_annotations[column] == null
93             || dc != row_annotations[column].secondaryStructure;
94
95     if (column > 0 && Rna.isClosingParenthesis(dc))
96     {
97       if (diffupstream)
98       // if (validRes && column>1 && row_annotations[column-2]!=null &&
99       // dc.equals(row_annotations[column-2].displayCharacter))
100       {
101         /*
102          * if new annotation with a closing base pair half of the stem, 
103          * display a backward arrow
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       // display a forward arrow
118       if (diffdownstream)
119       {
120         /*
121          * if annotation ending with an opeing base pair half of the stem, 
122          * display a forward arrow
123          */
124         g.fillPolygon(new int[] { x2 - 5, x2 - 5, x2 }, new int[] {
125             y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset }, 3);
126         x2 -= 5;
127       }
128       if (diffupstream)
129       {
130         x1 += 1;
131       }
132     }
133     // draw arrow body
134     g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 7);
135   }
136
137   private int charWidth, endRes, charHeight;
138
139   private boolean validCharWidth, hasHiddenColumns;
140
141   private FontMetrics fm;
142
143   private final boolean MAC = jalview.util.Platform.isAMac();
144
145   boolean av_renderHistogram = true, av_renderProfile = true,
146           av_normaliseProfile = false;
147
148   ColourSchemeI profcolour = null;
149
150   private ColumnSelection columnSelection;
151
152   private Hashtable[] hconsensus;
153
154   private Hashtable[] complementConsensus;
155
156   private Hashtable[] hStrucConsensus;
157
158   private boolean av_ignoreGapsConsensus;
159
160   /**
161    * attributes set from AwtRenderPanelI
162    */
163   /**
164    * old image used when data is currently being calculated and cannot be
165    * rendered
166    */
167   private Image fadedImage;
168
169   /**
170    * panel being rendered into
171    */
172   private ImageObserver annotationPanel;
173
174   /**
175    * width of image to render in panel
176    */
177   private int imgWidth;
178
179   /**
180    * offset to beginning of visible area
181    */
182   private int sOffset;
183
184   /**
185    * offset to end of visible area
186    */
187   private int visHeight;
188
189   /**
190    * indicate if the renderer should only render the visible portion of the
191    * annotation given the current view settings
192    */
193   private boolean useClip = true;
194
195   /**
196    * master flag indicating if renderer should ever try to clip. not enabled for
197    * jalview 2.8.1
198    */
199   private boolean canClip = false;
200
201   void drawNotCanonicalAnnot(Graphics g, Color nonCanColor,
202           Annotation[] row_annotations, int lastSSX, int x, int y,
203           int iconOffset, int startRes, int column, boolean validRes,
204           boolean validEnd)
205   {
206     // System.out.println(nonCanColor);
207
208     g.setColor(nonCanColor);
209     int sCol = (lastSSX / charWidth) + startRes;
210     int x1 = lastSSX;
211     int x2 = (x * charWidth);
212
213     String dc = (column == 0 || row_annotations[column - 1] == null) ? ""
214             : row_annotations[column - 1].displayCharacter;
215
216     boolean diffupstream = sCol == 0 || row_annotations[sCol - 1] == null
217             || !dc.equals(row_annotations[sCol - 1].displayCharacter);
218     boolean diffdownstream = !validRes || !validEnd
219             || row_annotations[column] == null
220             || !dc.equals(row_annotations[column].displayCharacter);
221     // System.out.println("Column "+column+" diff up: "+diffupstream+" down:"+diffdownstream);
222     // If a closing base pair half of the stem, display a backward arrow
223     if (column > 0 && Rna.isClosingParenthesis(dc))
224     {
225
226       if (diffupstream)
227       // if (validRes && column>1 && row_annotations[column-2]!=null &&
228       // dc.equals(row_annotations[column-2].displayCharacter))
229       {
230         g.fillPolygon(new int[] { lastSSX + 5, lastSSX + 5, lastSSX },
231                 new int[] { y + iconOffset, y + 14 + iconOffset,
232                     y + 8 + iconOffset }, 3);
233         x1 += 5;
234       }
235       if (diffdownstream)
236       {
237         x2 -= 1;
238       }
239     }
240     else
241     {
242
243       // display a forward arrow
244       if (diffdownstream)
245       {
246         g.fillPolygon(new int[] { x2 - 5, x2 - 5, x2 }, new int[] {
247             y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset }, 3);
248         x2 -= 5;
249       }
250       if (diffupstream)
251       {
252         x1 += 1;
253       }
254     }
255     // draw arrow body
256     g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 7);
257   }
258
259   // public void updateFromAnnotationPanel(FontMetrics annotFM, AlignViewportI
260   // av)
261   public void updateFromAwtRenderPanel(AwtRenderPanelI annotPanel,
262           AlignViewportI av)
263   {
264     fm = annotPanel.getFontMetrics();
265     annotationPanel = annotPanel;
266     fadedImage = annotPanel.getFadedImage();
267     imgWidth = annotPanel.getFadedImageWidth();
268     // visible area for rendering
269     int[] bounds = annotPanel.getVisibleVRange();
270     if (bounds != null)
271     {
272       sOffset = bounds[0];
273       visHeight = bounds[1];
274       if (visHeight == 0)
275       {
276         useClip = false;
277       }
278       else
279       {
280         useClip = canClip;
281       }
282     }
283     else
284     {
285       useClip = false;
286     }
287
288     updateFromAlignViewport(av);
289   }
290
291   public void updateFromAlignViewport(AlignViewportI av)
292   {
293     charWidth = av.getCharWidth();
294     endRes = av.getEndRes();
295     charHeight = av.getCharHeight();
296     hasHiddenColumns = av.hasHiddenColumns();
297     validCharWidth = av.isValidCharWidth();
298     av_renderHistogram = av.isShowConsensusHistogram();
299     av_renderProfile = av.isShowSequenceLogo();
300     av_normaliseProfile = av.isNormaliseSequenceLogo();
301     profcolour = av.getGlobalColourScheme();
302     if (profcolour == null)
303     {
304       // Set the default colour for sequence logo if the alignnent has no
305       // colourscheme set
306       profcolour = av.getAlignment().isNucleotide() ? new jalview.schemes.NucleotideColourScheme()
307               : new jalview.schemes.ZappoColourScheme();
308     }
309     columnSelection = av.getColumnSelection();
310     hconsensus = av.getSequenceConsensusHash();
311     complementConsensus = av.getComplementConsensusHash();
312     hStrucConsensus = av.getRnaStructureConsensusHash();
313     av_ignoreGapsConsensus = av.isIgnoreGapsConsensus();
314   }
315
316   /**
317    * Returns profile data; the first element is the profile type, the second is
318    * the number of distinct values, the third the total count, and the remainder
319    * depend on the profile type.
320    * 
321    * @param aa
322    * @param column
323    * @return
324    */
325   int[] getProfileFor(AlignmentAnnotation aa, int column)
326   {
327     // TODO : consider refactoring the global alignment calculation
328     // properties/rendering attributes as a global 'alignment group' which holds
329     // all vis settings for the alignment as a whole rather than a subset
330     //
331     if (aa.autoCalculated
332             && (aa.label.startsWith("Consensus") || aa.label
333                     .startsWith("cDNA Consensus")))
334     {
335       boolean forComplement = aa.label.startsWith("cDNA Consensus");
336       if (aa.groupRef != null && aa.groupRef.consensusData != null
337               && aa.groupRef.isShowSequenceLogo())
338       {
339         // TODO? group consensus for cDNA complement
340         return AAFrequency.extractProfile(
341                 aa.groupRef.consensusData[column],
342                 aa.groupRef.getIgnoreGapsConsensus());
343       }
344       // TODO extend annotation row to enable dynamic and static profile data to
345       // be stored
346       if (aa.groupRef == null && aa.sequenceRef == null)
347       {
348         if (forComplement)
349         {
350           return AAFrequency.extractCdnaProfile(
351                   complementConsensus[column], av_ignoreGapsConsensus);
352         }
353         else
354         {
355           return AAFrequency.extractProfile(hconsensus[column],
356                   av_ignoreGapsConsensus);
357         }
358       }
359     }
360     else
361     {
362       if (aa.autoCalculated && aa.label.startsWith("StrucConsensus"))
363       {
364         // TODO implement group structure consensus
365         /*
366          * if (aa.groupRef != null && aa.groupRef.consensusData != null &&
367          * aa.groupRef.isShowSequenceLogo()) { //TODO check what happens for
368          * group selections return StructureFrequency.extractProfile(
369          * aa.groupRef.consensusData[column], aa.groupRef
370          * .getIgnoreGapsConsensus()); }
371          */
372         // TODO extend annotation row to enable dynamic and static profile data
373         // to
374         // be stored
375         if (aa.groupRef == null && aa.sequenceRef == null
376                 && hStrucConsensus != null
377                 && hStrucConsensus.length > column)
378         {
379           return StructureFrequency.extractProfile(hStrucConsensus[column],
380                   av_ignoreGapsConsensus);
381         }
382       }
383     }
384     return null;
385   }
386
387   boolean rna = false;
388
389   /**
390    * Render the annotation rows associated with an alignment.
391    * 
392    * @param annotPanel
393    *          container frame
394    * @param av
395    *          data and view settings to render
396    * @param g
397    *          destination for graphics
398    * @param activeRow
399    *          row where a mouse event occured (or -1)
400    * @param startRes
401    *          first column that will be drawn
402    * @param endRes
403    *          last column that will be drawn
404    * @return true if the fadedImage was used for any alignment annotation rows
405    *         currently being calculated
406    */
407   public boolean drawComponent(AwtRenderPanelI annotPanel,
408           AlignViewportI av, Graphics g, int activeRow, int startRes,
409           int endRes)
410   {
411     long stime = System.currentTimeMillis();
412     boolean usedFaded = false;
413     // NOTES:
414     // AnnotationPanel needs to implement: ImageObserver, access to
415     // AlignViewport
416     updateFromAwtRenderPanel(annotPanel, av);
417     fm = g.getFontMetrics();
418     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
419     int temp = 0;
420     if (aa == null)
421     {
422       return false;
423     }
424     int x = 0, y = 0;
425     int column = 0;
426     char lastSS;
427     int lastSSX;
428     int iconOffset = 0;
429     boolean validRes = false;
430     boolean validEnd = false;
431     boolean labelAllCols = false;
432     boolean centreColLabels;
433     boolean centreColLabelsDef = av.isCentreColumnLabels();
434     boolean scaleColLabel = false;
435     final AlignmentAnnotation consensusAnnot = av
436             .getAlignmentConsensusAnnotation();
437     final AlignmentAnnotation structConsensusAnnot = av
438             .getAlignmentStrucConsensusAnnotation();
439     final AlignmentAnnotation complementConsensusAnnot = av
440             .getComplementConsensusAnnotation();
441     boolean renderHistogram = true, renderProfile = true, normaliseProfile = false, isRNA = rna;
442
443     BitSet graphGroupDrawn = new BitSet();
444     int charOffset = 0; // offset for a label
445     float fmWidth, fmScaling = 1f; // scaling for a label to fit it into a
446     // column.
447     Font ofont = g.getFont();
448     // \u03B2 \u03B1
449     // debug ints
450     int yfrom = 0, f_i = 0, yto = 0, f_to = 0;
451     boolean clipst = false, clipend = false;
452     for (int i = 0; i < aa.length; i++)
453     {
454       AlignmentAnnotation row = aa[i];
455       isRNA = row.isRNA();
456       {
457         // check if this is a consensus annotation row and set the display
458         // settings appropriately
459         // TODO: generalise this to have render styles for consensus/profile
460         // data
461         if (row.groupRef != null && row == row.groupRef.getConsensus())
462         {
463           renderHistogram = row.groupRef.isShowConsensusHistogram();
464           renderProfile = row.groupRef.isShowSequenceLogo();
465           normaliseProfile = row.groupRef.isNormaliseSequenceLogo();
466         }
467         else if (row == consensusAnnot || row == structConsensusAnnot
468                 || row == complementConsensusAnnot)
469         {
470           renderHistogram = av_renderHistogram;
471           renderProfile = av_renderProfile;
472           normaliseProfile = av_normaliseProfile;
473         }
474         else
475         {
476           renderHistogram = true;
477           // don't need to set render/normaliseProfile since they are not
478           // currently used in any other annotation track renderer
479         }
480       }
481       Annotation[] row_annotations = row.annotations;
482       if (!row.visible)
483       {
484         continue;
485       }
486       centreColLabels = row.centreColLabels || centreColLabelsDef;
487       labelAllCols = row.showAllColLabels;
488       scaleColLabel = row.scaleColLabel;
489       lastSS = ' ';
490       lastSSX = 0;
491
492       if (!useClip
493               || ((y - charHeight) < visHeight && (y + row.height + charHeight * 2) >= sOffset))
494       {// if_in_visible_region
495         if (!clipst)
496         {
497           clipst = true;
498           yfrom = y;
499           f_i = i;
500         }
501         yto = y;
502         f_to = i;
503         if (row.graph > 0)
504         {
505           if (row.graphGroup > -1 && graphGroupDrawn.get(row.graphGroup))
506           {
507             continue;
508           }
509
510           // this is so that we draw the characters below the graph
511           y += row.height;
512
513           if (row.hasText)
514           {
515             iconOffset = charHeight - fm.getDescent();
516             y -= charHeight;
517           }
518         }
519         else if (row.hasText)
520         {
521           iconOffset = charHeight - fm.getDescent();
522
523         }
524         else
525         {
526           iconOffset = 0;
527         }
528
529         if (row.autoCalculated && av.isCalculationInProgress(row))
530         {
531           y += charHeight;
532           usedFaded = true;
533           g.drawImage(fadedImage, 0, y - row.height, imgWidth, y, 0, y
534                   - row.height, imgWidth, y, annotationPanel);
535           g.setColor(Color.black);
536           // g.drawString("Calculating "+aa[i].label+"....",20, y-row.height/2);
537
538           continue;
539         }
540
541         /*
542          * else if (annotationPanel.av.updatingConservation &&
543          * aa[i].label.equals("Conservation")) {
544          * 
545          * y += charHeight; g.drawImage(annotationPanel.fadedImage, 0, y -
546          * row.height, annotationPanel.imgWidth, y, 0, y - row.height,
547          * annotationPanel.imgWidth, y, annotationPanel);
548          * 
549          * g.setColor(Color.black); //
550          * g.drawString("Calculating Conservation.....",20, y-row.height/2);
551          * 
552          * continue; } else if (annotationPanel.av.updatingConservation &&
553          * aa[i].label.equals("Quality")) {
554          * 
555          * y += charHeight; g.drawImage(annotationPanel.fadedImage, 0, y -
556          * row.height, annotationPanel.imgWidth, y, 0, y - row.height,
557          * annotationPanel.imgWidth, y, annotationPanel);
558          * g.setColor(Color.black); // /
559          * g.drawString("Calculating Quality....",20, y-row.height/2);
560          * 
561          * continue; }
562          */
563         // first pass sets up state for drawing continuation from left-hand
564         // column
565         // of startRes
566         x = (startRes == 0) ? 0 : -1;
567         while (x < endRes - startRes)
568         {
569           if (hasHiddenColumns)
570           {
571             column = columnSelection.adjustForHiddenColumns(startRes + x);
572             if (column > row_annotations.length - 1)
573             {
574               break;
575             }
576           }
577           else
578           {
579             column = startRes + x;
580           }
581
582           if ((row_annotations == null)
583                   || (row_annotations.length <= column)
584                   || (row_annotations[column] == null))
585           {
586             validRes = false;
587           }
588           else
589           {
590             validRes = true;
591           }
592           final String displayChar = validRes ? row_annotations[column].displayCharacter
593                   : null;
594           if (x > -1)
595           {
596             if (activeRow == i)
597             {
598               g.setColor(Color.red);
599
600               if (columnSelection != null)
601               {
602                 if (columnSelection.contains(column))
603                 {
604                   g.fillRect(x * charWidth, y, charWidth, charHeight);
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 (isRNA && (ss >= CHAR_A) && (ss <= CHAR_Z))
719             {
720               // distinguish between forward/backward base-pairing
721               int ssLowerCase = ss + UPPER_TO_LOWER;
722               // TODO would .equals() be safer here? or charAt(0)?
723               if (displayChar.indexOf(ssLowerCase) > -1)
724               {
725                 ss = (char) ssLowerCase;
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                   // no break if isRNA - falls through to drawNotCanonicalAnnot!
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                   // no break if isRNA - fall through to drawNotCanonicalAnnot!
764
765                 case '{':
766                 case '}':
767                 case '[':
768                 case ']':
769                 case '>':
770                 case '<':
771                 case 'A':
772                 case 'a':
773                 case 'B':
774                 case 'b':
775                 case 'C':
776                 case 'c':
777                 case 'D':
778                 case 'd':
779                 case 'e':
780                 case 'F':
781                 case 'f':
782                 case 'G':
783                 case 'g':
784                 case 'h':
785                 case 'I':
786                 case 'i':
787                 case 'J':
788                 case 'j':
789                 case 'K':
790                 case 'k':
791                 case 'L':
792                 case 'l':
793                 case 'M':
794                 case 'm':
795                 case 'N':
796                 case 'n':
797                 case 'O':
798                 case 'o':
799                 case 'P':
800                 case 'p':
801                 case 'Q':
802                 case 'q':
803                 case 'R':
804                 case 'r':
805                 case 'S':
806                 case 's':
807                 case 'T':
808                 case 't':
809                 case 'U':
810                 case 'u':
811                 case 'V':
812                 case 'v':
813                 case 'W':
814                 case 'w':
815                 case 'X':
816                 case 'x':
817                 case 'Y':
818                 case 'y':
819                 case 'Z':
820                 case 'z':
821
822                   Color nonCanColor = getNotCanonicalColor(lastSS);
823                   drawNotCanonicalAnnot(g, nonCanColor, row_annotations,
824                           lastSSX, x, y, iconOffset, startRes, column,
825                           validRes, validEnd);
826                   temp = x;
827                   break;
828                 default:
829                   g.setColor(Color.gray);
830                   g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth)
831                           - lastSSX, 2);
832                   temp = x;
833                   break;
834                 }
835               }
836               if (validRes)
837               {
838                 lastSS = ss;
839               }
840               else
841               {
842                 lastSS = ' ';
843               }
844               if (x > -1)
845               {
846                 lastSSX = (x * charWidth);
847               }
848             }
849           }
850           column++;
851           x++;
852         }
853         if (column >= row_annotations.length)
854         {
855           column = row_annotations.length - 1;
856           validEnd = false;
857         }
858         else
859         {
860           validEnd = true;
861         }
862         if ((row_annotations == null) || (row_annotations.length <= column)
863                 || (row_annotations[column] == null))
864         {
865           validRes = false;
866         }
867         else
868         {
869           validRes = true;
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             // no break if isRNA - fall through to drawNotCanonicalAnnot!
886
887           case 'E':
888             if (!isRNA)
889             {
890               drawSheetAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
891                       startRes, column, validRes, validEnd);
892               break;
893             }
894             // no break if isRNA - fall through to drawNotCanonicalAnnot!
895
896           case '(':
897           case ')': // Stem case for RNA secondary structure
898
899             drawStemAnnot(g, row_annotations, lastSSX, x, y, iconOffset,
900                     startRes, column, validRes, validEnd);
901
902             break;
903           case '{':
904           case '}':
905           case '[':
906           case ']':
907           case '>':
908           case '<':
909           case 'A':
910           case 'a':
911           case 'B':
912           case 'b':
913           case 'C':
914           case 'c':
915           case 'D':
916           case 'd':
917           case 'e':
918           case 'F':
919           case 'f':
920           case 'G':
921           case 'g':
922           case 'h':
923           case 'I':
924           case 'i':
925           case 'J':
926           case 'j':
927           case 'K':
928           case 'k':
929           case 'L':
930           case 'l':
931           case 'M':
932           case 'm':
933           case 'N':
934           case 'n':
935           case 'O':
936           case 'o':
937           case 'P':
938           case 'p':
939           case 'Q':
940           case 'q':
941           case 'R':
942           case 'r':
943           case 'T':
944           case 't':
945           case 'U':
946           case 'u':
947           case 'V':
948           case 'v':
949           case 'W':
950           case 'w':
951           case 'X':
952           case 'x':
953           case 'Y':
954           case 'y':
955           case 'Z':
956           case 'z':
957             // System.out.println(lastSS);
958             Color nonCanColor = getNotCanonicalColor(lastSS);
959             drawNotCanonicalAnnot(g, nonCanColor, row_annotations, lastSSX,
960                     x, y, iconOffset, startRes, column, validRes, validEnd);
961             break;
962           default:
963             drawGlyphLine(g, row_annotations, lastSSX, x, y, iconOffset,
964                     startRes, column, validRes, validEnd);
965             break;
966           }
967         }
968
969         if (row.graph > 0 && row.graphHeight > 0)
970         {
971           if (row.graph == AlignmentAnnotation.LINE_GRAPH)
972           {
973             if (row.graphGroup > -1 && !graphGroupDrawn.get(row.graphGroup))
974             {
975               // TODO: JAL-1291 revise rendering model so the graphGroup map is
976               // computed efficiently for all visible labels
977               float groupmax = -999999, groupmin = 9999999;
978               for (int gg = 0; gg < aa.length; gg++)
979               {
980                 if (aa[gg].graphGroup != row.graphGroup)
981                 {
982                   continue;
983                 }
984
985                 if (aa[gg] != row)
986                 {
987                   aa[gg].visible = false;
988                 }
989                 if (aa[gg].graphMax > groupmax)
990                 {
991                   groupmax = aa[gg].graphMax;
992                 }
993                 if (aa[gg].graphMin < groupmin)
994                 {
995                   groupmin = aa[gg].graphMin;
996                 }
997               }
998
999               for (int gg = 0; gg < aa.length; gg++)
1000               {
1001                 if (aa[gg].graphGroup == row.graphGroup)
1002                 {
1003                   drawLineGraph(g, aa[gg], aa[gg].annotations, startRes,
1004                           endRes, y, groupmin, groupmax, row.graphHeight);
1005                 }
1006               }
1007
1008               graphGroupDrawn.set(row.graphGroup);
1009             }
1010             else
1011             {
1012               drawLineGraph(g, row, row_annotations, startRes, endRes, y,
1013                       row.graphMin, row.graphMax, row.graphHeight);
1014             }
1015           }
1016           else if (row.graph == AlignmentAnnotation.BAR_GRAPH)
1017           {
1018             drawBarGraph(g, row, row_annotations, startRes, endRes,
1019                     row.graphMin, row.graphMax, y, renderHistogram,
1020                     renderProfile, normaliseProfile);
1021           }
1022         }
1023       }
1024       else
1025       {
1026         if (clipst && !clipend)
1027         {
1028           clipend = true;
1029         }
1030       }// end if_in_visible_region
1031       if (row.graph > 0 && row.hasText)
1032       {
1033         y += charHeight;
1034       }
1035
1036       if (row.graph == 0)
1037       {
1038         y += aa[i].height;
1039       }
1040     }
1041     if (debugRedraw)
1042     {
1043       if (canClip)
1044       {
1045         if (clipst)
1046         {
1047           System.err.println("Start clip at : " + yfrom + " (index " + f_i
1048                   + ")");
1049         }
1050         if (clipend)
1051         {
1052           System.err.println("End clip at : " + yto + " (index " + f_to
1053                   + ")");
1054         }
1055       }
1056       ;
1057       System.err.println("Annotation Rendering time:"
1058               + (System.currentTimeMillis() - stime));
1059     }
1060     ;
1061
1062     return !usedFaded;
1063   }
1064
1065   public static final Color GLYPHLINE_COLOR = Color.gray;
1066
1067   public static final Color SHEET_COLOUR = Color.green;
1068
1069   public static final Color HELIX_COLOUR = Color.red;
1070
1071   public static final Color STEM_COLOUR = Color.blue;
1072
1073   private Color sdNOTCANONICAL_COLOUR;
1074
1075   void drawGlyphLine(Graphics g, Annotation[] row, int lastSSX,
1076           int x, int y, int iconOffset, int startRes, int column,
1077           boolean validRes, boolean validEnd)
1078   {
1079     g.setColor(GLYPHLINE_COLOR);
1080     g.fillRect(lastSSX, y + 6 + iconOffset, (x * charWidth) - lastSSX, 2);
1081   }
1082
1083   void drawSheetAnnot(Graphics g, Annotation[] row,
1084
1085   int lastSSX, int x, int y, int iconOffset, int startRes, int column,
1086           boolean validRes, boolean validEnd)
1087   {
1088     g.setColor(SHEET_COLOUR);
1089
1090     if (!validEnd || !validRes || row == null || row[column] == null
1091             || row[column].secondaryStructure != 'E')
1092     {
1093       g.fillRect(lastSSX, y + 4 + iconOffset,
1094               (x * charWidth) - lastSSX - 4, 7);
1095       g.fillPolygon(new int[] { (x * charWidth) - 4, (x * charWidth) - 4,
1096           (x * charWidth) }, new int[] { y + iconOffset,
1097           y + 14 + iconOffset, y + 7 + iconOffset }, 3);
1098     }
1099     else
1100     {
1101       g.fillRect(lastSSX, y + 4 + iconOffset,
1102               (x + 1) * charWidth - lastSSX, 7);
1103     }
1104
1105   }
1106
1107   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   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[] { 5f, 3f }, 0f));
1253
1254       y2 = (int) (y - ((_aa.threshold.value - min) / range) * graphHeight);
1255       g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
1256       g2.setStroke(new BasicStroke());
1257     }
1258   }
1259
1260   void drawBarGraph(Graphics g, AlignmentAnnotation _aa,
1261           Annotation[] aa_annotations, int sRes, int eRes, float min,
1262           float max, int y, boolean renderHistogram, boolean renderProfile,
1263           boolean normaliseProfile)
1264   {
1265     if (sRes > aa_annotations.length)
1266     {
1267       return;
1268     }
1269     Font ofont = g.getFont();
1270     eRes = Math.min(eRes, aa_annotations.length);
1271
1272     int x = 0, y1 = y, y2 = y;
1273
1274     float range = max - min;
1275
1276     if (min < 0)
1277     {
1278       y2 = y - (int) ((0 - min / (range)) * _aa.graphHeight);
1279     }
1280
1281     g.setColor(Color.gray);
1282
1283     g.drawLine(x, y2, (eRes - sRes) * charWidth, y2);
1284
1285     int column;
1286     int aaMax = aa_annotations.length - 1;
1287     while (x < eRes - sRes)
1288     {
1289       column = sRes + x;
1290       if (hasHiddenColumns)
1291       {
1292         column = columnSelection.adjustForHiddenColumns(column);
1293       }
1294
1295       if (column > aaMax)
1296       {
1297         break;
1298       }
1299
1300       if (aa_annotations[column] == null)
1301       {
1302         x++;
1303         continue;
1304       }
1305       if (aa_annotations[column].colour == null)
1306       {
1307         g.setColor(Color.black);
1308       }
1309       else
1310       {
1311         g.setColor(aa_annotations[column].colour);
1312       }
1313
1314       y1 = y
1315               - (int) (((aa_annotations[column].value - min) / (range)) * _aa.graphHeight);
1316
1317       if (renderHistogram)
1318       {
1319         if (y1 - y2 > 0)
1320         {
1321           g.fillRect(x * charWidth, y2, charWidth, y1 - y2);
1322         }
1323         else
1324         {
1325           g.fillRect(x * charWidth, y1, charWidth, y2 - y1);
1326         }
1327       }
1328       // draw profile if available
1329       if (renderProfile)
1330       {
1331
1332         /*
1333          * {profile type, #values, total count, char1, pct1, char2, pct2...}
1334          */
1335         int profl[] = getProfileFor(_aa, column);
1336
1337         // just try to draw the logo if profl is not null
1338         if (profl != null && profl[2] != 0)
1339         {
1340           boolean isStructureProfile = profl[0] == AlignmentAnnotation.STRUCTURE_PROFILE;
1341           boolean isCdnaProfile = profl[0] == AlignmentAnnotation.CDNA_PROFILE;
1342           float ht = normaliseProfile ? y - _aa.graphHeight : y1;
1343           double htn = normaliseProfile ? _aa.graphHeight : (y2 - y1);// aa.graphHeight;
1344           double hght;
1345           float wdth;
1346           double ht2 = 0;
1347           char[] dc;
1348
1349           /**
1350            * Render a single base for a sequence profile, a base pair for
1351            * structure profile, and a triplet for a cdna profile
1352            */
1353           dc = new char[isStructureProfile ? 2 : (isCdnaProfile ? 3 : 1)];
1354
1355           LineMetrics lm = g.getFontMetrics(ofont).getLineMetrics("Q", g);
1356           double scale = 1f / (normaliseProfile ? profl[2] : 100f);
1357           float ofontHeight = 1f / lm.getAscent();// magnify to fill box
1358           double scl = 0.0;
1359
1360           /*
1361            * Traverse the character(s)/percentage data in the array
1362            */
1363           int c = 3;
1364           int valuesProcessed = 0;
1365           // profl[1] is the number of values in the profile
1366           while (valuesProcessed < profl[1])
1367           {
1368             if (isStructureProfile)
1369             {
1370               // todo can we encode a structure pair as an int, like codons?
1371               dc[0] = (char) profl[c++];
1372               dc[1] = (char) profl[c++];
1373             }
1374             else if (isCdnaProfile)
1375             {
1376               dc = CodingUtils.decodeCodon(profl[c++]);
1377             }
1378             else
1379             {
1380               dc[0] = (char) profl[c++];
1381             }
1382
1383             wdth = charWidth;
1384             wdth /= fm.charsWidth(dc, 0, dc.length);
1385
1386             ht += scl;
1387             // next profl[] position is profile % for the character(s)
1388             scl = htn * scale * profl[c++];
1389             lm = ofont.getLineMetrics(dc, 0, 1, g.getFontMetrics()
1390                     .getFontRenderContext());
1391             Font font = ofont.deriveFont(AffineTransform.getScaleInstance(
1392                     wdth, scl / lm.getAscent()));
1393             g.setFont(font);
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[] { 5f, 3f }, 0f));
1437
1438       y2 = (int) (y - ((_aa.threshold.value - min) / range)
1439               * _aa.graphHeight);
1440       g.drawLine(0, y2, (eRes - sRes) * charWidth, y2);
1441       g2.setStroke(new BasicStroke());
1442     }
1443   }
1444
1445   // used by overview window
1446   public void drawGraph(Graphics g, AlignmentAnnotation _aa,
1447           Annotation[] aa_annotations, int width, int y, int sRes, int eRes)
1448   {
1449     eRes = Math.min(eRes, aa_annotations.length);
1450     g.setColor(Color.white);
1451     g.fillRect(0, 0, width, y);
1452     g.setColor(new Color(0, 0, 180));
1453
1454     int x = 0, height;
1455
1456     for (int j = sRes; j < eRes; j++)
1457     {
1458       if (aa_annotations[j] != null)
1459       {
1460         if (aa_annotations[j].colour == null)
1461         {
1462           g.setColor(Color.black);
1463         }
1464         else
1465         {
1466           g.setColor(aa_annotations[j].colour);
1467         }
1468
1469         height = (int) ((aa_annotations[j].value / _aa.graphMax) * y);
1470         if (height > y)
1471         {
1472           height = y;
1473         }
1474
1475         g.fillRect(x, y - height, charWidth, height);
1476       }
1477       x += charWidth;
1478     }
1479   }
1480
1481   Color getNotCanonicalColor(char lastss)
1482   {
1483     switch (lastss)
1484     {
1485     case '{':
1486     case '}':
1487       return new Color(255, 125, 5);
1488
1489     case '[':
1490     case ']':
1491       return new Color(245, 115, 10);
1492
1493     case '>':
1494     case '<':
1495       return new Color(235, 135, 15);
1496
1497     case 'A':
1498     case 'a':
1499       return new Color(225, 105, 20);
1500
1501     case 'B':
1502     case 'b':
1503       return new Color(215, 145, 30);
1504
1505     case 'C':
1506     case 'c':
1507       return new Color(205, 95, 35);
1508
1509     case 'D':
1510     case 'd':
1511       return new Color(195, 155, 45);
1512
1513     case 'E':
1514     case 'e':
1515       return new Color(185, 85, 55);
1516
1517     case 'F':
1518     case 'f':
1519       return new Color(175, 165, 65);
1520
1521     case 'G':
1522     case 'g':
1523       return new Color(170, 75, 75);
1524
1525     case 'H':
1526     case 'h':
1527       return new Color(160, 175, 85);
1528
1529     case 'I':
1530     case 'i':
1531       return new Color(150, 65, 95);
1532
1533     case 'J':
1534     case 'j':
1535       return new Color(140, 185, 105);
1536
1537     case 'K':
1538     case 'k':
1539       return new Color(130, 55, 110);
1540
1541     case 'L':
1542     case 'l':
1543       return new Color(120, 195, 120);
1544
1545     case 'M':
1546     case 'm':
1547       return new Color(110, 45, 130);
1548
1549     case 'N':
1550     case 'n':
1551       return new Color(100, 205, 140);
1552
1553     case 'O':
1554     case 'o':
1555       return new Color(90, 35, 150);
1556
1557     case 'P':
1558     case 'p':
1559       return new Color(85, 215, 160);
1560
1561     case 'Q':
1562     case 'q':
1563       return new Color(75, 25, 170);
1564
1565     case 'R':
1566     case 'r':
1567       return new Color(65, 225, 180);
1568
1569     case 'S':
1570     case 's':
1571       return new Color(55, 15, 185);
1572
1573     case 'T':
1574     case 't':
1575       return new Color(45, 235, 195);
1576
1577     case 'U':
1578     case 'u':
1579       return new Color(35, 5, 205);
1580
1581     case 'V':
1582     case 'v':
1583       return new Color(25, 245, 215);
1584
1585     case 'W':
1586     case 'w':
1587       return new Color(15, 0, 225);
1588
1589     case 'X':
1590     case 'x':
1591       return new Color(10, 255, 235);
1592
1593     case 'Y':
1594     case 'y':
1595       return new Color(5, 150, 245);
1596
1597     case 'Z':
1598     case 'z':
1599       return new Color(0, 80, 255);
1600
1601     default:
1602       System.out.println("This is not a interaction : " + lastss);
1603       return null;
1604
1605     }
1606   }
1607 }