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