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