JAL-1620 version bump and release notes
[jalview.git] / src / jalview / gui / AnnotationLabels.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2b1)
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         // if (aa.hasProperties())
482         // {
483         // desc.append("<table>");
484         // for (String prop : aa.getProperties())
485         // {
486         // desc.append("<tr><td>" + prop + "</td><td>"
487         // + aa.getProperty(prop) + "</td><tr>");
488         // }
489         // desc.append("</table>");
490         // }
491       }
492       else
493       {
494         // begin the tooltip's html fragment
495         desc.append("<html>");
496         if (aa.hasScore())
497         {
498           // TODO: limit precision of score to avoid noise from imprecise
499           // doubles
500           // (64.7 becomes 64.7+/some tiny value).
501           desc.append(" Score: " + aa.score);
502         }
503       }
504       if (desc.length() > 6)
505       {
506         desc.append("</html>");
507         this.setToolTipText(desc.toString());
508       }
509       else
510       {
511         this.setToolTipText(null);
512       }
513     }
514   }
515
516   /**
517    * DOCUMENT ME!
518    * 
519    * @param evt
520    *          DOCUMENT ME!
521    */
522   public void mouseClicked(MouseEvent evt)
523   {
524     final AlignmentAnnotation[] aa = ap.av.getAlignment()
525             .getAlignmentAnnotation();
526     if (SwingUtilities.isLeftMouseButton(evt))
527     {
528       if (selectedRow > -1 && selectedRow < aa.length)
529       {
530         if (aa[selectedRow].groupRef != null)
531         {
532           if (evt.getClickCount() >= 2)
533           {
534             // todo: make the ap scroll to the selection - not necessary, first
535             // click highlights/scrolls, second selects
536             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
537             ap.av.setSelectionGroup(// new SequenceGroup(
538             aa[selectedRow].groupRef); // );
539             ap.paintAlignment(false);
540             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
541             ap.av.sendSelection();
542           }
543           else
544           {
545             ap.seqPanel.ap.idPanel
546                     .highlightSearchResults(aa[selectedRow].groupRef
547                             .getSequences(null));
548           }
549           return;
550         }
551         else if (aa[selectedRow].sequenceRef != null)
552         {
553           if (evt.getClickCount() == 1)
554           {
555             ap.seqPanel.ap.idPanel.highlightSearchResults(Arrays
556                     .asList(new SequenceI[]
557                     { aa[selectedRow].sequenceRef }));
558           }
559           else if (evt.getClickCount() >= 2)
560           {
561             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
562             SequenceGroup sg = ap.av.getSelectionGroup();
563             if (sg!=null)
564             {
565               // we make a copy rather than edit the current selection if no modifiers pressed
566               // see Enhancement JAL-1557
567               if (!(evt.isControlDown() || evt.isShiftDown()))
568               {
569                 sg = new SequenceGroup(sg);
570                 sg.clear();
571                 sg.addSequence(aa[selectedRow].sequenceRef, false);
572               } else {
573                 if (evt.isControlDown())
574                 {
575                   sg.addOrRemove(aa[selectedRow].sequenceRef, true);
576                 } else {
577                   // notionally, we should also add intermediate sequences from last added sequence ?
578                   sg.addSequence(aa[selectedRow].sequenceRef, true);
579                 }
580               }
581             } else {
582               sg = new SequenceGroup();
583               sg.setStartRes(0);
584               sg.setEndRes(ap.av.getAlignment().getWidth()-1);
585               sg.addSequence(aa[selectedRow].sequenceRef, false);
586             }
587             ap.av.setSelectionGroup(sg);
588             ap.av.sendSelection();
589             ap.paintAlignment(false);
590             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
591           }
592
593         }
594       }
595     }
596     if (!SwingUtilities.isRightMouseButton(evt))
597     {
598       return;
599     }
600
601     JPopupMenu pop = new JPopupMenu(
602             MessageManager.getString("label.annotations"));
603     JMenuItem item = new JMenuItem(ADDNEW);
604     item.addActionListener(this);
605     pop.add(item);
606     if (selectedRow < 0)
607     {
608       if (hasHiddenRows)
609       { // let the user make everything visible again
610         item = new JMenuItem(SHOWALL);
611         item.addActionListener(this);
612         pop.add(item);
613       }
614       pop.show(this, evt.getX(), evt.getY());
615       return;
616     }
617     item = new JMenuItem(EDITNAME);
618     item.addActionListener(this);
619     pop.add(item);
620     item = new JMenuItem(HIDE);
621     item.addActionListener(this);
622     pop.add(item);
623     // JAL-1264 hide all sequence-specific annotations of this type
624     final String label = aa[selectedRow].label;
625     if (selectedRow < aa.length)
626     {
627       if (aa[selectedRow].sequenceRef != null)
628       {
629         JMenuItem hideType = new JMenuItem();
630         String text = MessageManager.getString("label.hide_all") + " " + label;
631         hideType.setText(text);
632         hideType.addActionListener(new ActionListener()
633         {
634           @Override
635           public void actionPerformed(ActionEvent e)
636           {
637             for (AlignmentAnnotation ann : ap.av.getAlignment()
638                     .getAlignmentAnnotation())
639             {
640               if (ann.sequenceRef != null && ann.label != null
641                       && ann.label.equals(label))
642               {
643                 ann.visible = false;
644               }
645             }
646             refresh();
647           }
648         });
649         pop.add(hideType);
650       }
651     }
652     item = new JMenuItem(DELETE);
653     item.addActionListener(this);
654     pop.add(item);
655     if (hasHiddenRows)
656     {
657       item = new JMenuItem(SHOWALL);
658       item.addActionListener(this);
659       pop.add(item);
660     }
661     item = new JMenuItem(OUTPUT_TEXT);
662     item.addActionListener(this);
663     pop.add(item);
664     // TODO: annotation object should be typed for autocalculated/derived
665     // property methods
666     if (selectedRow < aa.length)
667     {
668       if (!aa[selectedRow].autoCalculated)
669       {
670         if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
671         {
672           // display formatting settings for this row.
673           pop.addSeparator();
674           // av and sequencegroup need to implement same interface for
675           item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
676                   aa[selectedRow].scaleColLabel);
677           item.addActionListener(this);
678           pop.add(item);
679         }
680       }
681       else if (label.indexOf("Consensus") > -1)
682       {
683         pop.addSeparator();
684         // av and sequencegroup need to implement same interface for
685         final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
686                         MessageManager.getString("label.ignore_gaps_consensus"),
687                 (aa[selectedRow].groupRef != null) ? aa[selectedRow].groupRef
688                         .getIgnoreGapsConsensus() : ap.av
689                         .getIgnoreGapsConsensus());
690         final AlignmentAnnotation aaa = aa[selectedRow];
691         cbmi.addActionListener(new ActionListener()
692         {
693           public void actionPerformed(ActionEvent e)
694           {
695             if (aaa.groupRef != null)
696             {
697               // TODO: pass on reference to ap so the view can be updated.
698               aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
699               ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
700             }
701             else
702             {
703               ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
704             }
705           }
706         });
707         pop.add(cbmi);
708         // av and sequencegroup need to implement same interface for
709         if (aaa.groupRef != null)
710         {
711           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
712                           MessageManager.getString("label.show_group_histogram"),
713                   aa[selectedRow].groupRef.isShowConsensusHistogram());
714           chist.addActionListener(new ActionListener()
715           {
716             public void actionPerformed(ActionEvent e)
717             {
718               // TODO: pass on reference
719               // to ap
720               // so the
721               // view
722               // can be
723               // updated.
724               aaa.groupRef.setShowConsensusHistogram(chist.getState());
725               ap.repaint();
726               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
727             }
728           });
729           pop.add(chist);
730           final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
731                           MessageManager.getString("label.show_group_logo"),
732                   aa[selectedRow].groupRef.isShowSequenceLogo());
733           cprofl.addActionListener(new ActionListener()
734           {
735             public void actionPerformed(ActionEvent e)
736             {
737               // TODO: pass on reference
738               // to ap
739               // so the
740               // view
741               // can be
742               // updated.
743               aaa.groupRef.setshowSequenceLogo(cprofl.getState());
744               ap.repaint();
745               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
746             }
747           });
748           pop.add(cprofl);
749           final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
750                           MessageManager.getString("label.normalise_group_logo"),
751                   aa[selectedRow].groupRef.isNormaliseSequenceLogo());
752           cproflnorm.addActionListener(new ActionListener()
753           {
754             public void actionPerformed(ActionEvent e)
755             {
756
757               // TODO: pass on reference
758               // to ap
759               // so the
760               // view
761               // can be
762               // updated.
763               aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
764               // automatically enable logo display if we're clicked
765               aaa.groupRef.setshowSequenceLogo(true);
766               ap.repaint();
767               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
768             }
769           });
770           pop.add(cproflnorm);
771         }
772         else
773         {
774           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
775                           MessageManager.getString("label.show_histogram"), av.isShowConsensusHistogram());
776           chist.addActionListener(new ActionListener()
777           {
778             public void actionPerformed(ActionEvent e)
779             {
780               // TODO: pass on reference
781               // to ap
782               // so the
783               // view
784               // can be
785               // updated.
786               av.setShowConsensusHistogram(chist.getState());
787               ap.alignFrame.setMenusForViewport();
788               ap.repaint();
789               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
790             }
791           });
792           pop.add(chist);
793           final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
794                           MessageManager.getString("label.show_logo"), av.isShowSequenceLogo());
795           cprof.addActionListener(new ActionListener()
796           {
797             public void actionPerformed(ActionEvent e)
798             {
799               // TODO: pass on reference
800               // to ap
801               // so the
802               // view
803               // can be
804               // updated.
805               av.setShowSequenceLogo(cprof.getState());
806               ap.alignFrame.setMenusForViewport();
807               ap.repaint();
808               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
809             }
810           });
811           pop.add(cprof);
812           final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
813                           MessageManager.getString("label.normalise_logo"), av.isNormaliseSequenceLogo());
814           cprofnorm.addActionListener(new ActionListener()
815           {
816             public void actionPerformed(ActionEvent e)
817             {
818               // TODO: pass on reference
819               // to ap
820               // so the
821               // view
822               // can be
823               // updated.
824               av.setShowSequenceLogo(true);
825               av.setNormaliseSequenceLogo(cprofnorm.getState());
826               ap.alignFrame.setMenusForViewport();
827               ap.repaint();
828               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
829             }
830           });
831           pop.add(cprofnorm);
832         }
833         final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
834         consclipbrd.addActionListener(this);
835         pop.add(consclipbrd);
836       }
837     }
838     pop.show(this, evt.getX(), evt.getY());
839   }
840
841   /**
842    * do a single sequence copy to jalview and the system clipboard
843    * 
844    * @param sq
845    *          sequence to be copied to clipboard
846    */
847   protected void copy_annotseqtoclipboard(SequenceI sq)
848   {
849     SequenceI[] seqs = new SequenceI[]
850     { sq };
851     String[] omitHidden = null;
852     SequenceI[] dseqs = new SequenceI[]
853     { sq.getDatasetSequence() };
854     if (dseqs[0] == null)
855     {
856       dseqs[0] = new Sequence(sq);
857       dseqs[0].setSequence(jalview.analysis.AlignSeq.extractGaps(
858               jalview.util.Comparison.GapChars, sq.getSequenceAsString()));
859
860       sq.setDatasetSequence(dseqs[0]);
861     }
862     Alignment ds = new Alignment(dseqs);
863     if (av.hasHiddenColumns())
864     {
865       omitHidden = av.getColumnSelection().getVisibleSequenceStrings(0,
866               sq.getLength(), seqs);
867     }
868
869     String output = new FormatAdapter().formatSequences("Fasta", seqs,
870             omitHidden);
871
872     Toolkit.getDefaultToolkit().getSystemClipboard()
873             .setContents(new StringSelection(output), Desktop.instance);
874
875     Vector hiddenColumns = null;
876     if (av.hasHiddenColumns())
877     {
878       hiddenColumns = new Vector();
879       for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
880       {
881         int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
882                 .elementAt(i);
883
884         hiddenColumns.addElement(new int[]
885         { region[0], region[1] });
886       }
887     }
888
889     Desktop.jalviewClipboard = new Object[]
890     { seqs, ds, // what is the dataset of a consensus sequence ? need to flag
891         // sequence as special.
892         hiddenColumns };
893   }
894
895   /**
896    * DOCUMENT ME!
897    * 
898    * @param g1
899    *          DOCUMENT ME!
900    */
901   public void paintComponent(Graphics g)
902   {
903
904     int width = getWidth();
905     if (width == 0)
906     {
907       width = ap.calculateIdWidth().width + 4;
908     }
909
910     Graphics2D g2 = (Graphics2D) g;
911     if (av.antiAlias)
912     {
913       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
914               RenderingHints.VALUE_ANTIALIAS_ON);
915     }
916
917     drawComponent(g2, true, width);
918
919   }
920
921   /**
922    * Draw the full set of annotation Labels for the alignment at the given
923    * cursor
924    * 
925    * @param g
926    *          Graphics2D instance (needed for font scaling)
927    * @param width
928    *          Width for scaling labels
929    * 
930    */
931   public void drawComponent(Graphics g, int width)
932   {
933     drawComponent(g, false, width);
934   }
935
936   private final boolean debugRedraw = false;
937
938   /**
939    * Draw the full set of annotation Labels for the alignment at the given
940    * cursor
941    * 
942    * @param g
943    *          Graphics2D instance (needed for font scaling)
944    * @param clip
945    *          - true indicates that only current visible area needs to be
946    *          rendered
947    * @param width
948    *          Width for scaling labels
949    */
950   public void drawComponent(Graphics g, boolean clip, int width)
951   {
952     if (av.getFont().getSize() < 10)
953     {
954       g.setFont(font);
955     }
956     else
957     {
958       g.setFont(av.getFont());
959     }
960
961     FontMetrics fm = g.getFontMetrics(g.getFont());
962     g.setColor(Color.white);
963     g.fillRect(0, 0, getWidth(), getHeight());
964
965     g.translate(0, scrollOffset);
966     g.setColor(Color.black);
967
968     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
969     int fontHeight = g.getFont().getSize();
970     int y = 0;
971     int x = 0;
972     int graphExtras = 0;
973     int offset = 0;
974     Font baseFont = g.getFont();
975     FontMetrics baseMetrics = fm;
976     int ofontH = fontHeight;
977     int sOffset = 0;
978     int visHeight = 0;
979     int[] visr = (ap != null && ap.annotationPanel != null) ? ap.annotationPanel
980             .getVisibleVRange() : null;
981     if (clip && visr != null)
982     {
983       sOffset = visr[0];
984       visHeight = visr[1];
985     }
986     boolean visible = true, before = false, after = false;
987     if (aa != null)
988     {
989       hasHiddenRows = false;
990       int olY = 0;
991       for (int i = 0; i < aa.length; i++)
992       {
993         visible = true;
994         if (!aa[i].visible)
995         {
996           hasHiddenRows = true;
997           continue;
998         }
999         olY = y;
1000         y += aa[i].height;
1001         if (clip)
1002         {
1003           if (y < sOffset)
1004           {
1005             if (!before)
1006             {
1007               if (debugRedraw)
1008               {
1009                 System.out.println("before vis: " + i);
1010               }
1011               before = true;
1012             }
1013             // don't draw what isn't visible
1014             continue;
1015           }
1016           if (olY > visHeight)
1017           {
1018
1019             if (!after)
1020             {
1021               if (debugRedraw)
1022               {
1023                 System.out.println("Scroll offset: " + sOffset
1024                         + " after vis: " + i);
1025               }
1026               after = true;
1027             }
1028             // don't draw what isn't visible
1029             continue;
1030           }
1031         }
1032         g.setColor(Color.black);
1033
1034         offset = -aa[i].height / 2;
1035
1036         if (aa[i].hasText)
1037         {
1038           offset += fm.getHeight() / 2;
1039           offset -= fm.getDescent();
1040         }
1041         else
1042         {
1043           offset += fm.getDescent();
1044         }
1045
1046         x = width - fm.stringWidth(aa[i].label) - 3;
1047
1048         if (aa[i].graphGroup > -1)
1049         {
1050           int groupSize = 0;
1051           // TODO: JAL-1291 revise rendering model so the graphGroup map is
1052           // computed efficiently for all visible labels
1053           for (int gg = 0; gg < aa.length; gg++)
1054           {
1055             if (aa[gg].graphGroup == aa[i].graphGroup)
1056             {
1057               groupSize++;
1058             }
1059           }
1060           if (groupSize * (fontHeight + 8) < aa[i].height)
1061           {
1062             graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1063           }
1064           else
1065           {
1066             // scale font to fit
1067             float h = aa[i].height / (float) groupSize, s;
1068             if (h < 9)
1069             {
1070               visible = false;
1071             }
1072             else
1073             {
1074               fontHeight = -8 + (int) h;
1075               s = ((float) fontHeight) / (float) ofontH;
1076               Font f = baseFont.deriveFont(AffineTransform
1077                       .getScaleInstance(s, s));
1078               g.setFont(f);
1079               fm = g.getFontMetrics();
1080               graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1081             }
1082           }
1083           if (visible)
1084           {
1085             for (int gg = 0; gg < aa.length; gg++)
1086             {
1087               if (aa[gg].graphGroup == aa[i].graphGroup)
1088               {
1089                 x = width - fm.stringWidth(aa[gg].label) - 3;
1090                 g.drawString(aa[gg].label, x, y - graphExtras);
1091
1092                 if (aa[gg]._linecolour != null)
1093                 {
1094
1095                   g.setColor(aa[gg]._linecolour);
1096                   g.drawLine(x, y - graphExtras + 3,
1097                           x + fm.stringWidth(aa[gg].label), y - graphExtras
1098                                   + 3);
1099                 }
1100
1101                 g.setColor(Color.black);
1102                 graphExtras += fontHeight + 8;
1103               }
1104             }
1105           }
1106           g.setFont(baseFont);
1107           fm = baseMetrics;
1108           fontHeight = ofontH;
1109         }
1110         else
1111         {
1112           g.drawString(aa[i].label, x, y + offset);
1113         }
1114       }
1115     }
1116
1117     if (resizePanel)
1118     {
1119       g.drawImage(image, 2, 0 - scrollOffset, this);
1120     }
1121     else if (dragEvent != null && aa != null)
1122     {
1123       g.setColor(Color.lightGray);
1124       g.drawString(aa[selectedRow].label, dragEvent.getX(),
1125               dragEvent.getY() - scrollOffset);
1126     }
1127
1128     if (!av.wrapAlignment && ((aa == null) || (aa.length < 1)))
1129     {
1130       g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1131       g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
1132               18);
1133     }
1134   }
1135 }