transferred the storage position of the HMM to annotations
[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       {
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) ? aa[selectedRow].groupRef
445                         .getIgnoreGapsConsensus() : ap.av
446                         .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().paint(
458                       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.setPreferredSize(new Dimension(d.width,
705                 d.height - dif));
706         d = ap.annotationSpaceFillerHolder.getPreferredSize();
707         ap.annotationSpaceFillerHolder.setPreferredSize(new Dimension(
708                 d.width, d.height - dif));
709         ap.paintAlignment(true);
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
734             && ap.av.getAlignment().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
749                 || (desc.substring(0, 6).toLowerCase().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
824                     || sg == aa[selectedRow].groupRef
825                     || !(jalview.util.Platform.isControlDown(evt) || evt
826                             .isShiftDown()))
827             {
828               if (jalview.util.Platform.isControlDown(evt)
829                       || evt.isShiftDown())
830               {
831                 // clone a new selection group from the associated group
832                 ap.av.setSelectionGroup(new SequenceGroup(
833                         aa[selectedRow].groupRef));
834               }
835               else
836               {
837                 // set selection to the associated group so it can be edited
838                 ap.av.setSelectionGroup(aa[selectedRow].groupRef);
839               }
840             }
841             else
842             {
843               // modify current selection with associated group
844               int remainToAdd = aa[selectedRow].groupRef.getSize();
845               for (SequenceI sgs : aa[selectedRow].groupRef.getSequences())
846               {
847                 if (jalview.util.Platform.isControlDown(evt))
848                 {
849                   sg.addOrRemove(sgs, --remainToAdd == 0);
850                 }
851                 else
852                 {
853                   // notionally, we should also add intermediate sequences from
854                   // last added sequence ?
855                   sg.addSequence(sgs, --remainToAdd == 0);
856                 }
857               }
858             }
859
860             ap.paintAlignment(false);
861             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
862             ap.av.sendSelection();
863           }
864           else
865           {
866             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(
867                     aa[selectedRow].groupRef.getSequences(null));
868           }
869           return;
870         }
871         else if (aa[selectedRow].sequenceRef != null)
872         {
873           if (evt.getClickCount() == 1)
874           {
875             ap.getSeqPanel().ap
876                     .getIdPanel()
877                     .highlightSearchResults(
878                             Arrays.asList(new SequenceI[] { aa[selectedRow].sequenceRef }));
879           }
880           else if (evt.getClickCount() >= 2)
881           {
882             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
883             SequenceGroup sg = ap.av.getSelectionGroup();
884             if (sg != null)
885             {
886               // we make a copy rather than edit the current selection if no
887               // modifiers pressed
888               // see Enhancement JAL-1557
889               if (!(jalview.util.Platform.isControlDown(evt) || evt
890                       .isShiftDown()))
891               {
892                 sg = new SequenceGroup(sg);
893                 sg.clear();
894                 sg.addSequence(aa[selectedRow].sequenceRef, false);
895               }
896               else
897               {
898                 if (jalview.util.Platform.isControlDown(evt))
899                 {
900                   sg.addOrRemove(aa[selectedRow].sequenceRef, true);
901                 }
902                 else
903                 {
904                   // notionally, we should also add intermediate sequences from
905                   // last added sequence ?
906                   sg.addSequence(aa[selectedRow].sequenceRef, true);
907                 }
908               }
909             }
910             else
911             {
912               sg = new SequenceGroup();
913               sg.setStartRes(0);
914               sg.setEndRes(ap.av.getAlignment().getWidth() - 1);
915               sg.addSequence(aa[selectedRow].sequenceRef, false);
916             }
917             ap.av.setSelectionGroup(sg);
918             ap.paintAlignment(false);
919             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
920             ap.av.sendSelection();
921           }
922
923         }
924       }
925       return;
926     }
927   }
928
929   /**
930    * do a single sequence copy to jalview and the system clipboard
931    * 
932    * @param sq
933    *          sequence to be copied to clipboard
934    */
935   protected void copy_annotseqtoclipboard(SequenceI sq)
936   {
937     SequenceI[] seqs = new SequenceI[] { sq };
938     String[] omitHidden = null;
939     SequenceI[] dseqs = new SequenceI[] { sq.getDatasetSequence() };
940     if (dseqs[0] == null)
941     {
942       dseqs[0] = new Sequence(sq);
943       dseqs[0].setSequence(jalview.analysis.AlignSeq.extractGaps(
944               jalview.util.Comparison.GapChars, sq.getSequenceAsString()));
945
946       sq.setDatasetSequence(dseqs[0]);
947     }
948     Alignment ds = new Alignment(dseqs);
949     if (av.hasHiddenColumns())
950     {
951       omitHidden = av.getAlignment().getHiddenColumns()
952               .getVisibleSequenceStrings(0,
953               sq.getLength(), seqs);
954     }
955
956     int[] alignmentStartEnd = new int[] { 0, ds.getWidth() - 1 };
957     List<int[]> hiddenCols = av.getAlignment().getHiddenColumns()
958             .getHiddenRegions();
959     if (hiddenCols != null)
960     {
961       alignmentStartEnd = av.getAlignment().getVisibleStartAndEndIndex(
962               hiddenCols);
963     }
964     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
965             seqs, omitHidden, alignmentStartEnd);
966
967     Toolkit.getDefaultToolkit().getSystemClipboard()
968             .setContents(new StringSelection(output), Desktop.instance);
969
970     ArrayList<int[]> hiddenColumns = null;
971     if (av.hasHiddenColumns())
972     {
973       hiddenColumns = new ArrayList<>();
974       for (int[] region : av.getAlignment().getHiddenColumns()
975               .getHiddenRegions())
976       {
977         hiddenColumns.add(new int[] { region[0], region[1] });
978       }
979     }
980
981     Desktop.jalviewClipboard = new Object[] { seqs, ds, // what is the dataset
982                                                         // of a consensus
983                                                         // sequence ? need to
984                                                         // flag
985         // sequence as special.
986         hiddenColumns };
987   }
988
989   /**
990    * DOCUMENT ME!
991    * 
992    * @param g1
993    *          DOCUMENT ME!
994    */
995   @Override
996   public void paintComponent(Graphics g)
997   {
998
999     int width = getWidth();
1000     if (width == 0)
1001     {
1002       width = ap.calculateIdWidth().width + 4;
1003     }
1004
1005     Graphics2D g2 = (Graphics2D) g;
1006     if (av.antiAlias)
1007     {
1008       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1009               RenderingHints.VALUE_ANTIALIAS_ON);
1010     }
1011
1012     drawComponent(g2, true, width);
1013
1014   }
1015
1016   /**
1017    * Draw the full set of annotation Labels for the alignment at the given
1018    * cursor
1019    * 
1020    * @param g
1021    *          Graphics2D instance (needed for font scaling)
1022    * @param width
1023    *          Width for scaling labels
1024    * 
1025    */
1026   public void drawComponent(Graphics g, int width)
1027   {
1028     drawComponent(g, false, width);
1029   }
1030
1031   private final boolean debugRedraw = false;
1032
1033   /**
1034    * Draw the full set of annotation Labels for the alignment at the given
1035    * cursor
1036    * 
1037    * @param g
1038    *          Graphics2D instance (needed for font scaling)
1039    * @param clip
1040    *          - true indicates that only current visible area needs to be
1041    *          rendered
1042    * @param width
1043    *          Width for scaling labels
1044    */
1045   public void drawComponent(Graphics g, boolean clip, int width)
1046   {
1047     if (av.getFont().getSize() < 10)
1048     {
1049       g.setFont(font);
1050     }
1051     else
1052     {
1053       g.setFont(av.getFont());
1054     }
1055
1056     FontMetrics fm = g.getFontMetrics(g.getFont());
1057     g.setColor(Color.white);
1058     g.fillRect(0, 0, getWidth(), getHeight());
1059
1060     g.translate(0, getScrollOffset());
1061     g.setColor(Color.black);
1062
1063     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
1064     int fontHeight = g.getFont().getSize();
1065     int y = 0;
1066     int x = 0;
1067     int graphExtras = 0;
1068     int offset = 0;
1069     Font baseFont = g.getFont();
1070     FontMetrics baseMetrics = fm;
1071     int ofontH = fontHeight;
1072     int sOffset = 0;
1073     int visHeight = 0;
1074     int[] visr = (ap != null && ap.getAnnotationPanel() != null) ? ap
1075             .getAnnotationPanel().getVisibleVRange() : null;
1076     if (clip && visr != null)
1077     {
1078       sOffset = visr[0];
1079       visHeight = visr[1];
1080     }
1081     boolean visible = true, before = false, after = false;
1082     if (aa != null)
1083     {
1084       hasHiddenRows = false;
1085       int olY = 0;
1086       for (int i = 0; i < aa.length; i++)
1087       {
1088         visible = true;
1089         if (!aa[i].visible)
1090         {
1091           hasHiddenRows = true;
1092           continue;
1093         }
1094         olY = y;
1095         y += aa[i].height;
1096         if (clip)
1097         {
1098           if (y < sOffset)
1099           {
1100             if (!before)
1101             {
1102               if (debugRedraw)
1103               {
1104                 System.out.println("before vis: " + i);
1105               }
1106               before = true;
1107             }
1108             // don't draw what isn't visible
1109             continue;
1110           }
1111           if (olY > visHeight)
1112           {
1113
1114             if (!after)
1115             {
1116               if (debugRedraw)
1117               {
1118                 System.out.println("Scroll offset: " + sOffset
1119                         + " after vis: " + i);
1120               }
1121               after = true;
1122             }
1123             // don't draw what isn't visible
1124             continue;
1125           }
1126         }
1127         g.setColor(Color.black);
1128
1129         offset = -aa[i].height / 2;
1130
1131         if (aa[i].hasText)
1132         {
1133           offset += fm.getHeight() / 2;
1134           offset -= fm.getDescent();
1135         }
1136         else
1137         {
1138           offset += fm.getDescent();
1139         }
1140
1141         x = width - fm.stringWidth(aa[i].label) - 3;
1142
1143         if (aa[i].graphGroup > -1)
1144         {
1145           int groupSize = 0;
1146           // TODO: JAL-1291 revise rendering model so the graphGroup map is
1147           // computed efficiently for all visible labels
1148           for (int gg = 0; gg < aa.length; gg++)
1149           {
1150             if (aa[gg].graphGroup == aa[i].graphGroup)
1151             {
1152               groupSize++;
1153             }
1154           }
1155           if (groupSize * (fontHeight + 8) < aa[i].height)
1156           {
1157             graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1158           }
1159           else
1160           {
1161             // scale font to fit
1162             float h = aa[i].height / (float) groupSize, s;
1163             if (h < 9)
1164             {
1165               visible = false;
1166             }
1167             else
1168             {
1169               fontHeight = -8 + (int) h;
1170               s = ((float) fontHeight) / (float) ofontH;
1171               Font f = baseFont.deriveFont(AffineTransform
1172                       .getScaleInstance(s, s));
1173               g.setFont(f);
1174               fm = g.getFontMetrics();
1175               graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1176             }
1177           }
1178           if (visible)
1179           {
1180             for (int gg = 0; gg < aa.length; gg++)
1181             {
1182               if (aa[gg].graphGroup == aa[i].graphGroup)
1183               {
1184                 x = width - fm.stringWidth(aa[gg].label) - 3;
1185                 g.drawString(aa[gg].label, x, y - graphExtras);
1186
1187                 if (aa[gg]._linecolour != null)
1188                 {
1189
1190                   g.setColor(aa[gg]._linecolour);
1191                   g.drawLine(x, y - graphExtras + 3,
1192                           x + fm.stringWidth(aa[gg].label), y - graphExtras
1193                                   + 3);
1194                 }
1195
1196                 g.setColor(Color.black);
1197                 graphExtras += fontHeight + 8;
1198               }
1199             }
1200           }
1201           g.setFont(baseFont);
1202           fm = baseMetrics;
1203           fontHeight = ofontH;
1204         }
1205         else
1206         {
1207           g.drawString(aa[i].label, x, y + offset);
1208         }
1209       }
1210     }
1211
1212     if (resizePanel)
1213     {
1214       g.drawImage(image, 2, 0 - getScrollOffset(), this);
1215     }
1216     else if (dragEvent != null && aa != null)
1217     {
1218       g.setColor(Color.lightGray);
1219       g.drawString(aa[selectedRow].label, dragEvent.getX(),
1220               dragEvent.getY() - getScrollOffset());
1221     }
1222
1223     if (!av.getWrapAlignment() && ((aa == null) || (aa.length < 1)))
1224     {
1225       g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1226       g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
1227               18);
1228     }
1229   }
1230
1231   public int getScrollOffset()
1232   {
1233     return scrollOffset;
1234   }
1235 }