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