JAL-1153 JAL-1155 improved layout and allowed labels to rescale for grouped linegraphs
[jalview.git] / src / jalview / gui / AnnotationLabels.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.gui;
19
20 import java.util.*;
21 import java.util.regex.Pattern;
22
23 import java.awt.*;
24 import java.awt.datatransfer.*;
25 import java.awt.event.*;
26 import java.awt.geom.AffineTransform;
27 import java.awt.image.*;
28 import javax.swing.*;
29
30 import jalview.datamodel.*;
31 import jalview.io.*;
32
33 /**
34  * DOCUMENT ME!
35  * 
36  * @author $author$
37  * @version $Revision$
38  */
39 public class AnnotationLabels extends JPanel implements MouseListener,
40         MouseMotionListener, ActionListener
41 {
42   static String TOGGLE_LABELSCALE = "Scale Label to Column";
43
44   static String ADDNEW = "Add New Row";
45
46   static String EDITNAME = "Edit Label/Description";
47
48   static String HIDE = "Hide This Row";
49
50   static String DELETE = "Delete This Row";
51
52   static String SHOWALL = "Show All Hidden Rows";
53
54   static String OUTPUT_TEXT = "Export Annotation";
55
56   static String COPYCONS_SEQ = "Copy Consensus Sequence";
57
58   boolean resizePanel = false;
59
60   Image image;
61
62   AlignmentPanel ap;
63
64   AlignViewport av;
65
66   boolean resizing = false;
67
68   MouseEvent dragEvent;
69
70   int oldY;
71
72   int selectedRow;
73
74   int scrollOffset = 0;
75
76   Font font = new Font("Arial", Font.PLAIN, 11);
77
78   private boolean hasHiddenRows;
79
80   /**
81    * Creates a new AnnotationLabels object.
82    * 
83    * @param ap
84    *          DOCUMENT ME!
85    */
86   public AnnotationLabels(AlignmentPanel ap)
87   {
88     this.ap = ap;
89     av = ap.av;
90     ToolTipManager.sharedInstance().registerComponent(this);
91
92     java.net.URL url = getClass().getResource("/images/idwidth.gif");
93     Image temp = null;
94
95     if (url != null)
96     {
97       temp = java.awt.Toolkit.getDefaultToolkit().createImage(url);
98     }
99
100     try
101     {
102       MediaTracker mt = new MediaTracker(this);
103       mt.addImage(temp, 0);
104       mt.waitForID(0);
105     } catch (Exception ex)
106     {
107     }
108
109     BufferedImage bi = new BufferedImage(temp.getHeight(this),
110             temp.getWidth(this), BufferedImage.TYPE_INT_RGB);
111     Graphics2D g = (Graphics2D) bi.getGraphics();
112     g.rotate(Math.toRadians(90));
113     g.drawImage(temp, 0, -bi.getWidth(this), this);
114     image = (Image) bi;
115
116     addMouseListener(this);
117     addMouseMotionListener(this);
118   }
119
120   public AnnotationLabels(AlignViewport av)
121   {
122     this.av = av;
123   }
124
125   /**
126    * DOCUMENT ME!
127    * 
128    * @param y
129    *          DOCUMENT ME!
130    */
131   public void setScrollOffset(int y)
132   {
133     scrollOffset = y;
134     repaint();
135   }
136
137   /**
138    * sets selectedRow to -2 if no annotation preset, -1 if no visible row is at
139    * y
140    * 
141    * @param y
142    *          coordinate position to search for a row
143    */
144   void getSelectedRow(int y)
145   {
146     int height = 0;
147     AlignmentAnnotation[] aa = ap.av.getAlignment().getAlignmentAnnotation();
148     selectedRow = -2;
149     if (aa != null)
150     {
151       for (int i = 0; i < aa.length; i++)
152       {
153         selectedRow = -1;
154         if (!aa[i].visible)
155         {
156           continue;
157         }
158
159         height += aa[i].height;
160
161         if (y < height)
162         {
163           selectedRow = i;
164
165           break;
166         }
167       }
168     }
169   }
170
171   /**
172    * DOCUMENT ME!
173    * 
174    * @param evt
175    *          DOCUMENT ME!
176    */
177   public void actionPerformed(ActionEvent evt)
178   {
179     AlignmentAnnotation[] aa = ap.av.getAlignment().getAlignmentAnnotation();
180
181     if (evt.getActionCommand().equals(ADDNEW))
182     {
183       AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
184               null, new Annotation[ap.av.getAlignment().getWidth()]);
185
186       if (!editLabelDescription(newAnnotation))
187       {
188         return;
189       }
190
191       ap.av.getAlignment().addAnnotation(newAnnotation);
192       ap.av.getAlignment().setAnnotationIndex(newAnnotation, 0);
193     }
194     else if (evt.getActionCommand().equals(EDITNAME))
195     {
196       editLabelDescription(aa[selectedRow]);
197       repaint();
198     }
199     else if (evt.getActionCommand().equals(HIDE))
200     {
201       aa[selectedRow].visible = false;
202     }
203     else if (evt.getActionCommand().equals(DELETE))
204     {
205       ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
206     }
207     else if (evt.getActionCommand().equals(SHOWALL))
208     {
209       for (int i = 0; i < aa.length; i++)
210       {
211         if (!aa[i].visible && aa[i].annotations != null)
212         {
213           aa[i].visible = true;
214         }
215       }
216     }
217     else if (evt.getActionCommand().equals(OUTPUT_TEXT))
218     {
219       new AnnotationExporter().exportAnnotations(ap,
220               new AlignmentAnnotation[]
221               { aa[selectedRow] }, null, null);
222     }
223     else if (evt.getActionCommand().equals(COPYCONS_SEQ))
224     {
225       SequenceI cons = null;
226       if (aa[selectedRow].groupRef != null)
227       {
228         cons = aa[selectedRow].groupRef.getConsensusSeq();
229       }
230       else
231       {
232         cons = av.getConsensusSeq();
233       }
234       if (cons != null)
235       {
236         copy_annotseqtoclipboard(cons);
237       }
238
239     }
240     else if (evt.getActionCommand().equals(TOGGLE_LABELSCALE))
241     {
242       aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
243     }
244
245     ap.validateAnnotationDimensions(false);
246     ap.addNotify();
247     ap.repaint();
248     //validate();
249     //ap.paintAlignment(true);
250   }
251
252   /**
253    * DOCUMENT ME!
254    * 
255    * @param e
256    *          DOCUMENT ME!
257    */
258   boolean editLabelDescription(AlignmentAnnotation annotation)
259   {
260     EditNameDialog dialog = new EditNameDialog(annotation.label,
261             annotation.description, "       Annotation Name ",
262             "Annotation Description ", "Edit Annotation Name/Description",
263             ap.alignFrame);
264
265     if (!dialog.accept)
266     {
267       return false;
268     }
269
270     annotation.label = dialog.getName();
271
272     String text = dialog.getDescription();
273     if (text != null && text.length() == 0)
274     {
275       text = null;
276     }
277     annotation.description = text;
278
279     return true;
280   }
281
282   /**
283    * DOCUMENT ME!
284    * 
285    * @param evt
286    *          DOCUMENT ME!
287    */
288   public void mousePressed(MouseEvent evt)
289   {
290     getSelectedRow(evt.getY() - scrollOffset);
291     oldY = evt.getY();
292   }
293
294   /**
295    * DOCUMENT ME!
296    * 
297    * @param evt
298    *          DOCUMENT ME!
299    */
300   public void mouseReleased(MouseEvent evt)
301   {
302     int start = selectedRow;
303     getSelectedRow(evt.getY() - scrollOffset);
304     int end = selectedRow;
305
306     if (start != end)
307     {
308       // Swap these annotations
309       AlignmentAnnotation startAA = ap.av.getAlignment()
310               .getAlignmentAnnotation()[start];
311       if (end == -1)
312       {
313         end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
314       }
315       AlignmentAnnotation endAA = ap.av.getAlignment().getAlignmentAnnotation()[end];
316
317       ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
318       ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
319     }
320
321     resizePanel = false;
322     dragEvent = null;
323     repaint();
324     ap.annotationPanel.repaint();
325   }
326
327   /**
328    * DOCUMENT ME!
329    * 
330    * @param evt
331    *          DOCUMENT ME!
332    */
333   public void mouseEntered(MouseEvent evt)
334   {
335     if (evt.getY() < 10)
336     {
337       resizePanel = true;
338       repaint();
339     }
340   }
341
342   /**
343    * DOCUMENT ME!
344    * 
345    * @param evt
346    *          DOCUMENT ME!
347    */
348   public void mouseExited(MouseEvent evt)
349   {
350     if (dragEvent == null)
351     {
352       resizePanel = false;
353       repaint();
354     }
355   }
356
357   /**
358    * DOCUMENT ME!
359    * 
360    * @param evt
361    *          DOCUMENT ME!
362    */
363   public void mouseDragged(MouseEvent evt)
364   {
365     dragEvent = evt;
366
367     if (resizePanel)
368     {
369       Dimension d = ap.annotationScroller.getPreferredSize();
370       int dif = evt.getY() - oldY;
371
372       dif /= ap.av.charHeight;
373       dif *= ap.av.charHeight;
374
375       if ((d.height - dif) > 20)
376       {
377         ap.annotationScroller.setPreferredSize(new Dimension(d.width,
378                 d.height - dif));
379         d = ap.annotationSpaceFillerHolder.getPreferredSize();
380         ap.annotationSpaceFillerHolder.setPreferredSize(new Dimension(
381                 d.width, d.height - dif));
382         ap.paintAlignment(true);
383       }
384
385       ap.addNotify();
386     }
387     else
388     {
389       repaint();
390     }
391   }
392
393   /**
394    * DOCUMENT ME!
395    * 
396    * @param evt
397    *          DOCUMENT ME!
398    */
399   public void mouseMoved(MouseEvent evt)
400   {
401     resizePanel = evt.getY() < 10;
402
403     getSelectedRow(evt.getY() - scrollOffset);
404
405     if (selectedRow > -1
406             && ap.av.getAlignment().getAlignmentAnnotation().length > selectedRow)
407     {
408       AlignmentAnnotation aa = ap.av.getAlignment().getAlignmentAnnotation()[selectedRow];
409       
410       StringBuffer desc = new StringBuffer();
411       if (aa.description != null
412               && !aa.description.equals("New description"))
413       {
414         // TODO: we could refactor and merge this code with the code in jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature tooltips
415         desc.append(aa.getDescription(true).trim());
416         // check to see if the description is an html fragment.
417         if (desc.length()<6 || (desc.substring(0,6).toLowerCase().indexOf("<html>")<0))
418         {
419           // clean the description ready for embedding in html
420           desc = new StringBuffer(Pattern.compile("<").matcher(desc).replaceAll("&lt;"));        
421           desc.insert(0, "<html>");
422         } else {
423                 // remove terminating html if any
424                 int i=desc.substring(desc.length()-7).toLowerCase().lastIndexOf("</html>");
425                 if (i>-1) {
426                   desc.setLength(desc.length()-7+i);
427                 }
428         }
429         if (aa.hasScore())
430         {
431           desc.append("<br/>");
432         }
433         
434         
435       } else {
436         // begin the tooltip's html fragment
437         desc.append("<html>");
438       }
439       if (aa.hasScore())
440       {
441         // TODO: limit precision of score to avoid noise from imprecise doubles (64.7 becomes 64.7+/some tiny value).
442         desc.append(" Score: " + aa.score);
443       }
444
445       if (desc.length() > 6)
446       {
447         desc.append("</html>");
448         this.setToolTipText(desc.toString());
449       }
450       else
451         this.setToolTipText(null);
452     }
453
454   }
455
456   /**
457    * DOCUMENT ME!
458    * 
459    * @param evt
460    *          DOCUMENT ME!
461    */
462   public void mouseClicked(MouseEvent evt)
463   {
464     AlignmentAnnotation[] aa = ap.av.getAlignment().getAlignmentAnnotation();
465     if (SwingUtilities.isLeftMouseButton(evt))
466     {
467       if (selectedRow > -1 && selectedRow < aa.length)
468       {
469         if (aa[selectedRow].groupRef != null)
470         {
471           if (evt.getClickCount() >= 2)
472           {
473             // todo: make the ap scroll to the selection - not necessary, first click highlights/scrolls, second selects
474             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
475             ap.av.setSelectionGroup(// new SequenceGroup(
476             aa[selectedRow].groupRef); // );
477             ap.paintAlignment(false);
478             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
479             ap.av.sendSelection();
480           }
481           else
482           {
483             ap.seqPanel.ap.idPanel
484                     .highlightSearchResults(aa[selectedRow].groupRef
485                             .getSequences(null));
486           }
487           return;
488         }
489         else if (aa[selectedRow].sequenceRef != null)
490         {
491           Vector sr = new Vector();
492           sr.addElement(aa[selectedRow].sequenceRef);
493           if (evt.getClickCount() == 1)
494           {
495             ap.seqPanel.ap.idPanel.highlightSearchResults(sr);
496           }
497           else if (evt.getClickCount() >= 2)
498           {
499             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
500             SequenceGroup sg = new SequenceGroup();
501             sg.addSequence(aa[selectedRow].sequenceRef, false);
502             ap.av.setSelectionGroup(sg);
503             ap.av.sendSelection();
504             ap.paintAlignment(false);
505             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
506           }
507
508         }
509       }
510     }
511     if (!SwingUtilities.isRightMouseButton(evt))
512     {
513       return;
514     }
515
516     JPopupMenu pop = new JPopupMenu("Annotations");
517     JMenuItem item = new JMenuItem(ADDNEW);
518     item.addActionListener(this);
519     pop.add(item);
520     if (selectedRow < 0)
521     {
522       if (hasHiddenRows)
523       { // let the user make everything visible again
524         item = new JMenuItem(SHOWALL);
525         item.addActionListener(this);
526         pop.add(item);
527       }
528       pop.show(this, evt.getX(), evt.getY());
529       return;
530     }
531     item = new JMenuItem(EDITNAME);
532     item.addActionListener(this);
533     pop.add(item);
534     item = new JMenuItem(HIDE);
535     item.addActionListener(this);
536     pop.add(item);
537     item = new JMenuItem(DELETE);
538     item.addActionListener(this);
539     pop.add(item);
540     if (hasHiddenRows)
541     {
542       item = new JMenuItem(SHOWALL);
543       item.addActionListener(this);
544       pop.add(item);
545     }
546     item = new JMenuItem(OUTPUT_TEXT);
547     item.addActionListener(this);
548     pop.add(item);
549     // TODO: annotation object should be typed for autocalculated/derived
550     // property methods
551     if (selectedRow < aa.length)
552     {
553       if (!aa[selectedRow].autoCalculated)
554       {
555         if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
556         {
557           // display formatting settings for this row.
558           pop.addSeparator();
559           // av and sequencegroup need to implement same interface for
560           item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
561                   aa[selectedRow].scaleColLabel);
562           item.addActionListener(this);
563           pop.add(item);
564         }
565       }
566       else if (aa[selectedRow].label.indexOf("Consensus") > -1)
567       {
568         pop.addSeparator();
569         // av and sequencegroup need to implement same interface for
570         final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
571                 "Ignore Gaps In Consensus",
572                 (aa[selectedRow].groupRef != null) ? aa[selectedRow].groupRef
573                         .getIgnoreGapsConsensus() : ap.av
574                         .getIgnoreGapsConsensus());
575         final AlignmentAnnotation aaa = aa[selectedRow];
576         cbmi.addActionListener(new ActionListener()
577         {
578           public void actionPerformed(ActionEvent e)
579           {
580             if (aaa.groupRef != null)
581             {
582               // TODO: pass on reference to ap so the view can be updated.
583               aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
584               ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
585             }
586             else
587             {
588               ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
589             }
590           }
591         });
592         pop.add(cbmi);
593         // av and sequencegroup need to implement same interface for
594         if (aaa.groupRef != null)
595         {
596           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
597                   "Show Group Histogram",
598                   aa[selectedRow].groupRef.isShowConsensusHistogram());
599           chist.addActionListener(new ActionListener()
600           {
601             public void actionPerformed(ActionEvent e)
602             {
603               // TODO: pass on reference
604               // to ap
605               // so the
606               // view
607               // can be
608               // updated.
609               aaa.groupRef.setShowConsensusHistogram(chist.getState());
610               ap.repaint();
611               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
612             }
613           });
614           pop.add(chist);
615           final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
616                   "Show Group Logo",
617                   aa[selectedRow].groupRef.isShowSequenceLogo());
618           cprofl.addActionListener(new ActionListener()
619           {
620             public void actionPerformed(ActionEvent e)
621             {
622               // TODO: pass on reference
623               // to ap
624               // so the
625               // view
626               // can be
627               // updated.
628               aaa.groupRef.setshowSequenceLogo(cprofl.getState());
629               ap.repaint();
630               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
631             }
632           });
633           pop.add(cprofl);
634           final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
635                   "Normalise Group Logo",
636                   aa[selectedRow].groupRef.isNormaliseSequenceLogo());
637           cproflnorm.addActionListener(new ActionListener()
638           {
639             public void actionPerformed(ActionEvent e)
640             {
641               
642               // TODO: pass on reference
643               // to ap
644               // so the
645               // view
646               // can be
647               // updated.
648               aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
649               // automatically enable logo display if we're clicked
650               aaa.groupRef.setshowSequenceLogo(true);
651               ap.repaint();
652               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
653             }
654           });
655           pop.add(cproflnorm);
656         }
657         else
658         {
659           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
660                   "Show Histogram", av.isShowConsensusHistogram());
661           chist.addActionListener(new ActionListener()
662           {
663             public void actionPerformed(ActionEvent e)
664             {
665               // TODO: pass on reference
666               // to ap
667               // so the
668               // view
669               // can be
670               // updated.
671               av.setShowConsensusHistogram(chist.getState());
672               ap.alignFrame.setMenusForViewport();
673               ap.repaint();
674               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
675             }
676           });
677           pop.add(chist);
678           final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
679                   "Show Logo", av.isShowSequenceLogo());
680           cprof.addActionListener(new ActionListener()
681           {
682             public void actionPerformed(ActionEvent e)
683             {
684               // TODO: pass on reference
685               // to ap
686               // so the
687               // view
688               // can be
689               // updated.
690               av.setShowSequenceLogo(cprof.getState());
691               ap.alignFrame.setMenusForViewport();
692               ap.repaint();
693               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
694             }
695           });
696           pop.add(cprof);
697           final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
698                   "Normalise Logo", av.isNormaliseSequenceLogo());
699           cprofnorm.addActionListener(new ActionListener()
700           {
701             public void actionPerformed(ActionEvent e)
702             {
703               // TODO: pass on reference
704               // to ap
705               // so the
706               // view
707               // can be
708               // updated.
709               av.setShowSequenceLogo(true);
710               av.setNormaliseSequenceLogo(cprofnorm.getState());
711               ap.alignFrame.setMenusForViewport();
712               ap.repaint();
713               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
714             }
715           });
716           pop.add(cprofnorm);
717         }
718         final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
719         consclipbrd.addActionListener(this);
720         pop.add(consclipbrd);
721       }
722     }
723     pop.show(this, evt.getX(), evt.getY());
724   }
725
726   /**
727    * do a single sequence copy to jalview and the system clipboard
728    * 
729    * @param sq
730    *          sequence to be copied to clipboard
731    */
732   protected void copy_annotseqtoclipboard(SequenceI sq)
733   {
734     SequenceI[] seqs = new SequenceI[]
735     { sq };
736     String[] omitHidden = null;
737     SequenceI[] dseqs = new SequenceI[]
738     { sq.getDatasetSequence() };
739     if (dseqs[0] == null)
740     {
741       dseqs[0] = new Sequence(sq);
742       dseqs[0].setSequence(jalview.analysis.AlignSeq.extractGaps(
743               jalview.util.Comparison.GapChars, sq.getSequenceAsString()));
744
745       sq.setDatasetSequence(dseqs[0]);
746     }
747     Alignment ds = new Alignment(dseqs);
748     if (av.hasHiddenColumns())
749     {
750       omitHidden = av.getColumnSelection().getVisibleSequenceStrings(0,
751               sq.getLength(), seqs);
752     }
753
754     String output = new FormatAdapter().formatSequences("Fasta", seqs,
755             omitHidden);
756
757     Toolkit.getDefaultToolkit().getSystemClipboard()
758             .setContents(new StringSelection(output), Desktop.instance);
759
760     Vector hiddenColumns = null;
761     if (av.hasHiddenColumns())
762     {
763       hiddenColumns = new Vector();
764       for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
765       {
766         int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
767                 .elementAt(i);
768
769         hiddenColumns.addElement(new int[]
770         { region[0], region[1] });
771       }
772     }
773
774     Desktop.jalviewClipboard = new Object[]
775     { seqs, ds, // what is the dataset of a consensus sequence ? need to flag
776         // sequence as special.
777         hiddenColumns };
778   }
779
780   /**
781    * DOCUMENT ME!
782    * 
783    * @param g1
784    *          DOCUMENT ME!
785    */
786   public void paintComponent(Graphics g)
787   {
788
789     int width = getWidth();
790     if (width == 0)
791     {
792       width = ap.calculateIdWidth().width + 4;
793     }
794
795     Graphics2D g2 = (Graphics2D) g;
796     if (av.antiAlias)
797     {
798       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
799               RenderingHints.VALUE_ANTIALIAS_ON);
800     }
801
802     drawComponent(g2, width);
803
804   }
805
806   /**
807    * DOCUMENT ME!
808    * 
809    * @param g
810    *          DOCUMENT ME!
811    */
812   public void drawComponent(Graphics g, int width)
813   {
814     if (av.getFont().getSize() < 10)
815     {
816       g.setFont(font);
817     }
818     else
819     {
820       g.setFont(av.getFont());
821     }
822
823     FontMetrics fm = g.getFontMetrics(g.getFont());
824     g.setColor(Color.white);
825     g.fillRect(0, 0, getWidth(), getHeight());
826
827     g.translate(0, scrollOffset);
828     g.setColor(Color.black);
829
830     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
831     int fontHeight = g.getFont().getSize();
832     int y = 0;
833     int x = 0;
834     int graphExtras = 0;
835     int offset = 0;
836     Font baseFont = g.getFont();
837     FontMetrics baseMetrics = fm;
838     int ofontH = fontHeight;
839     boolean visible = true;
840     if (aa != null)
841     {
842       hasHiddenRows = false;
843       for (int i = 0; i < aa.length; i++)
844       {
845         visible = true;
846         g.setColor(Color.black);
847
848         if (!aa[i].visible)
849         {
850           hasHiddenRows = true;
851           continue;
852         }
853
854         y += aa[i].height;
855
856         offset = -aa[i].height / 2;
857
858         if (aa[i].hasText)
859         {
860           offset += fm.getHeight() / 2;
861           offset -= fm.getDescent();
862         }
863         else
864           offset += fm.getDescent();
865
866         x = width - fm.stringWidth(aa[i].label) - 3;
867
868         if (aa[i].graphGroup > -1)
869         {
870           int groupSize = 0;
871           for (int gg = 0; gg < aa.length; gg++)
872           {
873             if (aa[gg].graphGroup == aa[i].graphGroup)
874             {
875               groupSize++;
876             }
877           }
878           if (groupSize * (fontHeight + 8) < aa[i].height)
879           {
880             graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
881           }
882           else
883           {
884             // scale font to fit
885             float h = aa[i].height / (float) groupSize, s;
886             if (h < 9)
887             {
888               visible = false;
889             }
890             else
891             {
892               fontHeight = -8 + (int) h;
893               s = ((float) fontHeight) / (float) ofontH;
894               Font f = baseFont.deriveFont(AffineTransform
895                       .getScaleInstance(s, s));
896               g.setFont(f);
897               fm = g.getFontMetrics();
898               graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
899             }
900           }
901           if (visible)
902           {
903             for (int gg = 0; gg < aa.length; gg++)
904             {
905               if (aa[gg].graphGroup == aa[i].graphGroup)
906               {
907                 x = width - fm.stringWidth(aa[gg].label) - 3;
908                 g.drawString(aa[gg].label, x, y - graphExtras);
909                 
910                 if (aa[gg]._linecolour != null)
911                 {
912
913                   g.setColor(aa[gg]._linecolour);
914                   g.drawLine(x, y - graphExtras + 3,
915                           x + fm.stringWidth(aa[gg].label), y - graphExtras
916                                   + 3);
917                 }
918
919                 g.setColor(Color.black);
920                 graphExtras += fontHeight + 8;
921               }
922             }
923           }
924           g.setFont(baseFont);
925           fm = baseMetrics;
926           fontHeight = ofontH;
927         }
928         else
929         {
930           g.drawString(aa[i].label, x, y + offset);
931         }
932       }
933     }
934
935     if (resizePanel)
936     {
937       g.drawImage(image, 2, 0 - scrollOffset, this);
938     }
939     else if (dragEvent != null && aa != null)
940     {
941       g.setColor(Color.lightGray);
942       g.drawString(aa[selectedRow].label, dragEvent.getX(),
943               dragEvent.getY() - scrollOffset);
944     }
945
946     if ((aa == null) || (aa.length < 1))
947     {
948       g.drawString("Right click", 2, 8);
949       g.drawString("to add annotation", 2, 18);
950     }
951   }
952 }