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