JAL-2629 add hmmalign command
[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.alignFrame.setMenusForViewport();
558               ap.repaint();
559               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
560             }
561           });
562           pop.add(chist);
563           final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
564                   MessageManager.getString("label.show_logo"),
565                   av.isShowSequenceLogo());
566           cprof.addActionListener(new ActionListener()
567           {
568             @Override
569             public void actionPerformed(ActionEvent e)
570             {
571               // TODO: pass on reference
572               // to ap
573               // so the
574               // view
575               // can be
576               // updated.
577               av.setShowSequenceLogo(cprof.getState());
578               ap.alignFrame.setMenusForViewport();
579               ap.repaint();
580               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
581             }
582           });
583           pop.add(cprof);
584           final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
585                   MessageManager.getString("label.normalise_logo"),
586                   av.isNormaliseSequenceLogo());
587           cprofnorm.addActionListener(new ActionListener()
588           {
589             @Override
590             public void actionPerformed(ActionEvent e)
591             {
592               // TODO: pass on reference
593               // to ap
594               // so the
595               // view
596               // can be
597               // updated.
598               av.setShowSequenceLogo(true);
599               av.setNormaliseSequenceLogo(cprofnorm.getState());
600               ap.alignFrame.setMenusForViewport();
601               ap.repaint();
602               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
603             }
604           });
605           pop.add(cprofnorm);
606         }
607         final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
608         consclipbrd.addActionListener(this);
609         pop.add(consclipbrd);
610       }
611       else if (label.indexOf("Information") > -1) // TODO create labels
612                                                           // in message resource
613                                                           // for these
614       {
615         pop.addSeparator();
616         final AlignmentAnnotation aaa = aa[selectedRow];
617
618         final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
619                 MessageManager.getString(
620                         "label.ignore_below_background_frequency"),
621                 (aa[selectedRow].groupRef != null)
622                         ? aa[selectedRow].groupRef
623                                 .getIgnoreBelowBackground()
624                         : ap.av.isIgnoreBelowBackground());
625
626         cbmi.addActionListener(new ActionListener()
627         {
628           @Override
629           public void actionPerformed(ActionEvent e)
630           {
631             if (aaa.groupRef != null)
632             {
633               // TODO: pass on reference to ap so the view can be updated.
634               aaa.groupRef.setIgnoreBelowBackground(cbmi.getState());
635               ap.getAnnotationPanel()
636                       .paint(ap.getAnnotationPanel().getGraphics());
637             }
638             else
639             {
640               ap.av.setIgnoreBelowBackground(cbmi.getState(), ap);
641             }
642             ap.alignmentChanged();
643           }
644         });
645         pop.add(cbmi);
646         if (aaa.groupRef != null)
647         {
648           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
649                   MessageManager.getString("label.show_group_histogram"),
650                   aa[selectedRow].groupRef.isShowInformationHistogram());
651           chist.addActionListener(new ActionListener()
652           {
653             @Override
654             public void actionPerformed(ActionEvent e)
655             {
656               // TODO: pass on reference
657               // to ap
658               // so the
659               // view
660               // can be
661               // updated.
662               aaa.groupRef.setShowInformationHistogram(chist.getState());
663               ap.repaint();
664               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
665             }
666           });
667           pop.add(chist);
668           final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
669                   MessageManager.getString("label.show_group_logo"),
670                   aa[selectedRow].groupRef.isShowHMMSequenceLogo());
671           cprofl.addActionListener(new ActionListener()
672           {
673             @Override
674             public void actionPerformed(ActionEvent e)
675             {
676               // TODO: pass on reference
677               // to ap
678               // so the
679               // view
680               // can be
681               // updated.
682               aaa.groupRef.setshowHMMSequenceLogo(cprofl.getState());
683               ap.repaint();
684               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
685             }
686           });
687           pop.add(cprofl);
688           final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
689                   MessageManager.getString("label.normalise_group_logo"),
690                   aa[selectedRow].groupRef.isNormaliseHMMSequenceLogo());
691           cproflnorm.addActionListener(new ActionListener()
692           {
693             @Override
694             public void actionPerformed(ActionEvent e)
695             {
696
697               // TODO: pass on reference
698               // to ap
699               // so the
700               // view
701               // can be
702               // updated.
703               aaa.groupRef
704                       .setNormaliseHMMSequenceLogo(cproflnorm.getState());
705               // automatically enable logo display if we're clicked
706               aaa.groupRef.setshowHMMSequenceLogo(true);
707               ap.repaint();
708               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
709             }
710           });
711           pop.add(cproflnorm);
712         }
713         else
714         {
715           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
716                   MessageManager.getString("label.show_histogram"),
717                   av.isShowInformationHistogram());
718           chist.addActionListener(new ActionListener()
719           {
720             @Override
721             public void actionPerformed(ActionEvent e)
722             {
723               // TODO: pass on reference
724               // to ap
725               // so the
726               // view
727               // can be
728               // updated.
729               av.setShowInformationHistogram(chist.getState());
730               ap.alignFrame.setMenusForViewport();
731               ap.repaint();
732               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
733             }
734           });
735           pop.add(chist);
736           final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
737                   MessageManager.getString("label.show_logo"),
738                   av.isShowHMMSequenceLogo());
739           cprof.addActionListener(new ActionListener()
740           {
741             @Override
742             public void actionPerformed(ActionEvent e)
743             {
744               // TODO: pass on reference
745               // to ap
746               // so the
747               // view
748               // can be
749               // updated.
750               av.setShowHMMSequenceLogo(cprof.getState());
751               ap.alignFrame.setMenusForViewport();
752               ap.repaint();
753               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
754             }
755           });
756           pop.add(cprof);
757           final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
758                   MessageManager.getString("label.normalise_logo"),
759                   av.isNormaliseHMMSequenceLogo());
760           cprofnorm.addActionListener(new ActionListener()
761           {
762             @Override
763             public void actionPerformed(ActionEvent e)
764             {
765               // TODO: pass on reference
766               // to ap
767               // so the
768               // view
769               // can be
770               // updated.
771               av.setShowHMMSequenceLogo(true);
772               av.setNormaliseHMMSequenceLogo(cprofnorm.getState());
773               ap.alignFrame.setMenusForViewport();
774               ap.repaint();
775               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
776             }
777           });
778           pop.add(cprofnorm);
779         }
780         final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
781         consclipbrd.addActionListener(this);
782         pop.add(consclipbrd);
783       }
784     }
785     pop.show(this, evt.getX(), evt.getY());
786   }
787
788   /**
789    * DOCUMENT ME!
790    * 
791    * @param evt
792    *          DOCUMENT ME!
793    */
794   @Override
795   public void mouseReleased(MouseEvent evt)
796   {
797     if (evt.isPopupTrigger())
798     {
799       showPopupMenu(evt);
800       return;
801     }
802
803     int start = selectedRow;
804     getSelectedRow(evt.getY() - getScrollOffset());
805     int end = selectedRow;
806
807     if (start != end)
808     {
809       // Swap these annotations
810       AlignmentAnnotation startAA = ap.av.getAlignment()
811               .getAlignmentAnnotation()[start];
812       if (end == -1)
813       {
814         end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
815       }
816       AlignmentAnnotation endAA = ap.av.getAlignment()
817               .getAlignmentAnnotation()[end];
818
819       ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
820       ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
821     }
822
823     resizePanel = false;
824     dragEvent = null;
825     repaint();
826     ap.getAnnotationPanel().repaint();
827   }
828
829   /**
830    * DOCUMENT ME!
831    * 
832    * @param evt
833    *          DOCUMENT ME!
834    */
835   @Override
836   public void mouseEntered(MouseEvent evt)
837   {
838     if (evt.getY() < 10)
839     {
840       resizePanel = true;
841       repaint();
842     }
843   }
844
845   /**
846    * DOCUMENT ME!
847    * 
848    * @param evt
849    *          DOCUMENT ME!
850    */
851   @Override
852   public void mouseExited(MouseEvent evt)
853   {
854     if (dragEvent == null)
855     {
856       resizePanel = false;
857       repaint();
858     }
859   }
860
861   /**
862    * DOCUMENT ME!
863    * 
864    * @param evt
865    *          DOCUMENT ME!
866    */
867   @Override
868   public void mouseDragged(MouseEvent evt)
869   {
870     dragEvent = evt;
871
872     if (resizePanel)
873     {
874       Dimension d = ap.annotationScroller.getPreferredSize();
875       int dif = evt.getY() - oldY;
876
877       dif /= ap.av.getCharHeight();
878       dif *= ap.av.getCharHeight();
879
880       if ((d.height - dif) > 20)
881       {
882         ap.annotationScroller.setPreferredSize(new Dimension(d.width,
883                 d.height - dif));
884         d = ap.annotationSpaceFillerHolder.getPreferredSize();
885         ap.annotationSpaceFillerHolder.setPreferredSize(new Dimension(
886                 d.width, d.height - dif));
887         ap.paintAlignment(true);
888       }
889
890       ap.addNotify();
891     }
892     else
893     {
894       repaint();
895     }
896   }
897
898   /**
899    * DOCUMENT ME!
900    * 
901    * @param evt
902    *          DOCUMENT ME!
903    */
904   @Override
905   public void mouseMoved(MouseEvent evt)
906   {
907     resizePanel = evt.getY() < 10;
908
909     getSelectedRow(evt.getY() - getScrollOffset());
910
911     if (selectedRow > -1
912             && ap.av.getAlignment().getAlignmentAnnotation().length > selectedRow)
913     {
914       AlignmentAnnotation aa = ap.av.getAlignment()
915               .getAlignmentAnnotation()[selectedRow];
916
917       StringBuffer desc = new StringBuffer();
918       if (aa.description != null
919               && !aa.description.equals("New description"))
920       {
921         // TODO: we could refactor and merge this code with the code in
922         // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
923         // tooltips
924         desc.append(aa.getDescription(true).trim());
925         // check to see if the description is an html fragment.
926         if (desc.length() < 6
927                 || (desc.substring(0, 6).toLowerCase().indexOf("<html>") < 0))
928         {
929           // clean the description ready for embedding in html
930           desc = new StringBuffer(LEFT_ANGLE_BRACKET_PATTERN.matcher(desc)
931                   .replaceAll("&lt;"));
932           desc.insert(0, "<html>");
933         }
934         else
935         {
936           // remove terminating html if any
937           int i = desc.substring(desc.length() - 7).toLowerCase()
938                   .lastIndexOf("</html>");
939           if (i > -1)
940           {
941             desc.setLength(desc.length() - 7 + i);
942           }
943         }
944         if (aa.hasScore())
945         {
946           desc.append("<br/>");
947         }
948         // if (aa.hasProperties())
949         // {
950         // desc.append("<table>");
951         // for (String prop : aa.getProperties())
952         // {
953         // desc.append("<tr><td>" + prop + "</td><td>"
954         // + aa.getProperty(prop) + "</td><tr>");
955         // }
956         // desc.append("</table>");
957         // }
958       }
959       else
960       {
961         // begin the tooltip's html fragment
962         desc.append("<html>");
963         if (aa.hasScore())
964         {
965           // TODO: limit precision of score to avoid noise from imprecise
966           // doubles
967           // (64.7 becomes 64.7+/some tiny value).
968           desc.append(" Score: " + aa.score);
969         }
970       }
971       if (desc.length() > 6)
972       {
973         desc.append("</html>");
974         this.setToolTipText(desc.toString());
975       }
976       else
977       {
978         this.setToolTipText(null);
979       }
980     }
981   }
982
983   @Override
984   public void mouseClicked(MouseEvent evt)
985   {
986     final AlignmentAnnotation[] aa = ap.av.getAlignment()
987             .getAlignmentAnnotation();
988     if (!evt.isPopupTrigger() && SwingUtilities.isLeftMouseButton(evt))
989     {
990       if (selectedRow > -1 && selectedRow < aa.length)
991       {
992         if (aa[selectedRow].groupRef != null)
993         {
994           if (evt.getClickCount() >= 2)
995           {
996             // todo: make the ap scroll to the selection - not necessary, first
997             // click highlights/scrolls, second selects
998             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
999             // process modifiers
1000             SequenceGroup sg = ap.av.getSelectionGroup();
1001             if (sg == null
1002                     || sg == aa[selectedRow].groupRef
1003                     || !(jalview.util.Platform.isControlDown(evt) || evt
1004                             .isShiftDown()))
1005             {
1006               if (jalview.util.Platform.isControlDown(evt)
1007                       || evt.isShiftDown())
1008               {
1009                 // clone a new selection group from the associated group
1010                 ap.av.setSelectionGroup(new SequenceGroup(
1011                         aa[selectedRow].groupRef));
1012               }
1013               else
1014               {
1015                 // set selection to the associated group so it can be edited
1016                 ap.av.setSelectionGroup(aa[selectedRow].groupRef);
1017               }
1018             }
1019             else
1020             {
1021               // modify current selection with associated group
1022               int remainToAdd = aa[selectedRow].groupRef.getSize();
1023               for (SequenceI sgs : aa[selectedRow].groupRef.getSequences())
1024               {
1025                 if (jalview.util.Platform.isControlDown(evt))
1026                 {
1027                   sg.addOrRemove(sgs, --remainToAdd == 0);
1028                 }
1029                 else
1030                 {
1031                   // notionally, we should also add intermediate sequences from
1032                   // last added sequence ?
1033                   sg.addSequence(sgs, --remainToAdd == 0);
1034                 }
1035               }
1036             }
1037
1038             ap.paintAlignment(false);
1039             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
1040             ap.av.sendSelection();
1041           }
1042           else
1043           {
1044             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(
1045                     aa[selectedRow].groupRef.getSequences(null));
1046           }
1047           return;
1048         }
1049         else if (aa[selectedRow].sequenceRef != null)
1050         {
1051           if (evt.getClickCount() == 1)
1052           {
1053             ap.getSeqPanel().ap
1054                     .getIdPanel()
1055                     .highlightSearchResults(
1056                             Arrays.asList(new SequenceI[] { aa[selectedRow].sequenceRef }));
1057           }
1058           else if (evt.getClickCount() >= 2)
1059           {
1060             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
1061             SequenceGroup sg = ap.av.getSelectionGroup();
1062             if (sg != null)
1063             {
1064               // we make a copy rather than edit the current selection if no
1065               // modifiers pressed
1066               // see Enhancement JAL-1557
1067               if (!(jalview.util.Platform.isControlDown(evt) || evt
1068                       .isShiftDown()))
1069               {
1070                 sg = new SequenceGroup(sg);
1071                 sg.clear();
1072                 sg.addSequence(aa[selectedRow].sequenceRef, false);
1073               }
1074               else
1075               {
1076                 if (jalview.util.Platform.isControlDown(evt))
1077                 {
1078                   sg.addOrRemove(aa[selectedRow].sequenceRef, true);
1079                 }
1080                 else
1081                 {
1082                   // notionally, we should also add intermediate sequences from
1083                   // last added sequence ?
1084                   sg.addSequence(aa[selectedRow].sequenceRef, true);
1085                 }
1086               }
1087             }
1088             else
1089             {
1090               sg = new SequenceGroup();
1091               sg.setStartRes(0);
1092               sg.setEndRes(ap.av.getAlignment().getWidth() - 1);
1093               sg.addSequence(aa[selectedRow].sequenceRef, false);
1094             }
1095             ap.av.setSelectionGroup(sg);
1096             ap.paintAlignment(false);
1097             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
1098             ap.av.sendSelection();
1099           }
1100
1101         }
1102       }
1103       return;
1104     }
1105   }
1106
1107   /**
1108    * do a single sequence copy to jalview and the system clipboard
1109    * 
1110    * @param sq
1111    *          sequence to be copied to clipboard
1112    */
1113   protected void copy_annotseqtoclipboard(SequenceI sq)
1114   {
1115     SequenceI[] seqs = new SequenceI[] { sq };
1116     String[] omitHidden = null;
1117     SequenceI[] dseqs = new SequenceI[] { sq.getDatasetSequence() };
1118     if (dseqs[0] == null)
1119     {
1120       dseqs[0] = new Sequence(sq);
1121       dseqs[0].setSequence(jalview.analysis.AlignSeq.extractGaps(
1122               jalview.util.Comparison.GapChars, sq.getSequenceAsString()));
1123
1124       sq.setDatasetSequence(dseqs[0]);
1125     }
1126     Alignment ds = new Alignment(dseqs);
1127     if (av.hasHiddenColumns())
1128     {
1129       omitHidden = av.getAlignment().getHiddenColumns()
1130               .getVisibleSequenceStrings(0,
1131               sq.getLength(), seqs);
1132     }
1133
1134     int[] alignmentStartEnd = new int[] { 0, ds.getWidth() - 1 };
1135     List<int[]> hiddenCols = av.getAlignment().getHiddenColumns()
1136             .getHiddenRegions();
1137     if (hiddenCols != null)
1138     {
1139       alignmentStartEnd = av.getAlignment().getVisibleStartAndEndIndex(
1140               hiddenCols);
1141     }
1142     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
1143             seqs, omitHidden, alignmentStartEnd);
1144
1145     Toolkit.getDefaultToolkit().getSystemClipboard()
1146             .setContents(new StringSelection(output), Desktop.instance);
1147
1148     ArrayList<int[]> hiddenColumns = null;
1149     if (av.hasHiddenColumns())
1150     {
1151       hiddenColumns = new ArrayList<>();
1152       for (int[] region : av.getAlignment().getHiddenColumns()
1153               .getHiddenRegions())
1154       {
1155         hiddenColumns.add(new int[] { region[0], region[1] });
1156       }
1157     }
1158
1159     Desktop.jalviewClipboard = new Object[] { seqs, ds, // what is the dataset
1160                                                         // of a consensus
1161                                                         // sequence ? need to
1162                                                         // flag
1163         // sequence as special.
1164         hiddenColumns };
1165   }
1166
1167   /**
1168    * DOCUMENT ME!
1169    * 
1170    * @param g1
1171    *          DOCUMENT ME!
1172    */
1173   @Override
1174   public void paintComponent(Graphics g)
1175   {
1176
1177     int width = getWidth();
1178     if (width == 0)
1179     {
1180       width = ap.calculateIdWidth().width + 4;
1181     }
1182
1183     Graphics2D g2 = (Graphics2D) g;
1184     if (av.antiAlias)
1185     {
1186       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1187               RenderingHints.VALUE_ANTIALIAS_ON);
1188     }
1189
1190     drawComponent(g2, true, width);
1191
1192   }
1193
1194   /**
1195    * Draw the full set of annotation Labels for the alignment at the given
1196    * cursor
1197    * 
1198    * @param g
1199    *          Graphics2D instance (needed for font scaling)
1200    * @param width
1201    *          Width for scaling labels
1202    * 
1203    */
1204   public void drawComponent(Graphics g, int width)
1205   {
1206     drawComponent(g, false, width);
1207   }
1208
1209   private final boolean debugRedraw = false;
1210
1211   /**
1212    * Draw the full set of annotation Labels for the alignment at the given
1213    * cursor
1214    * 
1215    * @param g
1216    *          Graphics2D instance (needed for font scaling)
1217    * @param clip
1218    *          - true indicates that only current visible area needs to be
1219    *          rendered
1220    * @param width
1221    *          Width for scaling labels
1222    */
1223   public void drawComponent(Graphics g, boolean clip, int width)
1224   {
1225     if (av.getFont().getSize() < 10)
1226     {
1227       g.setFont(font);
1228     }
1229     else
1230     {
1231       g.setFont(av.getFont());
1232     }
1233
1234     FontMetrics fm = g.getFontMetrics(g.getFont());
1235     g.setColor(Color.white);
1236     g.fillRect(0, 0, getWidth(), getHeight());
1237
1238     g.translate(0, getScrollOffset());
1239     g.setColor(Color.black);
1240
1241     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
1242     int fontHeight = g.getFont().getSize();
1243     int y = 0;
1244     int x = 0;
1245     int graphExtras = 0;
1246     int offset = 0;
1247     Font baseFont = g.getFont();
1248     FontMetrics baseMetrics = fm;
1249     int ofontH = fontHeight;
1250     int sOffset = 0;
1251     int visHeight = 0;
1252     int[] visr = (ap != null && ap.getAnnotationPanel() != null) ? ap
1253             .getAnnotationPanel().getVisibleVRange() : null;
1254     if (clip && visr != null)
1255     {
1256       sOffset = visr[0];
1257       visHeight = visr[1];
1258     }
1259     boolean visible = true, before = false, after = false;
1260     if (aa != null)
1261     {
1262       hasHiddenRows = false;
1263       int olY = 0;
1264       for (int i = 0; i < aa.length; i++)
1265       {
1266         visible = true;
1267         if (!aa[i].visible)
1268         {
1269           hasHiddenRows = true;
1270           continue;
1271         }
1272         olY = y;
1273         y += aa[i].height;
1274         if (clip)
1275         {
1276           if (y < sOffset)
1277           {
1278             if (!before)
1279             {
1280               if (debugRedraw)
1281               {
1282                 System.out.println("before vis: " + i);
1283               }
1284               before = true;
1285             }
1286             // don't draw what isn't visible
1287             continue;
1288           }
1289           if (olY > visHeight)
1290           {
1291
1292             if (!after)
1293             {
1294               if (debugRedraw)
1295               {
1296                 System.out.println("Scroll offset: " + sOffset
1297                         + " after vis: " + i);
1298               }
1299               after = true;
1300             }
1301             // don't draw what isn't visible
1302             continue;
1303           }
1304         }
1305         g.setColor(Color.black);
1306
1307         offset = -aa[i].height / 2;
1308
1309         if (aa[i].hasText)
1310         {
1311           offset += fm.getHeight() / 2;
1312           offset -= fm.getDescent();
1313         }
1314         else
1315         {
1316           offset += fm.getDescent();
1317         }
1318
1319         x = width - fm.stringWidth(aa[i].label) - 3;
1320
1321         if (aa[i].graphGroup > -1)
1322         {
1323           int groupSize = 0;
1324           // TODO: JAL-1291 revise rendering model so the graphGroup map is
1325           // computed efficiently for all visible labels
1326           for (int gg = 0; gg < aa.length; gg++)
1327           {
1328             if (aa[gg].graphGroup == aa[i].graphGroup)
1329             {
1330               groupSize++;
1331             }
1332           }
1333           if (groupSize * (fontHeight + 8) < aa[i].height)
1334           {
1335             graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1336           }
1337           else
1338           {
1339             // scale font to fit
1340             float h = aa[i].height / (float) groupSize, s;
1341             if (h < 9)
1342             {
1343               visible = false;
1344             }
1345             else
1346             {
1347               fontHeight = -8 + (int) h;
1348               s = ((float) fontHeight) / (float) ofontH;
1349               Font f = baseFont.deriveFont(AffineTransform
1350                       .getScaleInstance(s, s));
1351               g.setFont(f);
1352               fm = g.getFontMetrics();
1353               graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
1354             }
1355           }
1356           if (visible)
1357           {
1358             for (int gg = 0; gg < aa.length; gg++)
1359             {
1360               if (aa[gg].graphGroup == aa[i].graphGroup)
1361               {
1362                 x = width - fm.stringWidth(aa[gg].label) - 3;
1363                 g.drawString(aa[gg].label, x, y - graphExtras);
1364
1365                 if (aa[gg]._linecolour != null)
1366                 {
1367
1368                   g.setColor(aa[gg]._linecolour);
1369                   g.drawLine(x, y - graphExtras + 3,
1370                           x + fm.stringWidth(aa[gg].label), y - graphExtras
1371                                   + 3);
1372                 }
1373
1374                 g.setColor(Color.black);
1375                 graphExtras += fontHeight + 8;
1376               }
1377             }
1378           }
1379           g.setFont(baseFont);
1380           fm = baseMetrics;
1381           fontHeight = ofontH;
1382         }
1383         else
1384         {
1385           g.drawString(aa[i].label, x, y + offset);
1386         }
1387       }
1388     }
1389
1390     if (resizePanel)
1391     {
1392       g.drawImage(image, 2, 0 - getScrollOffset(), this);
1393     }
1394     else if (dragEvent != null && aa != null)
1395     {
1396       g.setColor(Color.lightGray);
1397       g.drawString(aa[selectedRow].label, dragEvent.getX(),
1398               dragEvent.getY() - getScrollOffset());
1399     }
1400
1401     if (!av.getWrapAlignment() && ((aa == null) || (aa.length < 1)))
1402     {
1403       g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1404       g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
1405               18);
1406     }
1407   }
1408
1409   public int getScrollOffset()
1410   {
1411     return scrollOffset;
1412   }
1413 }