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