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