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