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