bugfix for redraw when AlignPanel partially constructed. group autoannotation and...
[jalview.git] / src / jalview / gui / AnnotationPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3  * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import java.awt.*;
22 import java.awt.event.*;
23 import java.awt.font.LineMetrics;
24 import java.awt.geom.AffineTransform;
25 import java.awt.image.*;
26 import java.util.Hashtable;
27
28 import javax.swing.*;
29
30 import jalview.analysis.AAFrequency;
31 import jalview.datamodel.*;
32 import jalview.schemes.ColourSchemeI;
33
34 /**
35  * DOCUMENT ME!
36  * 
37  * @author $author$
38  * @version $Revision$
39  */
40 public class AnnotationPanel extends JPanel implements MouseListener,
41         MouseMotionListener, ActionListener, AdjustmentListener
42 {
43   final String HELIX = "Helix";
44
45   final String SHEET = "Sheet";
46
47   final String LABEL = "Label";
48
49   final String REMOVE = "Remove Annotation";
50
51   final String COLOUR = "Colour";
52
53   final Color HELIX_COLOUR = Color.red.darker();
54
55   final Color SHEET_COLOUR = Color.green.darker().darker();
56
57   /** DOCUMENT ME!! */
58   AlignViewport av;
59
60   AlignmentPanel ap;
61
62   int activeRow = -1;
63
64   BufferedImage image;
65
66   BufferedImage fadedImage;
67
68   Graphics2D gg;
69
70   FontMetrics fm;
71
72   int imgWidth = 0;
73
74   boolean fastPaint = false;
75
76   // Used For mouse Dragging and resizing graphs
77   int graphStretch = -1;
78
79   int graphStretchY = -1;
80
81   int min; // used by mouseDragged to see if user
82
83   int max; // used by mouseDragged to see if user
84
85   boolean mouseDragging = false;
86
87   boolean MAC = false;
88
89   /**
90    * Creates a new AnnotationPanel object.
91    * 
92    * @param ap
93    *                DOCUMENT ME!
94    */
95   public AnnotationPanel(AlignmentPanel ap)
96   {
97
98     MAC = new jalview.util.Platform().isAMac();
99
100     ToolTipManager.sharedInstance().registerComponent(this);
101     ToolTipManager.sharedInstance().setInitialDelay(0);
102     ToolTipManager.sharedInstance().setDismissDelay(10000);
103     this.ap = ap;
104     av = ap.av;
105     this.setLayout(null);
106     addMouseListener(this);
107     addMouseMotionListener(this);
108     ap.annotationScroller.getVerticalScrollBar()
109             .addAdjustmentListener(this);
110   }
111
112   public AnnotationPanel(AlignViewport av)
113   {
114     this.av = av;
115   }
116
117   /**
118    * DOCUMENT ME!
119    * 
120    * @param evt
121    *                DOCUMENT ME!
122    */
123   public void adjustmentValueChanged(AdjustmentEvent evt)
124   {
125     ap.alabels.setScrollOffset(-evt.getValue());
126   }
127
128   /**
129    * Calculates the height of the annotation displayed in the annotation panel. 
130    * Callers should normally call the ap.adjustAnnotationHeight method to ensure all
131    * annotation associated components are updated correctly.
132    *  
133    */
134   public int adjustPanelHeight()
135   {
136     // setHeight of panels
137     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
138     int height = 0;
139
140     if (aa != null)
141     {
142       for (int i = 0; i < aa.length; i++)
143       {
144         if (aa[i]==null)
145         {
146           System.err.println("Null annotation row: ignoring.");
147           continue;
148         }
149         if (!aa[i].visible)
150         {
151           continue;
152         }
153
154         aa[i].height = 0;
155
156         if (aa[i].hasText)
157         {
158           aa[i].height += av.charHeight;
159         }
160
161         if (aa[i].hasIcons)
162         {
163           aa[i].height += 16;
164         }
165
166         if (aa[i].graph > 0)
167         {
168           aa[i].height += aa[i].graphHeight;
169         }
170
171         if (aa[i].height == 0)
172         {
173           aa[i].height = 20;
174         }
175
176         height += aa[i].height;
177       }
178     }
179     else
180     {
181       height = 20;
182     }
183
184     this.setPreferredSize(new Dimension(1, height));
185     if (ap!=null)
186     {
187       // revalidate only when the alignment panel is fully constructed
188       ap.validate();
189     }
190
191     return height;
192   }
193
194   /**
195    * DOCUMENT ME!
196    * 
197    * @param evt
198    *                DOCUMENT ME!
199    */
200   public void actionPerformed(ActionEvent evt)
201   {
202     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
203     Annotation[] anot = aa[activeRow].annotations;
204
205     if (anot.length < av.getColumnSelection().getMax())
206     {
207       Annotation[] temp = new Annotation[av.getColumnSelection().getMax() + 2];
208       System.arraycopy(anot, 0, temp, 0, anot.length);
209       anot = temp;
210       aa[activeRow].annotations = anot;
211     }
212
213     if (evt.getActionCommand().equals(REMOVE))
214     {
215       for (int i = 0; i < av.getColumnSelection().size(); i++)
216       {
217         anot[av.getColumnSelection().columnAt(i)] = null;
218       }
219     }
220     else if (evt.getActionCommand().equals(LABEL))
221     {
222       String exMesg = collectAnnotVals(anot, av.getColumnSelection(), LABEL);
223       String label = JOptionPane.showInputDialog(this, "Enter label",
224               exMesg);
225
226       if (label == null)
227       {
228         return;
229       }
230
231       if ((label.length() > 0) && !aa[activeRow].hasText)
232       {
233         aa[activeRow].hasText = true;
234       }
235
236       for (int i = 0; i < av.getColumnSelection().size(); i++)
237       {
238         int index = av.getColumnSelection().columnAt(i);
239
240         if (!av.colSel.isVisible(index))
241           continue;
242
243         if (anot[index] == null)
244         {
245           anot[index] = new Annotation(label, "", ' ', 0); // TODO: verify that
246                                                             // null exceptions
247                                                             // aren't raised
248                                                             // elsewhere.
249         }
250         else
251         {
252           anot[index].displayCharacter = label;
253         }
254       }
255     }
256     else if (evt.getActionCommand().equals(COLOUR))
257     {
258       Color col = JColorChooser.showDialog(this,
259               "Choose foreground colour", Color.black);
260
261       for (int i = 0; i < av.getColumnSelection().size(); i++)
262       {
263         int index = av.getColumnSelection().columnAt(i);
264
265         if (!av.colSel.isVisible(index))
266           continue;
267
268         if (anot[index] == null)
269         {
270           anot[index] = new Annotation("", "", ' ', 0);
271         }
272
273         anot[index].colour = col;
274       }
275     }
276     else
277     // HELIX OR SHEET
278     {
279       char type = 0;
280       String symbol = "\u03B1";
281
282       if (evt.getActionCommand().equals(HELIX))
283       {
284         type = 'H';
285       }
286       else if (evt.getActionCommand().equals(SHEET))
287       {
288         type = 'E';
289         symbol = "\u03B2";
290       }
291
292       if (!aa[activeRow].hasIcons)
293       {
294         aa[activeRow].hasIcons = true;
295       }
296
297       String label = JOptionPane.showInputDialog(
298               "Enter a label for the structure?", symbol);
299
300       if (label == null)
301       {
302         return;
303       }
304
305       if ((label.length() > 0) && !aa[activeRow].hasText)
306       {
307         aa[activeRow].hasText = true;
308       }
309
310       for (int i = 0; i < av.getColumnSelection().size(); i++)
311       {
312         int index = av.getColumnSelection().columnAt(i);
313
314         if (!av.colSel.isVisible(index))
315           continue;
316
317         if (anot[index] == null)
318         {
319           anot[index] = new Annotation(label, "", type, 0);
320         }
321
322         anot[index].secondaryStructure = type;
323         anot[index].displayCharacter = label;
324       }
325     }
326
327     adjustPanelHeight();
328     repaint();
329
330     return;
331   }
332
333   private String collectAnnotVals(Annotation[] anot,
334           ColumnSelection columnSelection, String label2)
335   {
336     String collatedInput = "";
337     String last = "";
338     for (int i = 0; i < columnSelection.size(); i++)
339     {
340       int index = columnSelection.columnAt(i);
341       // always check for current display state - just in case
342       if (!av.colSel.isVisible(index))
343         continue;
344       String tlabel = null;
345       if (anot[index] != null)
346       {
347         if (label2.equals(HELIX) || label2.equals(SHEET)
348                 || label2.equals(LABEL))
349         {
350           tlabel = anot[index].description;
351           if (tlabel == null || tlabel.length()<1)
352           {
353             if (label2.equals(HELIX) || label2.equals(SHEET))
354             {
355               tlabel = "" + anot[index].secondaryStructure;
356             }
357             else
358             {
359               tlabel = "" + anot[index].displayCharacter;
360             }
361           }
362         }
363         if (tlabel != null && !tlabel.equals(last))
364         {
365           if (last.length() > 0)
366           {
367             collatedInput += " ";
368           }
369           collatedInput += tlabel;
370         }
371       }
372     }
373     return collatedInput;
374   }
375
376   /**
377    * DOCUMENT ME!
378    * 
379    * @param evt
380    *                DOCUMENT ME!
381    */
382   public void mousePressed(MouseEvent evt)
383   {
384
385     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
386     if (aa == null)
387     {
388       return;
389     }
390
391     int height = 0;
392     activeRow = -1;
393
394     for (int i = 0; i < aa.length; i++)
395     {
396       if (aa[i].visible)
397       {
398         height += aa[i].height;
399       }
400
401       if (evt.getY() < height)
402       {
403         if (aa[i].editable)
404         {
405           activeRow = i;
406         }
407         else if (aa[i].graph > 0)
408         {
409           // Stretch Graph
410           graphStretch = i;
411           graphStretchY = evt.getY();
412         }
413
414         break;
415       }
416     }
417
418     if (SwingUtilities.isRightMouseButton(evt) && activeRow != -1)
419     {
420       if (av.getColumnSelection() == null)
421       {
422         return;
423       }
424
425       JPopupMenu pop = new JPopupMenu("Structure type");
426       JMenuItem item = new JMenuItem(HELIX);
427       item.addActionListener(this);
428       pop.add(item);
429       item = new JMenuItem(SHEET);
430       item.addActionListener(this);
431       pop.add(item);
432       item = new JMenuItem(LABEL);
433       item.addActionListener(this);
434       pop.add(item);
435       item = new JMenuItem(COLOUR);
436       item.addActionListener(this);
437       pop.add(item);
438       item = new JMenuItem(REMOVE);
439       item.addActionListener(this);
440       pop.add(item);
441       pop.show(this, evt.getX(), evt.getY());
442
443       return;
444     }
445
446     if (aa == null)
447     {
448       return;
449     }
450
451     ap.scalePanel.mousePressed(evt);
452
453   }
454
455   /**
456    * DOCUMENT ME!
457    * 
458    * @param evt
459    *                DOCUMENT ME!
460    */
461   public void mouseReleased(MouseEvent evt)
462   {
463     graphStretch = -1;
464     graphStretchY = -1;
465     mouseDragging = false;
466     ap.scalePanel.mouseReleased(evt);
467   }
468
469   /**
470    * DOCUMENT ME!
471    * 
472    * @param evt
473    *                DOCUMENT ME!
474    */
475   public void mouseEntered(MouseEvent evt)
476   {
477     ap.scalePanel.mouseEntered(evt);
478   }
479
480   /**
481    * DOCUMENT ME!
482    * 
483    * @param evt
484    *                DOCUMENT ME!
485    */
486   public void mouseExited(MouseEvent evt)
487   {
488     ap.scalePanel.mouseExited(evt);
489   }
490
491   /**
492    * DOCUMENT ME!
493    * 
494    * @param evt
495    *                DOCUMENT ME!
496    */
497   public void mouseDragged(MouseEvent evt)
498   {
499     if (graphStretch > -1)
500     {
501       av.alignment.getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
502               - evt.getY();
503       if (av.alignment.getAlignmentAnnotation()[graphStretch].graphHeight < 0)
504       {
505         av.alignment.getAlignmentAnnotation()[graphStretch].graphHeight = 0;
506       }
507       graphStretchY = evt.getY();
508       adjustPanelHeight();
509       ap.paintAlignment(true);
510     }
511     else
512     {
513       ap.scalePanel.mouseDragged(evt);
514     }
515   }
516
517   /**
518    * DOCUMENT ME!
519    * 
520    * @param evt
521    *                DOCUMENT ME!
522    */
523   public void mouseMoved(MouseEvent evt)
524   {
525     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
526
527     if (aa == null)
528     {
529       this.setToolTipText(null);
530       return;
531     }
532
533     int row = -1;
534     int height = 0;
535
536     for (int i = 0; i < aa.length; i++)
537     {
538       if (aa[i].visible)
539       {
540         height += aa[i].height;
541       }
542
543       if (evt.getY() < height)
544       {
545         row = i;
546
547         break;
548       }
549     }
550
551     if (row == -1)
552     {
553       this.setToolTipText(null);
554       return;
555     }
556
557     int res = (evt.getX() / av.getCharWidth()) + av.getStartRes();
558
559     if (av.hasHiddenColumns)
560     {
561       res = av.getColumnSelection().adjustForHiddenColumns(res);
562     }
563
564     if (aa[row].annotations != null && row > -1
565             && res < (int) aa[row].annotations.length)
566     {
567       if (aa[row].graphGroup > -1)
568       {
569         StringBuffer tip = new StringBuffer("<html>");
570         for (int gg = 0; gg < aa.length; gg++)
571         {
572           if (aa[gg].graphGroup == aa[row].graphGroup
573                   && aa[gg].annotations[res] != null)
574           {
575             tip.append(aa[gg].label + " "
576                     + aa[gg].annotations[res].description + "<br>");
577           }
578         }
579         if (tip.length() != 6)
580         {
581           tip.setLength(tip.length() - 4);
582           this.setToolTipText(tip.toString() + "</html>");
583         }
584       }
585       else if (aa[row].annotations[res] != null
586               && aa[row].annotations[res].description != null)
587       {
588         this.setToolTipText(aa[row].annotations[res].description);
589       }
590
591       if (aa[row].annotations[res] != null)
592       {
593         StringBuffer text = new StringBuffer("Sequence position "
594                 + (res + 1));
595
596         if (aa[row].annotations[res].description != null)
597         {
598           text.append("  " + aa[row].annotations[res].description);
599         }
600
601         ap.alignFrame.statusBar.setText(text.toString());
602       }
603     }
604     else
605     {
606       this.setToolTipText(null);
607     }
608   }
609
610   /**
611    * DOCUMENT ME!
612    * 
613    * @param evt
614    *                DOCUMENT ME!
615    */
616   public void mouseClicked(MouseEvent evt)
617   {
618   }
619
620   /**
621    * DOCUMENT ME!
622    * 
623    * @param g
624    *                DOCUMENT ME!
625    */
626   public void paintComponent(Graphics g)
627   {
628     g.setColor(Color.white);
629     g.fillRect(0, 0, getWidth(), getHeight());
630
631     if (image != null)
632     {
633       if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
634               || (getVisibleRect().height != g.getClipBounds().height))
635       {
636         g.drawImage(image, 0, 0, this);
637         fastPaint = false;
638         return;
639       }
640     }
641     imgWidth = (av.endRes - av.startRes + 1) * av.charWidth;
642     if (imgWidth < 1)
643       return;
644     if (image == null || imgWidth != image.getWidth()
645             || image.getHeight(this) != getHeight())
646     {
647       image = new BufferedImage(imgWidth, ap.annotationPanel.getHeight(),
648               BufferedImage.TYPE_INT_RGB);
649       gg = (Graphics2D) image.getGraphics();
650
651       if (av.antiAlias)
652       {
653         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
654                 RenderingHints.VALUE_ANTIALIAS_ON);
655       }
656
657       gg.setFont(av.getFont());
658       fm = gg.getFontMetrics();
659       gg.setColor(Color.white);
660       gg.fillRect(0, 0, imgWidth, image.getHeight());
661     }
662
663     drawComponent(gg, av.startRes, av.endRes + 1);
664     g.drawImage(image, 0, 0, this);
665   }
666
667   /**
668    * non-Thread safe repaint
669    * 
670    * @param horizontal
671    *                repaint with horizontal shift in alignment
672    */
673   public void fastPaint(int horizontal)
674   {
675
676     if ((horizontal == 0) || gg == null
677             || av.alignment.getAlignmentAnnotation() == null
678             || av.alignment.getAlignmentAnnotation().length < 1
679             || av.updatingConsensus || av.updatingConservation)
680     {
681       repaint();
682       return;
683     }
684     gg.copyArea(0, 0, imgWidth, getHeight(), -horizontal * av.charWidth, 0);
685
686     int sr = av.startRes;
687     int er = av.endRes + 1;
688     int transX = 0;
689
690     if (horizontal > 0) // scrollbar pulled right, image to the left
691     {
692       transX = (er - sr - horizontal) * av.charWidth;
693       sr = er - horizontal;
694     }
695     else if (horizontal < 0)
696     {
697       er = sr - horizontal;
698     }
699
700     gg.translate(transX, 0);
701
702     drawComponent(gg, sr, er);
703
704     gg.translate(-transX, 0);
705
706     fastPaint = true;
707     repaint();
708
709   }
710
711   /**
712    * DOCUMENT ME!
713    * 
714    * @param g
715    *                DOCUMENT ME!
716    * @param startRes
717    *                DOCUMENT ME!
718    * @param endRes
719    *                DOCUMENT ME!
720    */
721   public void drawComponent(Graphics g, int startRes, int endRes)
722   {
723     if (av.updatingConsensus || av.updatingConservation)
724     {
725       if (image == null)
726       {
727         return;
728       }
729       // We'll keep a record of the old image,
730       // and draw a faded image until the calculation
731       // has completed
732       if (fadedImage == null || fadedImage.getWidth() != imgWidth
733               || fadedImage.getHeight() != image.getHeight())
734       {
735         fadedImage = new BufferedImage(imgWidth, image.getHeight(),
736                 BufferedImage.TYPE_INT_RGB);
737
738         Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
739
740         fadedG.setColor(Color.white);
741         fadedG.fillRect(0, 0, imgWidth, image.getHeight());
742
743         fadedG.setComposite(AlphaComposite.getInstance(
744                 AlphaComposite.SRC_OVER, .3f));
745         fadedG.drawImage(image, 0, 0, this);
746
747       }
748
749     }
750     else
751     {
752       fadedImage = null;
753     }
754
755     g.setColor(Color.white);
756     g.fillRect(0, 0, (endRes - startRes) * av.charWidth, getHeight());
757
758     g.setFont(av.getFont());
759     if (fm == null)
760     {
761       fm = g.getFontMetrics();
762     }
763
764     if ((av.alignment.getAlignmentAnnotation() == null)
765             || (av.alignment.getAlignmentAnnotation().length < 1))
766     {
767       g.setColor(Color.white);
768       g.fillRect(0, 0, getWidth(), getHeight());
769       g.setColor(Color.black);
770       if (av.validCharWidth)
771       {
772         g.drawString("Alignment has no annotations", 20, 15);
773       }
774
775       return;
776     }
777
778     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
779
780     int x = 0, y = 0;
781     int column = 0;
782     char lastSS;
783     int lastSSX;
784     int iconOffset = 0;
785     boolean validRes = false;
786     boolean validEnd = false;
787     boolean labelAllCols = false;
788     boolean centreColLabels,centreColLabelsDef = av.getCentreColumnLabels();
789     boolean scaleColLabel=false;
790     boolean[] graphGroupDrawn = new boolean[aa.length];
791     int charOffset = 0; // offset for a label
792     float fmWidth, fmScaling = 1f; // scaling for a label to fit it into a column.
793     Font ofont = g.getFont();
794     // \u03B2 \u03B1
795     for (int i = 0; i < aa.length; i++)
796     {
797       AlignmentAnnotation row = aa[i];
798
799       if (!row.visible)
800       {
801         continue;
802       }
803       centreColLabels = row.centreColLabels || centreColLabelsDef;
804       labelAllCols = row.showAllColLabels;
805       scaleColLabel = row.scaleColLabel;
806       lastSS = ' ';
807       lastSSX = 0;
808
809       if (row.graph > 0)
810       {
811         if (row.graphGroup > -1 && graphGroupDrawn[row.graphGroup])
812         {
813           continue;
814         }
815
816         // this is so that we draw the characters below the graph
817         y += row.height;
818
819         if (row.hasText)
820         {
821           iconOffset = av.charHeight - fm.getDescent();
822           y -= av.charHeight;
823         }
824       }
825       else if (row.hasText)
826       {
827         iconOffset = av.charHeight - fm.getDescent();
828
829       }
830       else
831       {
832         iconOffset = 0;
833       }
834
835       if (av.updatingConsensus && aa[i] == av.consensus)
836       {
837         y += av.charHeight;
838
839         g.drawImage(fadedImage, 0, y - row.height, imgWidth, y, 0, y
840                 - row.height, imgWidth, y, this);
841         g.setColor(Color.black);
842         // g.drawString("Calculating Consensus....",20, y-row.height/2);
843
844         continue;
845       }
846       else if (av.updatingConservation
847               && aa[i].label.equals("Conservation"))
848       {
849
850         y += av.charHeight;
851         g.drawImage(fadedImage, 0, y - row.height, imgWidth, y, 0, y
852                 - row.height, imgWidth, y, this);
853
854         g.setColor(Color.black);
855         // g.drawString("Calculating Conservation.....",20, y-row.height/2);
856
857         continue;
858       }
859       else if (av.updatingConservation && aa[i].label.equals("Quality"))
860       {
861
862         y += av.charHeight;
863         g.drawImage(fadedImage, 0, y - row.height, imgWidth, y, 0, y
864                 - row.height, imgWidth, y, this);
865         g.setColor(Color.black);
866         // / g.drawString("Calculating Quality....",20, y-row.height/2);
867
868         continue;
869       }
870
871       x = 0;
872       while (x < endRes - startRes)
873       {
874         if (av.hasHiddenColumns)
875         {
876           column = av.getColumnSelection().adjustForHiddenColumns(
877                   startRes + x);
878           if (column > row.annotations.length - 1)
879           {
880             break;
881           }
882         }
883         else
884         {
885           column = startRes + x;
886         }
887
888         if ((row.annotations == null) || (row.annotations.length <= column)
889                 || (row.annotations[column] == null))
890         {
891           validRes = false;
892         }
893         else
894         {
895           validRes = true;
896         }
897
898         if (activeRow == i)
899         {
900           g.setColor(Color.red);
901
902           if (av.getColumnSelection() != null)
903           {
904             for (int n = 0; n < av.getColumnSelection().size(); n++)
905             {
906               int v = av.getColumnSelection().columnAt(n);
907
908               if (v == column)
909               {
910                 g
911                         .fillRect(x * av.charWidth, y, av.charWidth,
912                                 av.charHeight);
913               }
914             }
915           }
916         }
917
918         if (av.validCharWidth && validRes
919                 && row.annotations[column].displayCharacter != null
920                 && (row.annotations[column].displayCharacter.length() > 0))
921         {
922           
923           if (centreColLabels || scaleColLabel)
924           {
925             fmWidth = (float) fm
926             .charsWidth(row.annotations[column].displayCharacter
927                     .toCharArray(), 0,
928                     row.annotations[column].displayCharacter.length());
929
930             if ( scaleColLabel ) { 
931               // justify the label and scale to fit in column
932               if (fmWidth > av.charWidth) {
933                 // scale only if the current font isn't already small enough
934                 fmScaling = av.charWidth;
935                 fmScaling /= fmWidth;
936                 g.setFont(ofont.deriveFont(AffineTransform.getScaleInstance(fmScaling, 1.0)));
937                 // and update the label's width to reflect the scaling.
938                 fmWidth = av.charWidth;
939               }
940             }
941           } else {
942             fmWidth = (float) fm
943             .charWidth(row.annotations[column].displayCharacter.charAt(0));
944           }
945           charOffset =  (int) ((av.charWidth - fmWidth) / 2f);
946           
947           if (row.annotations[column].colour == null)
948             g.setColor(Color.black);
949           else
950             g.setColor(row.annotations[column].colour);
951
952           if (column == 0 || row.graph > 0)
953           {
954             g.drawString(row.annotations[column].displayCharacter,
955                     (x * av.charWidth) + charOffset, y + iconOffset);
956           }
957           else if (row.annotations[column - 1] == null
958                   || (labelAllCols||!row.annotations[column].displayCharacter
959                           .equals(row.annotations[column - 1].displayCharacter) || (row.annotations[column].displayCharacter
960                           .length() < 2 && row.annotations[column].secondaryStructure == ' ')))
961           {
962             g.drawString(row.annotations[column].displayCharacter, x
963                     * av.charWidth + charOffset, y + iconOffset);
964           }
965           g.setFont(ofont);
966         }
967
968         if (row.hasIcons)
969         {
970           if (!validRes
971                   || (row.annotations[column].secondaryStructure != lastSS))
972           {
973             switch (lastSS)
974             {
975             case 'H':
976               g.setColor(HELIX_COLOUR);
977               if (MAC)
978               {
979                 // Off by 1 offset when drawing rects and ovals
980                 // to offscreen image on the MAC
981                 g.fillRoundRect(lastSSX, y + 4 + iconOffset,
982                         (x * av.charWidth) - lastSSX, 7, 8, 8);
983                 break;
984               }
985
986               int sCol = (lastSSX / av.charWidth) + startRes;
987               int x1 = lastSSX;
988               int x2 = (x * av.charWidth);
989
990               if (sCol == 0
991                       || row.annotations[sCol - 1] == null
992                       || row.annotations[sCol - 1].secondaryStructure != 'H')
993               {
994                 g.fillArc(lastSSX, y + 4 + iconOffset, av.charWidth, 8, 90,
995                         180);
996                 x1 += av.charWidth / 2;
997               }
998
999               if (!validRes || row.annotations[column] == null
1000                       || row.annotations[column].secondaryStructure != 'H')
1001               {
1002                 g.fillArc((x * av.charWidth) - av.charWidth, y + 4
1003                         + iconOffset, av.charWidth, 8, 270, 180);
1004                 x2 -= av.charWidth / 2;
1005               }
1006
1007               g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 8);
1008               break;
1009
1010             case 'E':
1011               g.setColor(SHEET_COLOUR);
1012               g.fillRect(lastSSX, y + 4 + iconOffset, (x * av.charWidth)
1013                       - lastSSX - 4, 7);
1014               g.fillPolygon(new int[]
1015               { (x * av.charWidth) - 4, (x * av.charWidth) - 4,
1016                   (x * av.charWidth) }, new int[]
1017               { y + iconOffset, y + 14 + iconOffset, y + 8 + iconOffset },
1018                       3);
1019
1020               break;
1021
1022             default:
1023               g.setColor(Color.gray);
1024               g.fillRect(lastSSX, y + 6 + iconOffset, (x * av.charWidth)
1025                       - lastSSX, 2);
1026
1027               break;
1028             }
1029
1030             if (validRes)
1031             {
1032               lastSS = row.annotations[column].secondaryStructure;
1033             }
1034             else
1035             {
1036               lastSS = ' ';
1037             }
1038
1039             lastSSX = (x * av.charWidth);
1040           }
1041         }
1042
1043         column++;
1044         x++;
1045       }
1046
1047       if (column >= row.annotations.length)
1048       {
1049         column = row.annotations.length - 1;
1050         validEnd = false;
1051       }
1052       else
1053       {
1054         validEnd = true;
1055       }
1056
1057       // x ++;
1058
1059       if (row.hasIcons)
1060       {
1061         switch (lastSS)
1062         {
1063         case 'H':
1064           g.setColor(HELIX_COLOUR);
1065           if (MAC)
1066           {
1067             // Off by 1 offset when drawing rects and ovals
1068             // to offscreen image on the MAC
1069             g.fillRoundRect(lastSSX, y + 4 + iconOffset, (x * av.charWidth)
1070                     - lastSSX, 7, 8, 8);
1071             break;
1072           }
1073
1074           int sCol = (lastSSX / av.charWidth) + startRes;
1075           int x1 = lastSSX;
1076           int x2 = (x * av.charWidth);
1077
1078           if (sCol == 0 || row.annotations[sCol - 1] == null
1079                   || row.annotations[sCol - 1].secondaryStructure != 'H')
1080           {
1081             g
1082                     .fillArc(lastSSX, y + 4 + iconOffset, av.charWidth, 8,
1083                             90, 180);
1084             x1 += av.charWidth / 2;
1085           }
1086
1087           if (row.annotations[column] == null
1088                   || row.annotations[column].secondaryStructure != 'H')
1089           {
1090             g.fillArc((x * av.charWidth) - av.charWidth,
1091                     y + 4 + iconOffset, av.charWidth, 8, 270, 180);
1092             x2 -= av.charWidth / 2;
1093           }
1094
1095           g.fillRect(x1, y + 4 + iconOffset, x2 - x1, 8);
1096
1097           break;
1098
1099         case 'E':
1100           g.setColor(SHEET_COLOUR);
1101
1102           if (!validEnd || row.annotations[endRes] == null
1103                   || row.annotations[endRes].secondaryStructure != 'E')
1104           {
1105             g.fillRect(lastSSX, y + 4 + iconOffset, (x * av.charWidth)
1106                     - lastSSX - 4, 7);
1107             g.fillPolygon(new int[]
1108             { (x * av.charWidth) - 4, (x * av.charWidth) - 4,
1109                 (x * av.charWidth) }, new int[]
1110             { y + iconOffset, y + 14 + iconOffset, y + 7 + iconOffset }, 3);
1111           }
1112           else
1113           {
1114             g.fillRect(lastSSX, y + 4 + iconOffset, (x + 1) * av.charWidth
1115                     - lastSSX, 7);
1116           }
1117           break;
1118
1119         default:
1120           g.setColor(Color.gray);
1121           g.fillRect(lastSSX, y + 6 + iconOffset, (x * av.charWidth)
1122                   - lastSSX, 2);
1123
1124           break;
1125         }
1126       }
1127
1128       if (row.graph > 0 && row.graphHeight > 0)
1129       {
1130         if (row.graph == AlignmentAnnotation.LINE_GRAPH)
1131         {
1132           if (row.graphGroup > -1 && !graphGroupDrawn[row.graphGroup])
1133           {
1134             float groupmax = -999999, groupmin = 9999999;
1135             for (int gg = 0; gg < aa.length; gg++)
1136             {
1137               if (aa[gg].graphGroup != row.graphGroup)
1138               {
1139                 continue;
1140               }
1141
1142               if (aa[gg] != row)
1143               {
1144                 aa[gg].visible = false;
1145               }
1146
1147               if (aa[gg].graphMax > groupmax)
1148               {
1149                 groupmax = aa[gg].graphMax;
1150               }
1151               if (aa[gg].graphMin < groupmin)
1152               {
1153                 groupmin = aa[gg].graphMin;
1154               }
1155             }
1156
1157             for (int gg = 0; gg < aa.length; gg++)
1158             {
1159               if (aa[gg].graphGroup == row.graphGroup)
1160               {
1161                 drawLineGraph(g, aa[gg], startRes, endRes, y, groupmin,
1162                         groupmax, row.graphHeight);
1163               }
1164             }
1165
1166             graphGroupDrawn[row.graphGroup] = true;
1167           }
1168           else
1169           {
1170             drawLineGraph(g, row, startRes, endRes, y, row.graphMin,
1171                     row.graphMax, row.graphHeight);
1172           }
1173         }
1174         else if (row.graph == AlignmentAnnotation.BAR_GRAPH)
1175         {
1176           drawBarGraph(g, row, startRes, endRes, row.graphMin,
1177                   row.graphMax, y);
1178         }
1179       }
1180
1181       if (row.graph > 0 && row.hasText)
1182       {
1183         y += av.charHeight;
1184       }
1185
1186       if (row.graph == 0)
1187       {
1188         y += aa[i].height;
1189       }
1190     }
1191   }
1192
1193   public void drawLineGraph(Graphics g, AlignmentAnnotation aa, int sRes,
1194           int eRes, int y, float min, float max, int graphHeight)
1195   {
1196     if (sRes > aa.annotations.length)
1197     {
1198       return;
1199     }
1200
1201     int x = 0;
1202
1203     // Adjustment for fastpaint to left
1204     if (eRes < av.endRes)
1205     {
1206       eRes++;
1207     }
1208
1209     eRes = Math.min(eRes, aa.annotations.length);
1210
1211     if (sRes == 0)
1212     {
1213       x++;
1214     }
1215
1216     int y1 = y, y2 = y;
1217     float range = max - min;
1218
1219     // //Draw origin
1220     if (min < 0)
1221     {
1222       y2 = y - (int) ((0 - min / range) * graphHeight);
1223     }
1224
1225     g.setColor(Color.gray);
1226     g.drawLine(x - av.charWidth, y2, (eRes - sRes + 1) * av.charWidth, y2);
1227
1228     eRes = Math.min(eRes, aa.annotations.length);
1229
1230     int column;
1231     int aaMax = aa.annotations.length - 1;
1232
1233     while (x < eRes - sRes)
1234     {
1235       column = sRes + x;
1236       if (av.hasHiddenColumns)
1237       {
1238         column = av.getColumnSelection().adjustForHiddenColumns(column);
1239       }
1240
1241       if (column > aaMax)
1242       {
1243         break;
1244       }
1245
1246       if (aa.annotations[column] == null
1247               || aa.annotations[column - 1] == null)
1248       {
1249         x++;
1250         continue;
1251       }
1252
1253       if (aa.annotations[column].colour == null)
1254         g.setColor(Color.black);
1255       else
1256         g.setColor(aa.annotations[column].colour);
1257
1258       y1 = y
1259               - (int) (((aa.annotations[column - 1].value - min) / range) * graphHeight);
1260       y2 = y
1261               - (int) (((aa.annotations[column].value - min) / range) * graphHeight);
1262
1263       g.drawLine(x * av.charWidth - av.charWidth / 2, y1, x * av.charWidth
1264               + av.charWidth / 2, y2);
1265       x++;
1266     }
1267
1268     if (aa.threshold != null)
1269     {
1270       g.setColor(aa.threshold.colour);
1271       Graphics2D g2 = (Graphics2D) g;
1272       g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
1273               BasicStroke.JOIN_ROUND, 3f, new float[]
1274               { 5f, 3f }, 0f));
1275
1276       y2 = (int) (y - ((aa.threshold.value - min) / range) * graphHeight);
1277       g.drawLine(0, y2, (eRes - sRes) * av.charWidth, y2);
1278       g2.setStroke(new BasicStroke());
1279     }
1280   }
1281
1282   public void drawBarGraph(Graphics g, AlignmentAnnotation aa, int sRes,
1283           int eRes, float min, float max, int y)
1284   {
1285     ColourSchemeI profcolour = av.getGlobalColourScheme();
1286     if (profcolour==null)
1287     {
1288       profcolour = new jalview.schemes.ZappoColourScheme();
1289     }
1290     if (sRes > aa.annotations.length)
1291     {
1292       return;
1293     }
1294     Font ofont = g.getFont();
1295     eRes = Math.min(eRes, aa.annotations.length);
1296
1297     int x = 0, y1 = y, y2 = y;
1298
1299     float range = max - min;
1300
1301     if (min < 0)
1302     {
1303       y2 = y - (int) ((0 - min / (range)) * aa.graphHeight);
1304     }
1305
1306     g.setColor(Color.gray);
1307
1308     g.drawLine(x, y2, (eRes - sRes) * av.charWidth, y2);
1309
1310     int column;
1311     int aaMax = aa.annotations.length - 1;
1312     boolean renderHistogram = true, renderProfile = true;
1313     if (aa.autoCalculated && aa.label.startsWith("Consensus")) {
1314       // TODO: generalise this to have render styles for consensus/profile data 
1315       if (aa.groupRef!=null)
1316       {
1317         renderHistogram = aa.groupRef.isShowConsensusHistogram();
1318         renderProfile = aa.groupRef.isIncludeAllConsSymbols();
1319       } else {
1320         renderHistogram = av.isShowConsensusHistogram();
1321         renderProfile = av.isShowConsensusProfile();
1322       }
1323     }
1324     while (x < eRes - sRes)
1325     {
1326       column = sRes + x;
1327       if (av.hasHiddenColumns)
1328       {
1329         column = av.getColumnSelection().adjustForHiddenColumns(column);
1330       }
1331
1332       if (column > aaMax)
1333       {
1334         break;
1335       }
1336
1337       if (aa.annotations[column] == null)
1338       {
1339         x++;
1340         continue;
1341       }
1342       if (aa.annotations[column].colour == null)
1343         g.setColor(Color.black);
1344       else
1345         g.setColor(aa.annotations[column].colour);
1346
1347       y1 = y
1348               - (int) (((aa.annotations[column].value - min) / (range)) * aa.graphHeight);
1349
1350       if (renderHistogram)
1351       {      
1352         if (y1 - y2 > 0)
1353       {
1354         g.fillRect(x * av.charWidth, y2, av.charWidth, y1 - y2);
1355       }
1356       else
1357       {
1358         g.fillRect(x * av.charWidth, y1, av.charWidth, y2 - y1);
1359       }
1360       }
1361       // draw profile if available
1362       if (aa.annotations[column].value!=0 && renderProfile)
1363       {
1364         int profl[] = getProfileFor(aa,column);
1365         int ht = y1,htn=y2-y1;//aa.graphHeight;
1366           float wdth;
1367           double ht2=0;
1368           char[] dc = new char[1];
1369           LineMetrics lm;
1370           for (int c=1;profl!=null && c<profl[0];)
1371           {
1372             dc[0] = (char) profl[c++];
1373             wdth = av.charWidth;
1374             wdth/=(float) fm
1375                     .charsWidth(dc,0,1);
1376             
1377             if (c>2)
1378             {
1379               ht+=(int)ht2;
1380             }
1381             {
1382               //if (aa.annotations[column].value==0) {
1383               //  g.setFont(ofont.deriveFont(AffineTransform.getScaleInstance(wdth, (ht2=(aa.graphHeight*0.1/av.charHeight)))));
1384               //  ht = y2-(int)ht2;
1385               //} else {
1386                 g.setFont(ofont.deriveFont(AffineTransform.getScaleInstance(wdth, (ht2=(htn*((double)profl[c++])/100.0))/av.charHeight)));
1387                 lm = g.getFontMetrics().getLineMetrics(dc,0,1, g);
1388                 //htn -=ht2;
1389               //}
1390               g.setColor(profcolour.findColour(dc[0])); // (av.globalColourScheme!=null) ? );// try to get a colourscheme for the group(aa.groupRef.cs==null) ? av.textColour2 : cs.findColour(dc));
1391               g.drawChars(dc,0,1,x*av.charWidth, (int) (ht+lm.getHeight()));
1392               // ht+=g.getFontMetrics().getAscent()-g.getFontMetrics().getDescent();
1393             }
1394           }
1395           g.setFont(ofont);
1396       }
1397       x++;
1398     }
1399     if (aa.threshold != null)
1400     {
1401       g.setColor(aa.threshold.colour);
1402       Graphics2D g2 = (Graphics2D) g;
1403       g2.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE,
1404               BasicStroke.JOIN_ROUND, 3f, new float[]
1405               { 5f, 3f }, 0f));
1406
1407       y2 = (int) (y - ((aa.threshold.value - min) / range) * aa.graphHeight);
1408       g.drawLine(0, y2, (eRes - sRes) * av.charWidth, y2);
1409       g2.setStroke(new BasicStroke());
1410     }
1411   }
1412
1413   private int[] getProfileFor(AlignmentAnnotation aa, int column)
1414   {
1415     if (aa.autoCalculated && aa.label.startsWith("Consensus")) {
1416     if (aa.groupRef!=null && aa.groupRef.consensusData!=null && aa.groupRef.isIncludeAllConsSymbols()) {
1417       return AAFrequency.extractProfile(aa.groupRef.consensusData[column],aa.groupRef.getIgnoreGapsConsensus());
1418     }
1419     // TODO extend annotation row to enable dynamic and static profile data to be stored  
1420     if (aa.groupRef==null && aa.sequenceRef==null && av.isShowConsensusProfile())
1421     {
1422       return AAFrequency.extractProfile(av.hconsensus[column],av.getIgnoreGapsConsensus());
1423     }
1424     }
1425     return null;
1426   }
1427
1428   // used by overview window
1429   public void drawGraph(Graphics g, AlignmentAnnotation aa, int width,
1430           int y, int sRes, int eRes)
1431   {
1432     eRes = Math.min(eRes, aa.annotations.length);
1433     g.setColor(Color.white);
1434     g.fillRect(0, 0, width, y);
1435     g.setColor(new Color(0, 0, 180));
1436
1437     int x = 0, height;
1438
1439     for (int j = sRes; j < eRes; j++)
1440     {
1441       if (aa.annotations[j] != null)
1442       {
1443         if (aa.annotations[j].colour == null)
1444           g.setColor(Color.black);
1445         else
1446           g.setColor(aa.annotations[j].colour);
1447
1448         height = (int) ((aa.annotations[j].value / aa.graphMax) * y);
1449         if (height > y)
1450         {
1451           height = y;
1452         }
1453
1454         g.fillRect(x, y - height, av.charWidth, height);
1455       }
1456       x += av.charWidth;
1457     }
1458   }
1459
1460 }