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