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