Merge branch 'bug/JAL-689' into Release_2_8_2_Branch
[jalview.git] / src / jalview / gui / AnnotationLabels.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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.gui;
22
23 import jalview.datamodel.Alignment;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.Annotation;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceGroup;
28 import jalview.datamodel.SequenceI;
29 import jalview.io.FormatAdapter;
30 import jalview.util.MessageManager;
31
32 import java.awt.Color;
33 import java.awt.Dimension;
34 import java.awt.Font;
35 import java.awt.FontMetrics;
36 import java.awt.Graphics;
37 import java.awt.Graphics2D;
38 import java.awt.Image;
39 import java.awt.MediaTracker;
40 import java.awt.RenderingHints;
41 import java.awt.Toolkit;
42 import java.awt.datatransfer.StringSelection;
43 import java.awt.event.ActionEvent;
44 import java.awt.event.ActionListener;
45 import java.awt.event.MouseEvent;
46 import java.awt.event.MouseListener;
47 import java.awt.event.MouseMotionListener;
48 import java.awt.geom.AffineTransform;
49 import java.awt.image.BufferedImage;
50 import java.util.Arrays;
51 import java.util.Vector;
52 import java.util.regex.Pattern;
53
54 import javax.swing.JCheckBoxMenuItem;
55 import javax.swing.JMenuItem;
56 import javax.swing.JPanel;
57 import javax.swing.JPopupMenu;
58 import javax.swing.SwingUtilities;
59 import javax.swing.ToolTipManager;
60
61 /**
62  * DOCUMENT ME!
63  * 
64  * @author $author$
65  * @version $Revision$
66  */
67 public class AnnotationLabels extends JPanel implements MouseListener,
68         MouseMotionListener, ActionListener
69 {
70   String TOGGLE_LABELSCALE = MessageManager.getString("label.scale_label_to_column");
71
72   String ADDNEW = MessageManager.getString("label.add_new_row");
73
74   String EDITNAME = MessageManager.getString("label.edit_label_description");
75
76   String HIDE = MessageManager.getString("label.hide_row");
77
78   String DELETE = MessageManager.getString("label.delete_row");
79
80   String SHOWALL = MessageManager.getString("label.show_all_hidden_rows");
81
82   String OUTPUT_TEXT = MessageManager.getString("label.export_annotation");
83
84   String COPYCONS_SEQ = MessageManager.getString("label.copy_consensus_sequence");
85
86   boolean resizePanel = false;
87
88   Image image;
89
90   AlignmentPanel ap;
91
92   AlignViewport av;
93
94   boolean resizing = false;
95
96   MouseEvent dragEvent;
97
98   int oldY;
99
100   int selectedRow;
101
102   int scrollOffset = 0;
103
104   Font font = new Font("Arial", Font.PLAIN, 11);
105
106   private boolean hasHiddenRows;
107
108   /**
109    * Creates a new AnnotationLabels object.
110    * 
111    * @param ap
112    *          DOCUMENT ME!
113    */
114   public AnnotationLabels(AlignmentPanel ap)
115   {
116     this.ap = ap;
117     av = ap.av;
118     ToolTipManager.sharedInstance().registerComponent(this);
119
120     java.net.URL url = getClass().getResource("/images/idwidth.gif");
121     Image temp = null;
122
123     if (url != null)
124     {
125       temp = java.awt.Toolkit.getDefaultToolkit().createImage(url);
126     }
127
128     try
129     {
130       MediaTracker mt = new MediaTracker(this);
131       mt.addImage(temp, 0);
132       mt.waitForID(0);
133     } catch (Exception ex)
134     {
135     }
136
137     BufferedImage bi = new BufferedImage(temp.getHeight(this),
138             temp.getWidth(this), BufferedImage.TYPE_INT_RGB);
139     Graphics2D g = (Graphics2D) bi.getGraphics();
140     g.rotate(Math.toRadians(90));
141     g.drawImage(temp, 0, -bi.getWidth(this), this);
142     image = bi;
143
144     addMouseListener(this);
145     addMouseMotionListener(this);
146     addMouseWheelListener(ap.annotationPanel);
147   }
148
149   public AnnotationLabels(AlignViewport av)
150   {
151     this.av = av;
152   }
153
154   /**
155    * DOCUMENT ME!
156    * 
157    * @param y
158    *          DOCUMENT ME!
159    */
160   public void setScrollOffset(int y)
161   {
162     scrollOffset = y;
163     repaint();
164   }
165
166   /**
167    * sets selectedRow to -2 if no annotation preset, -1 if no visible row is at
168    * y
169    * 
170    * @param y
171    *          coordinate position to search for a row
172    */
173   void getSelectedRow(int y)
174   {
175     int height = 0;
176     AlignmentAnnotation[] aa = ap.av.getAlignment()
177             .getAlignmentAnnotation();
178     selectedRow = -2;
179     if (aa != null)
180     {
181       for (int i = 0; i < aa.length; i++)
182       {
183         selectedRow = -1;
184         if (!aa[i].visible)
185         {
186           continue;
187         }
188
189         height += aa[i].height;
190
191         if (y < height)
192         {
193           selectedRow = i;
194
195           break;
196         }
197       }
198     }
199   }
200
201   /**
202    * DOCUMENT ME!
203    * 
204    * @param evt
205    *          DOCUMENT ME!
206    */
207   public void actionPerformed(ActionEvent evt)
208   {
209     AlignmentAnnotation[] aa = ap.av.getAlignment()
210             .getAlignmentAnnotation();
211
212     if (evt.getActionCommand().equals(ADDNEW))
213     {
214       AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
215               null, new Annotation[ap.av.getAlignment().getWidth()]);
216
217       if (!editLabelDescription(newAnnotation))
218       {
219         return;
220       }
221
222       ap.av.getAlignment().addAnnotation(newAnnotation);
223       ap.av.getAlignment().setAnnotationIndex(newAnnotation, 0);
224     }
225     else if (evt.getActionCommand().equals(EDITNAME))
226     {
227       editLabelDescription(aa[selectedRow]);
228       repaint();
229     }
230     else if (evt.getActionCommand().equals(HIDE))
231     {
232       aa[selectedRow].visible = false;
233     }
234     else if (evt.getActionCommand().equals(DELETE))
235     {
236       ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
237     }
238     else if (evt.getActionCommand().equals(SHOWALL))
239     {
240       for (int i = 0; i < aa.length; i++)
241       {
242         if (!aa[i].visible && aa[i].annotations != null)
243         {
244           aa[i].visible = true;
245         }
246       }
247     }
248     else if (evt.getActionCommand().equals(OUTPUT_TEXT))
249     {
250       new AnnotationExporter().exportAnnotations(ap,
251               new AlignmentAnnotation[]
252               { aa[selectedRow] }, null, null);
253     }
254     else if (evt.getActionCommand().equals(COPYCONS_SEQ))
255     {
256       SequenceI cons = null;
257       if (aa[selectedRow].groupRef != null)
258       {
259         cons = aa[selectedRow].groupRef.getConsensusSeq();
260       }
261       else
262       {
263         cons = av.getConsensusSeq();
264       }
265       if (cons != null)
266       {
267         copy_annotseqtoclipboard(cons);
268       }
269
270     }
271     else if (evt.getActionCommand().equals(TOGGLE_LABELSCALE))
272     {
273       aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
274     }
275
276     refresh();
277
278   }
279
280   /**
281    * Redraw sensibly.
282    */
283   protected void refresh()
284   {
285     ap.validateAnnotationDimensions(false);
286     ap.addNotify();
287     ap.repaint();
288   }
289
290   /**
291    * DOCUMENT ME!
292    * 
293    * @param e
294    *          DOCUMENT ME!
295    */
296   boolean editLabelDescription(AlignmentAnnotation annotation)
297   {
298     EditNameDialog dialog = new EditNameDialog(annotation.label,
299             annotation.description, "       Annotation Name ",
300             "Annotation Description ", "Edit Annotation Name/Description",
301             ap.alignFrame);
302
303     if (!dialog.accept)
304     {
305       return false;
306     }
307
308     annotation.label = dialog.getName();
309
310     String text = dialog.getDescription();
311     if (text != null && text.length() == 0)
312     {
313       text = null;
314     }
315     annotation.description = text;
316
317     return true;
318   }
319
320   /**
321    * DOCUMENT ME!
322    * 
323    * @param evt
324    *          DOCUMENT ME!
325    */
326   public void mousePressed(MouseEvent evt)
327   {
328     getSelectedRow(evt.getY() - scrollOffset);
329     oldY = evt.getY();
330   }
331
332   /**
333    * DOCUMENT ME!
334    * 
335    * @param evt
336    *          DOCUMENT ME!
337    */
338   public void mouseReleased(MouseEvent evt)
339   {
340     int start = selectedRow;
341     getSelectedRow(evt.getY() - scrollOffset);
342     int end = selectedRow;
343
344     if (start != end)
345     {
346       // Swap these annotations
347       AlignmentAnnotation startAA = ap.av.getAlignment()
348               .getAlignmentAnnotation()[start];
349       if (end == -1)
350       {
351         end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
352       }
353       AlignmentAnnotation endAA = ap.av.getAlignment()
354               .getAlignmentAnnotation()[end];
355
356       ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
357       ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
358     }
359
360     resizePanel = false;
361     dragEvent = null;
362     repaint();
363     ap.annotationPanel.repaint();
364   }
365
366   /**
367    * DOCUMENT ME!
368    * 
369    * @param evt
370    *          DOCUMENT ME!
371    */
372   public void mouseEntered(MouseEvent evt)
373   {
374     if (evt.getY() < 10)
375     {
376       resizePanel = true;
377       repaint();
378     }
379   }
380
381   /**
382    * DOCUMENT ME!
383    * 
384    * @param evt
385    *          DOCUMENT ME!
386    */
387   public void mouseExited(MouseEvent evt)
388   {
389     if (dragEvent == null)
390     {
391       resizePanel = false;
392       repaint();
393     }
394   }
395
396   /**
397    * DOCUMENT ME!
398    * 
399    * @param evt
400    *          DOCUMENT ME!
401    */
402   public void mouseDragged(MouseEvent evt)
403   {
404     dragEvent = evt;
405
406     if (resizePanel)
407     {
408       Dimension d = ap.annotationScroller.getPreferredSize();
409       int dif = evt.getY() - oldY;
410
411       dif /= ap.av.charHeight;
412       dif *= ap.av.charHeight;
413
414       if ((d.height - dif) > 20)
415       {
416         ap.annotationScroller.setPreferredSize(new Dimension(d.width,
417                 d.height - dif));
418         d = ap.annotationSpaceFillerHolder.getPreferredSize();
419         ap.annotationSpaceFillerHolder.setPreferredSize(new Dimension(
420                 d.width, d.height - dif));
421         ap.paintAlignment(true);
422       }
423
424       ap.addNotify();
425     }
426     else
427     {
428       repaint();
429     }
430   }
431
432   /**
433    * DOCUMENT ME!
434    * 
435    * @param evt
436    *          DOCUMENT ME!
437    */
438   public void mouseMoved(MouseEvent evt)
439   {
440     resizePanel = evt.getY() < 10;
441
442     getSelectedRow(evt.getY() - scrollOffset);
443
444     if (selectedRow > -1
445             && ap.av.getAlignment().getAlignmentAnnotation().length > selectedRow)
446     {
447       AlignmentAnnotation aa = ap.av.getAlignment()
448               .getAlignmentAnnotation()[selectedRow];
449
450       StringBuffer desc = new StringBuffer();
451       if (aa.description != null
452               && !aa.description.equals("New description"))
453       {
454         // TODO: we could refactor and merge this code with the code in
455         // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
456         // tooltips
457         desc.append(aa.getDescription(true).trim());
458         // check to see if the description is an html fragment.
459         if (desc.length() < 6
460                 || (desc.substring(0, 6).toLowerCase().indexOf("<html>") < 0))
461         {
462           // clean the description ready for embedding in html
463           desc = new StringBuffer(Pattern.compile("<").matcher(desc)
464                   .replaceAll("&lt;"));
465           desc.insert(0, "<html>");
466         }
467         else
468         {
469           // remove terminating html if any
470           int i = desc.substring(desc.length() - 7).toLowerCase()
471                   .lastIndexOf("</html>");
472           if (i > -1)
473           {
474             desc.setLength(desc.length() - 7 + i);
475           }
476         }
477         if (aa.hasScore())
478         {
479           desc.append("<br/>");
480         }
481
482       }
483       else
484       {
485         // begin the tooltip's html fragment
486         desc.append("<html>");
487       }
488       if (aa.hasScore())
489       {
490         // TODO: limit precision of score to avoid noise from imprecise doubles
491         // (64.7 becomes 64.7+/some tiny value).
492         desc.append(" Score: " + aa.score);
493       }
494
495       if (desc.length() > 6)
496       {
497         desc.append("</html>");
498         this.setToolTipText(desc.toString());
499       }
500       else
501       {
502         this.setToolTipText(null);
503       }
504     }
505
506   }
507
508   /**
509    * DOCUMENT ME!
510    * 
511    * @param evt
512    *          DOCUMENT ME!
513    */
514   public void mouseClicked(MouseEvent evt)
515   {
516     final AlignmentAnnotation[] aa = ap.av.getAlignment()
517             .getAlignmentAnnotation();
518     if (SwingUtilities.isLeftMouseButton(evt))
519     {
520       if (selectedRow > -1 && selectedRow < aa.length)
521       {
522         if (aa[selectedRow].groupRef != null)
523         {
524           if (evt.getClickCount() >= 2)
525           {
526             // todo: make the ap scroll to the selection - not necessary, first
527             // click highlights/scrolls, second selects
528             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
529             ap.av.setSelectionGroup(// new SequenceGroup(
530             aa[selectedRow].groupRef); // );
531             ap.paintAlignment(false);
532             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
533             ap.av.sendSelection();
534           }
535           else
536           {
537             ap.seqPanel.ap.idPanel
538                     .highlightSearchResults(aa[selectedRow].groupRef
539                             .getSequences(null));
540           }
541           return;
542         }
543         else if (aa[selectedRow].sequenceRef != null)
544         {
545           if (evt.getClickCount() == 1)
546           {
547             ap.seqPanel.ap.idPanel.highlightSearchResults(Arrays
548                     .asList(new SequenceI[]
549                     { aa[selectedRow].sequenceRef }));
550           }
551           else if (evt.getClickCount() >= 2)
552           {
553             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
554             SequenceGroup sg = ap.av.getSelectionGroup();
555             if (sg!=null)
556             {
557               // we make a copy rather than edit the current selection if no modifiers pressed
558               // see Enhancement JAL-1557
559               if (!(evt.isControlDown() || evt.isShiftDown()))
560               {
561                 sg = new SequenceGroup(sg);
562                 sg.clear();
563                 sg.addSequence(aa[selectedRow].sequenceRef, false);
564               } else {
565                 if (evt.isControlDown())
566                 {
567                   sg.addOrRemove(aa[selectedRow].sequenceRef, true);
568                 } else {
569                   // notionally, we should also add intermediate sequences from last added sequence ?
570                   sg.addSequence(aa[selectedRow].sequenceRef, true);
571                 }
572               }
573             } else {
574               sg = new SequenceGroup();
575               sg.setStartRes(0);
576               sg.setEndRes(ap.av.getAlignment().getWidth()-1);
577               sg.addSequence(aa[selectedRow].sequenceRef, false);
578             }
579             ap.av.setSelectionGroup(sg);
580             ap.av.sendSelection();
581             ap.paintAlignment(false);
582             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
583           }
584
585         }
586       }
587     }
588     if (!SwingUtilities.isRightMouseButton(evt))
589     {
590       return;
591     }
592
593     JPopupMenu pop = new JPopupMenu(
594             MessageManager.getString("label.annotations"));
595     JMenuItem item = new JMenuItem(ADDNEW);
596     item.addActionListener(this);
597     pop.add(item);
598     if (selectedRow < 0)
599     {
600       if (hasHiddenRows)
601       { // let the user make everything visible again
602         item = new JMenuItem(SHOWALL);
603         item.addActionListener(this);
604         pop.add(item);
605       }
606       pop.show(this, evt.getX(), evt.getY());
607       return;
608     }
609     item = new JMenuItem(EDITNAME);
610     item.addActionListener(this);
611     pop.add(item);
612     item = new JMenuItem(HIDE);
613     item.addActionListener(this);
614     pop.add(item);
615     // JAL-1264 hide all sequence-specific annotations of this type
616     final String label = aa[selectedRow].label;
617     if (selectedRow < aa.length)
618     {
619       if (aa[selectedRow].sequenceRef != null)
620       {
621         JMenuItem hideType = new JMenuItem();
622         String text = MessageManager.getString("label.hide_all") + " " + label;
623         hideType.setText(text);
624         hideType.addActionListener(new ActionListener()
625         {
626           @Override
627           public void actionPerformed(ActionEvent e)
628           {
629             for (AlignmentAnnotation ann : ap.av.getAlignment()
630                     .getAlignmentAnnotation())
631             {
632               if (ann.sequenceRef != null && ann.label != null
633                       && ann.label.equals(label))
634               {
635                 ann.visible = false;
636               }
637             }
638             refresh();
639           }
640         });
641         pop.add(hideType);
642       }
643     }
644     item = new JMenuItem(DELETE);
645     item.addActionListener(this);
646     pop.add(item);
647     if (hasHiddenRows)
648     {
649       item = new JMenuItem(SHOWALL);
650       item.addActionListener(this);
651       pop.add(item);
652     }
653     item = new JMenuItem(OUTPUT_TEXT);
654     item.addActionListener(this);
655     pop.add(item);
656     // TODO: annotation object should be typed for autocalculated/derived
657     // property methods
658     if (selectedRow < aa.length)
659     {
660       if (!aa[selectedRow].autoCalculated)
661       {
662         if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
663         {
664           // display formatting settings for this row.
665           pop.addSeparator();
666           // av and sequencegroup need to implement same interface for
667           item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
668                   aa[selectedRow].scaleColLabel);
669           item.addActionListener(this);
670           pop.add(item);
671         }
672       }
673       else if (label.indexOf("Consensus") > -1)
674       {
675         pop.addSeparator();
676         // av and sequencegroup need to implement same interface for
677         final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
678                         MessageManager.getString("label.ignore_gaps_consensus"),
679                 (aa[selectedRow].groupRef != null) ? aa[selectedRow].groupRef
680                         .getIgnoreGapsConsensus() : ap.av
681                         .getIgnoreGapsConsensus());
682         final AlignmentAnnotation aaa = aa[selectedRow];
683         cbmi.addActionListener(new ActionListener()
684         {
685           public void actionPerformed(ActionEvent e)
686           {
687             if (aaa.groupRef != null)
688             {
689               // TODO: pass on reference to ap so the view can be updated.
690               aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
691               ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
692             }
693             else
694             {
695               ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
696             }
697           }
698         });
699         pop.add(cbmi);
700         // av and sequencegroup need to implement same interface for
701         if (aaa.groupRef != null)
702         {
703           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
704                           MessageManager.getString("label.show_group_histogram"),
705                   aa[selectedRow].groupRef.isShowConsensusHistogram());
706           chist.addActionListener(new ActionListener()
707           {
708             public void actionPerformed(ActionEvent e)
709             {
710               // TODO: pass on reference
711               // to ap
712               // so the
713               // view
714               // can be
715               // updated.
716               aaa.groupRef.setShowConsensusHistogram(chist.getState());
717               ap.repaint();
718               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
719             }
720           });
721           pop.add(chist);
722           final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
723                           MessageManager.getString("label.show_group_logo"),
724                   aa[selectedRow].groupRef.isShowSequenceLogo());
725           cprofl.addActionListener(new ActionListener()
726           {
727             public void actionPerformed(ActionEvent e)
728             {
729               // TODO: pass on reference
730               // to ap
731               // so the
732               // view
733               // can be
734               // updated.
735               aaa.groupRef.setshowSequenceLogo(cprofl.getState());
736               ap.repaint();
737               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
738             }
739           });
740           pop.add(cprofl);
741           final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
742                           MessageManager.getString("label.normalise_group_logo"),
743                   aa[selectedRow].groupRef.isNormaliseSequenceLogo());
744           cproflnorm.addActionListener(new ActionListener()
745           {
746             public void actionPerformed(ActionEvent e)
747             {
748
749               // TODO: pass on reference
750               // to ap
751               // so the
752               // view
753               // can be
754               // updated.
755               aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
756               // automatically enable logo display if we're clicked
757               aaa.groupRef.setshowSequenceLogo(true);
758               ap.repaint();
759               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
760             }
761           });
762           pop.add(cproflnorm);
763         }
764         else
765         {
766           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
767                           MessageManager.getString("label.show_histogram"), av.isShowConsensusHistogram());
768           chist.addActionListener(new ActionListener()
769           {
770             public void actionPerformed(ActionEvent e)
771             {
772               // TODO: pass on reference
773               // to ap
774               // so the
775               // view
776               // can be
777               // updated.
778               av.setShowConsensusHistogram(chist.getState());
779               ap.alignFrame.setMenusForViewport();
780               ap.repaint();
781               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
782             }
783           });
784           pop.add(chist);
785           final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
786                           MessageManager.getString("label.show_logo"), av.isShowSequenceLogo());
787           cprof.addActionListener(new ActionListener()
788           {
789             public void actionPerformed(ActionEvent e)
790             {
791               // TODO: pass on reference
792               // to ap
793               // so the
794               // view
795               // can be
796               // updated.
797               av.setShowSequenceLogo(cprof.getState());
798               ap.alignFrame.setMenusForViewport();
799               ap.repaint();
800               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
801             }
802           });
803           pop.add(cprof);
804           final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
805                           MessageManager.getString("label.normalise_logo"), av.isNormaliseSequenceLogo());
806           cprofnorm.addActionListener(new ActionListener()
807           {
808             public void actionPerformed(ActionEvent e)
809             {
810               // TODO: pass on reference
811               // to ap
812               // so the
813               // view
814               // can be
815               // updated.
816               av.setShowSequenceLogo(true);
817               av.setNormaliseSequenceLogo(cprofnorm.getState());
818               ap.alignFrame.setMenusForViewport();
819               ap.repaint();
820               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
821             }
822           });
823           pop.add(cprofnorm);
824         }
825         final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
826         consclipbrd.addActionListener(this);
827         pop.add(consclipbrd);
828       }
829     }
830     pop.show(this, evt.getX(), evt.getY());
831   }
832
833   /**
834    * do a single sequence copy to jalview and the system clipboard
835    * 
836    * @param sq
837    *          sequence to be copied to clipboard
838    */
839   protected void copy_annotseqtoclipboard(SequenceI sq)
840   {
841     SequenceI[] seqs = new SequenceI[]
842     { sq };
843     String[] omitHidden = null;
844     SequenceI[] dseqs = new SequenceI[]
845     { sq.getDatasetSequence() };
846     if (dseqs[0] == null)
847     {
848       dseqs[0] = new Sequence(sq);
849       dseqs[0].setSequence(jalview.analysis.AlignSeq.extractGaps(
850               jalview.util.Comparison.GapChars, sq.getSequenceAsString()));
851
852       sq.setDatasetSequence(dseqs[0]);
853     }
854     Alignment ds = new Alignment(dseqs);
855     if (av.hasHiddenColumns())
856     {
857       omitHidden = av.getColumnSelection().getVisibleSequenceStrings(0,
858               sq.getLength(), seqs);
859     }
860
861     String output = new FormatAdapter().formatSequences("Fasta", seqs,
862             omitHidden);
863
864     Toolkit.getDefaultToolkit().getSystemClipboard()
865             .setContents(new StringSelection(output), Desktop.instance);
866
867     Vector hiddenColumns = null;
868     if (av.hasHiddenColumns())
869     {
870       hiddenColumns = new Vector();
871       for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
872       {
873         int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
874                 .elementAt(i);
875
876         hiddenColumns.addElement(new int[]
877         { region[0], region[1] });
878       }
879     }
880
881     Desktop.jalviewClipboard = new Object[]
882     { seqs, ds, // what is the dataset of a consensus sequence ? need to flag
883         // sequence as special.
884         hiddenColumns };
885   }
886
887   /**
888    * DOCUMENT ME!
889    * 
890    * @param g1
891    *          DOCUMENT ME!
892    */
893   public void paintComponent(Graphics g)
894   {
895
896     int width = getWidth();
897     if (width == 0)
898     {
899       width = ap.calculateIdWidth().width + 4;
900     }
901
902     Graphics2D g2 = (Graphics2D) g;
903     if (av.antiAlias)
904     {
905       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
906               RenderingHints.VALUE_ANTIALIAS_ON);
907     }
908
909     drawComponent(g2, true, width);
910
911   }
912
913   /**
914    * Draw the full set of annotation Labels for the alignment at the given
915    * cursor
916    * 
917    * @param g
918    *          Graphics2D instance (needed for font scaling)
919    * @param width
920    *          Width for scaling labels
921    * 
922    */
923   public void drawComponent(Graphics g, int width)
924   {
925     drawComponent(g, false, width);
926   }
927
928   private final boolean debugRedraw = false;
929
930   /**
931    * Draw the full set of annotation Labels for the alignment at the given
932    * cursor
933    * 
934    * @param g
935    *          Graphics2D instance (needed for font scaling)
936    * @param clip
937    *          - true indicates that only current visible area needs to be
938    *          rendered
939    * @param width
940    *          Width for scaling labels
941    */
942   public void drawComponent(Graphics g, boolean clip, int width)
943   {
944     if (av.getFont().getSize() < 10)
945     {
946       g.setFont(font);
947     }
948     else
949     {
950       g.setFont(av.getFont());
951     }
952
953     FontMetrics fm = g.getFontMetrics(g.getFont());
954     g.setColor(Color.white);
955     g.fillRect(0, 0, getWidth(), getHeight());
956
957     g.translate(0, scrollOffset);
958     g.setColor(Color.black);
959
960     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
961     int fontHeight = g.getFont().getSize();
962     int y = 0;
963     int x = 0;
964     int graphExtras = 0;
965     int offset = 0;
966     Font baseFont = g.getFont();
967     FontMetrics baseMetrics = fm;
968     int ofontH = fontHeight;
969     int sOffset = 0;
970     int visHeight = 0;
971     int[] visr = (ap != null && ap.annotationPanel != null) ? ap.annotationPanel
972             .getVisibleVRange() : null;
973     if (clip && visr != null)
974     {
975       sOffset = visr[0];
976       visHeight = visr[1];
977     }
978     boolean visible = true, before = false, after = false;
979     if (aa != null)
980     {
981       hasHiddenRows = false;
982       int olY = 0;
983       for (int i = 0; i < aa.length; i++)
984       {
985         visible = true;
986         if (!aa[i].visible)
987         {
988           hasHiddenRows = true;
989           continue;
990         }
991         olY = y;
992         y += aa[i].height;
993         if (clip)
994         {
995           if (y < sOffset)
996           {
997             if (!before)
998             {
999               if (debugRedraw)
1000               {
1001                 System.out.println("before vis: " + i);
1002               }
1003               before = true;
1004             }
1005             // don't draw what isn't visible
1006             continue;
1007           }
1008           if (olY > visHeight)
1009           {
1010
1011             if (!after)
1012             {
1013               if (debugRedraw)
1014               {
1015                 System.out.println("Scroll offset: " + sOffset
1016                         + " after vis: " + i);
1017               }
1018               after = true;
1019             }
1020             // don't draw what isn't visible
1021             continue;
1022           }
1023         }
1024         g.setColor(Color.black);
1025
1026         offset = -aa[i].height / 2;
1027
1028         if (aa[i].hasText)
1029         {
1030           offset += fm.getHeight() / 2;
1031           offset -= fm.getDescent();
1032         }
1033         else
1034         {
1035           offset += fm.getDescent();
1036         }
1037
1038         x = width - fm.stringWidth(aa[i].label) - 3;
1039
1040         if (aa[i].graphGroup > -1)
1041         {
1042           int groupSize = 0;
1043           // TODO: JAL-1291 revise rendering model so the graphGroup map is
1044           // computed efficiently for all visible labels
1045           for (int gg = 0; gg < aa.length; gg++)
1046           {
1047             if (aa[gg].graphGroup == aa[i].graphGroup)
1048             {
1049               groupSize++;
1050             }
1051           }
1052           if (groupSize * (fontHeight + 8) < aa[i].height)
1053           {
1054             graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1055           }
1056           else
1057           {
1058             // scale font to fit
1059             float h = aa[i].height / (float) groupSize, s;
1060             if (h < 9)
1061             {
1062               visible = false;
1063             }
1064             else
1065             {
1066               fontHeight = -8 + (int) h;
1067               s = ((float) fontHeight) / (float) ofontH;
1068               Font f = baseFont.deriveFont(AffineTransform
1069                       .getScaleInstance(s, s));
1070               g.setFont(f);
1071               fm = g.getFontMetrics();
1072               graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1073             }
1074           }
1075           if (visible)
1076           {
1077             for (int gg = 0; gg < aa.length; gg++)
1078             {
1079               if (aa[gg].graphGroup == aa[i].graphGroup)
1080               {
1081                 x = width - fm.stringWidth(aa[gg].label) - 3;
1082                 g.drawString(aa[gg].label, x, y - graphExtras);
1083
1084                 if (aa[gg]._linecolour != null)
1085                 {
1086
1087                   g.setColor(aa[gg]._linecolour);
1088                   g.drawLine(x, y - graphExtras + 3,
1089                           x + fm.stringWidth(aa[gg].label), y - graphExtras
1090                                   + 3);
1091                 }
1092
1093                 g.setColor(Color.black);
1094                 graphExtras += fontHeight + 8;
1095               }
1096             }
1097           }
1098           g.setFont(baseFont);
1099           fm = baseMetrics;
1100           fontHeight = ofontH;
1101         }
1102         else
1103         {
1104           g.drawString(aa[i].label, x, y + offset);
1105         }
1106       }
1107     }
1108
1109     if (resizePanel)
1110     {
1111       g.drawImage(image, 2, 0 - scrollOffset, this);
1112     }
1113     else if (dragEvent != null && aa != null)
1114     {
1115       g.setColor(Color.lightGray);
1116       g.drawString(aa[selectedRow].label, dragEvent.getX(),
1117               dragEvent.getY() - scrollOffset);
1118     }
1119
1120     if (!av.wrapAlignment && ((aa == null) || (aa.length < 1)))
1121     {
1122       g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1123       g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
1124               18);
1125     }
1126   }
1127 }