77b4ea933227a5f034915991aa8fa78e752bd3af
[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().exportAnnotations(ap,
294               new AlignmentAnnotation[]
295               { aa[selectedRow] });
296     }
297     else if (evt.getActionCommand().equals(COPYCONS_SEQ))
298     {
299       SequenceI cons = null;
300       if (aa[selectedRow].groupRef != null)
301       {
302         cons = aa[selectedRow].groupRef.getConsensusSeq();
303       }
304       else
305       {
306         cons = av.getConsensusSeq();
307       }
308       if (cons != null)
309       {
310         copy_annotseqtoclipboard(cons);
311       }
312
313     }
314     else if (evt.getActionCommand().equals(TOGGLE_LABELSCALE))
315     {
316       aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
317     }
318
319     ap.refresh(fullRepaint);
320
321   }
322
323   /**
324    * DOCUMENT ME!
325    * 
326    * @param e
327    *          DOCUMENT ME!
328    */
329   boolean editLabelDescription(AlignmentAnnotation annotation)
330   {
331     // TODO i18n
332     EditNameDialog dialog = new EditNameDialog(annotation.label,
333             annotation.description, "       Annotation Name ",
334             "Annotation Description ", "Edit Annotation Name/Description",
335             ap.alignFrame);
336
337     if (!dialog.accept)
338     {
339       return false;
340     }
341
342     annotation.label = dialog.getName();
343
344     String text = dialog.getDescription();
345     if (text != null && text.length() == 0)
346     {
347       text = null;
348     }
349     annotation.description = text;
350
351     return true;
352   }
353
354   @Override
355   public void mousePressed(MouseEvent evt)
356   {
357     getSelectedRow(evt.getY() - getScrollOffset());
358     oldY = evt.getY();
359     if (evt.isPopupTrigger())
360     {
361       showPopupMenu(evt);
362     }
363   }
364
365   /**
366    * Build and show the Pop-up menu at the right-click mouse position
367    * 
368    * @param evt
369    */
370   void showPopupMenu(MouseEvent evt)
371   {
372     evt.consume();
373     final AlignmentAnnotation[] aa = ap.av.getAlignment()
374             .getAlignmentAnnotation();
375
376     JPopupMenu pop = new JPopupMenu(
377             MessageManager.getString("label.annotations"));
378     JMenuItem item = new JMenuItem(ADDNEW);
379     item.addActionListener(this);
380     pop.add(item);
381     if (selectedRow < 0)
382     {
383       if (hasHiddenRows)
384       { // let the user make everything visible again
385         item = new JMenuItem(SHOWALL);
386         item.addActionListener(this);
387         pop.add(item);
388       }
389       pop.show(this, evt.getX(), evt.getY());
390       return;
391     }
392     item = new JMenuItem(EDITNAME);
393     item.addActionListener(this);
394     pop.add(item);
395     item = new JMenuItem(HIDE);
396     item.addActionListener(this);
397     pop.add(item);
398     // JAL-1264 hide all sequence-specific annotations of this type
399     if (selectedRow < aa.length)
400     {
401       if (aa[selectedRow].sequenceRef != null)
402       {
403         final String label = aa[selectedRow].label;
404         JMenuItem hideType = new JMenuItem();
405         String text = MessageManager.getString("label.hide_all") + " "
406                 + label;
407         hideType.setText(text);
408         hideType.addActionListener(new ActionListener()
409         {
410           @Override
411           public void actionPerformed(ActionEvent e)
412           {
413             AlignmentUtils.showOrHideSequenceAnnotations(
414                     ap.av.getAlignment(), Collections.singleton(label),
415                     null, false, false);
416             // for (AlignmentAnnotation ann : ap.av.getAlignment()
417             // .getAlignmentAnnotation())
418             // {
419             // if (ann.sequenceRef != null && ann.label != null
420             // && ann.label.equals(label))
421             // {
422             // ann.visible = false;
423             // }
424             // }
425             ap.refresh(true);
426           }
427         });
428         pop.add(hideType);
429       }
430     }
431     item = new JMenuItem(DELETE);
432     item.addActionListener(this);
433     pop.add(item);
434     if (hasHiddenRows)
435     {
436       item = new JMenuItem(SHOWALL);
437       item.addActionListener(this);
438       pop.add(item);
439     }
440     item = new JMenuItem(OUTPUT_TEXT);
441     item.addActionListener(this);
442     pop.add(item);
443     // TODO: annotation object should be typed for autocalculated/derived
444     // property methods
445     if (selectedRow < aa.length)
446     {
447       final String label = aa[selectedRow].label;
448       if (!aa[selectedRow].autoCalculated)
449       {
450         if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
451         {
452           // display formatting settings for this row.
453           pop.addSeparator();
454           // av and sequencegroup need to implement same interface for
455           item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
456                   aa[selectedRow].scaleColLabel);
457           item.addActionListener(this);
458           pop.add(item);
459         }
460       }
461       else if (label.indexOf("Consensus") > -1)
462       {
463         pop.addSeparator();
464         // av and sequencegroup need to implement same interface for
465         final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
466                 MessageManager.getString("label.ignore_gaps_consensus"),
467                 (aa[selectedRow].groupRef != null)
468                         ? aa[selectedRow].groupRef.getIgnoreGapsConsensus()
469                         : ap.av.isIgnoreGapsConsensus());
470         final AlignmentAnnotation aaa = aa[selectedRow];
471         cbmi.addActionListener(new ActionListener()
472         {
473           @Override
474           public void actionPerformed(ActionEvent e)
475           {
476             if (aaa.groupRef != null)
477             {
478               // TODO: pass on reference to ap so the view can be updated.
479               aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
480               ap.getAnnotationPanel()
481                       .paint(ap.getAnnotationPanel().getGraphics());
482             }
483             else
484             {
485               ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
486             }
487             ap.alignmentChanged();
488           }
489         });
490         pop.add(cbmi);
491         // av and sequencegroup need to implement same interface for
492         if (aaa.groupRef != null)
493         {
494           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
495                   MessageManager.getString("label.show_group_histogram"),
496                   aa[selectedRow].groupRef.isShowConsensusHistogram());
497           chist.addActionListener(new ActionListener()
498           {
499             @Override
500             public void actionPerformed(ActionEvent e)
501             {
502               // TODO: pass on reference
503               // to ap
504               // so the
505               // view
506               // can be
507               // updated.
508               aaa.groupRef.setShowConsensusHistogram(chist.getState());
509               ap.repaint();
510               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
511             }
512           });
513           pop.add(chist);
514           final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
515                   MessageManager.getString("label.show_group_logo"),
516                   aa[selectedRow].groupRef.isShowSequenceLogo());
517           cprofl.addActionListener(new ActionListener()
518           {
519             @Override
520             public void actionPerformed(ActionEvent e)
521             {
522               // TODO: pass on reference
523               // to ap
524               // so the
525               // view
526               // can be
527               // updated.
528               aaa.groupRef.setshowSequenceLogo(cprofl.getState());
529               ap.repaint();
530               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
531             }
532           });
533           pop.add(cprofl);
534           final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
535                   MessageManager.getString("label.normalise_group_logo"),
536                   aa[selectedRow].groupRef.isNormaliseSequenceLogo());
537           cproflnorm.addActionListener(new ActionListener()
538           {
539             @Override
540             public void actionPerformed(ActionEvent e)
541             {
542
543               // TODO: pass on reference
544               // to ap
545               // so the
546               // view
547               // can be
548               // updated.
549               aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
550               // automatically enable logo display if we're clicked
551               aaa.groupRef.setshowSequenceLogo(true);
552               ap.repaint();
553               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
554             }
555           });
556           pop.add(cproflnorm);
557         }
558         else
559         {
560           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
561                   MessageManager.getString("label.show_histogram"),
562                   av.isShowConsensusHistogram());
563           chist.addActionListener(new ActionListener()
564           {
565             @Override
566             public void actionPerformed(ActionEvent e)
567             {
568               // TODO: pass on reference
569               // to ap
570               // so the
571               // view
572               // can be
573               // updated.
574               av.setShowConsensusHistogram(chist.getState());
575               ap.alignFrame.setMenusForViewport();
576               ap.repaint();
577               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
578             }
579           });
580           pop.add(chist);
581           final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
582                   MessageManager.getString("label.show_logo"),
583                   av.isShowSequenceLogo());
584           cprof.addActionListener(new ActionListener()
585           {
586             @Override
587             public void actionPerformed(ActionEvent e)
588             {
589               // TODO: pass on reference
590               // to ap
591               // so the
592               // view
593               // can be
594               // updated.
595               av.setShowSequenceLogo(cprof.getState());
596               ap.alignFrame.setMenusForViewport();
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.alignFrame.setMenusForViewport();
619               ap.repaint();
620               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
621             }
622           });
623           pop.add(cprofnorm);
624         }
625         final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
626         consclipbrd.addActionListener(this);
627         pop.add(consclipbrd);
628       }
629     }
630     pop.show(this, evt.getX(), evt.getY());
631   }
632
633   /**
634    * Reorders annotation rows after a drag of a label
635    * 
636    * @param evt
637    */
638   @Override
639   public void mouseReleased(MouseEvent evt)
640   {
641     if (evt.isPopupTrigger())
642     {
643       showPopupMenu(evt);
644       return;
645     }
646
647     int start = selectedRow;
648     getSelectedRow(evt.getY() - getScrollOffset());
649     int end = selectedRow;
650
651     /*
652      * if dragging to resize instead, start == end
653      */
654     if (start != end)
655     {
656       // Swap these annotations
657       AlignmentAnnotation startAA = ap.av.getAlignment()
658               .getAlignmentAnnotation()[start];
659       if (end == -1)
660       {
661         end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
662       }
663       AlignmentAnnotation endAA = ap.av.getAlignment()
664               .getAlignmentAnnotation()[end];
665
666       ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
667       ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
668     }
669
670     resizePanel = false;
671     dragEvent = null;
672     repaint();
673     ap.getAnnotationPanel().repaint();
674   }
675
676   /**
677    * Removes the height adjuster image on leaving the panel, unless currently
678    * dragging it
679    */
680   @Override
681   public void mouseExited(MouseEvent evt)
682   {
683     if (resizePanel && dragEvent == null)
684     {
685       resizePanel = false;
686       repaint();
687     }
688   }
689
690   /**
691    * A mouse drag may be either an adjustment of the panel height (if flag
692    * resizePanel is set on), or a reordering of the annotation rows. The former
693    * is dealt with by this method, the latter in mouseReleased.
694    * 
695    * @param evt
696    */
697   @Override
698   public void mouseDragged(MouseEvent evt)
699   {
700     dragEvent = evt;
701
702     if (resizePanel)
703     {
704       Dimension d = ap.annotationScroller.getPreferredSize();
705       int dif = evt.getY() - oldY;
706
707       dif /= ap.av.getCharHeight();
708       dif *= ap.av.getCharHeight();
709
710       if ((d.height - dif) > 20)
711       {
712         ap.annotationScroller
713                 .setPreferredSize(new Dimension(d.width, d.height - dif));
714         d = ap.annotationSpaceFillerHolder.getPreferredSize();
715         ap.annotationSpaceFillerHolder
716                 .setPreferredSize(new Dimension(d.width, d.height - dif));
717         ap.paintAlignment(true, false);
718       }
719
720       ap.addNotify();
721     }
722     else
723     {
724       repaint();
725     }
726   }
727
728   /**
729    * Updates the tooltip as the mouse moves over the labels
730    * 
731    * @param evt
732    */
733   @Override
734   public void mouseMoved(MouseEvent evt)
735   {
736     showOrHideAdjuster(evt);
737
738     getSelectedRow(evt.getY() - getScrollOffset());
739
740     if (selectedRow > -1 && ap.av.getAlignment()
741             .getAlignmentAnnotation().length > selectedRow)
742     {
743       AlignmentAnnotation aa = ap.av.getAlignment()
744               .getAlignmentAnnotation()[selectedRow];
745
746       StringBuffer desc = new StringBuffer();
747       if (aa.description != null
748               && !aa.description.equals("New description"))
749       {
750         // TODO: we could refactor and merge this code with the code in
751         // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
752         // tooltips
753         desc.append(aa.getDescription(true).trim());
754         // check to see if the description is an html fragment.
755         if (desc.length() < 6 || (desc.substring(0, 6).toLowerCase()
756                 .indexOf("<html>") < 0))
757         {
758           // clean the description ready for embedding in html
759           desc = new StringBuffer(LEFT_ANGLE_BRACKET_PATTERN.matcher(desc)
760                   .replaceAll("&lt;"));
761           desc.insert(0, "<html>");
762         }
763         else
764         {
765           // remove terminating html if any
766           int i = desc.substring(desc.length() - 7).toLowerCase()
767                   .lastIndexOf("</html>");
768           if (i > -1)
769           {
770             desc.setLength(desc.length() - 7 + i);
771           }
772         }
773         if (aa.hasScore())
774         {
775           desc.append("<br/>");
776         }
777         // if (aa.hasProperties())
778         // {
779         // desc.append("<table>");
780         // for (String prop : aa.getProperties())
781         // {
782         // desc.append("<tr><td>" + prop + "</td><td>"
783         // + aa.getProperty(prop) + "</td><tr>");
784         // }
785         // desc.append("</table>");
786         // }
787       }
788       else
789       {
790         // begin the tooltip's html fragment
791         desc.append("<html>");
792         if (aa.hasScore())
793         {
794           // TODO: limit precision of score to avoid noise from imprecise
795           // doubles
796           // (64.7 becomes 64.7+/some tiny value).
797           desc.append(" Score: " + aa.score);
798         }
799       }
800       if (desc.length() > 6)
801       {
802         desc.append("</html>");
803         this.setToolTipText(desc.toString());
804       }
805       else
806       {
807         this.setToolTipText(null);
808       }
809     }
810   }
811
812   /**
813    * Shows the height adjuster image if the mouse moves into the top left
814    * region, or hides it if the mouse leaves the regio
815    * 
816    * @param evt
817    */
818   protected void showOrHideAdjuster(MouseEvent evt)
819   {
820     boolean was = resizePanel;
821     resizePanel = evt.getY() < adjusterImageHeight && evt.getX() < HEIGHT_ADJUSTER_WIDTH;
822
823     if (resizePanel != was)
824     {
825       setCursor(Cursor.getPredefinedCursor(
826               resizePanel ? Cursor.S_RESIZE_CURSOR
827                       : Cursor.DEFAULT_CURSOR));
828       repaint();
829     }
830   }
831
832   @Override
833   public void mouseClicked(MouseEvent evt)
834   {
835     final AlignmentAnnotation[] aa = ap.av.getAlignment()
836             .getAlignmentAnnotation();
837     if (!evt.isPopupTrigger() && SwingUtilities.isLeftMouseButton(evt))
838     {
839       if (selectedRow > -1 && selectedRow < aa.length)
840       {
841         if (aa[selectedRow].groupRef != null)
842         {
843           if (evt.getClickCount() >= 2)
844           {
845             // todo: make the ap scroll to the selection - not necessary, first
846             // click highlights/scrolls, second selects
847             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
848             // process modifiers
849             SequenceGroup sg = ap.av.getSelectionGroup();
850             if (sg == null || sg == aa[selectedRow].groupRef
851                     || !(Platform.isControlDown(evt) || evt.isShiftDown()))
852             {
853               if (Platform.isControlDown(evt) || evt.isShiftDown())
854               {
855                 // clone a new selection group from the associated group
856                 ap.av.setSelectionGroup(
857                         new SequenceGroup(aa[selectedRow].groupRef));
858               }
859               else
860               {
861                 // set selection to the associated group so it can be edited
862                 ap.av.setSelectionGroup(aa[selectedRow].groupRef);
863               }
864             }
865             else
866             {
867               // modify current selection with associated group
868               int remainToAdd = aa[selectedRow].groupRef.getSize();
869               for (SequenceI sgs : aa[selectedRow].groupRef.getSequences())
870               {
871                 if (jalview.util.Platform.isControlDown(evt))
872                 {
873                   sg.addOrRemove(sgs, --remainToAdd == 0);
874                 }
875                 else
876                 {
877                   // notionally, we should also add intermediate sequences from
878                   // last added sequence ?
879                   sg.addSequence(sgs, --remainToAdd == 0);
880                 }
881               }
882             }
883
884             ap.paintAlignment(false, false);
885             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
886             ap.av.sendSelection();
887           }
888           else
889           {
890             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(
891                     aa[selectedRow].groupRef.getSequences(null));
892           }
893           return;
894         }
895         else if (aa[selectedRow].sequenceRef != null)
896         {
897           if (evt.getClickCount() == 1)
898           {
899             ap.getSeqPanel().ap.getIdPanel()
900                     .highlightSearchResults(Arrays.asList(new SequenceI[]
901                     { aa[selectedRow].sequenceRef }));
902           }
903           else if (evt.getClickCount() >= 2)
904           {
905             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
906             SequenceGroup sg = ap.av.getSelectionGroup();
907             if (sg != null)
908             {
909               // we make a copy rather than edit the current selection if no
910               // modifiers pressed
911               // see Enhancement JAL-1557
912               if (!(Platform.isControlDown(evt) || evt.isShiftDown()))
913               {
914                 sg = new SequenceGroup(sg);
915                 sg.clear();
916                 sg.addSequence(aa[selectedRow].sequenceRef, false);
917               }
918               else
919               {
920                 if (Platform.isControlDown(evt))
921                 {
922                   sg.addOrRemove(aa[selectedRow].sequenceRef, true);
923                 }
924                 else
925                 {
926                   // notionally, we should also add intermediate sequences from
927                   // last added sequence ?
928                   sg.addSequence(aa[selectedRow].sequenceRef, true);
929                 }
930               }
931             }
932             else
933             {
934               sg = new SequenceGroup();
935               sg.setStartRes(0);
936               sg.setEndRes(ap.av.getAlignment().getWidth() - 1);
937               sg.addSequence(aa[selectedRow].sequenceRef, false);
938             }
939             ap.av.setSelectionGroup(sg);
940             ap.paintAlignment(false, false);
941             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
942             ap.av.sendSelection();
943           }
944
945         }
946       }
947       return;
948     }
949   }
950
951   /**
952    * do a single sequence copy to jalview and the system clipboard
953    * 
954    * @param sq
955    *          sequence to be copied to clipboard
956    */
957   protected void copy_annotseqtoclipboard(SequenceI sq)
958   {
959     SequenceI[] seqs = new SequenceI[] { sq };
960     String[] omitHidden = null;
961     SequenceI[] dseqs = new SequenceI[] { sq.getDatasetSequence() };
962     if (dseqs[0] == null)
963     {
964       dseqs[0] = new Sequence(sq);
965       dseqs[0].setSequence(AlignSeq.extractGaps(Comparison.GapChars,
966               sq.getSequenceAsString()));
967
968       sq.setDatasetSequence(dseqs[0]);
969     }
970     Alignment ds = new Alignment(dseqs);
971     if (av.hasHiddenColumns())
972     {
973       omitHidden = av.getAlignment().getHiddenColumns()
974               .getVisibleSequenceStrings(0, sq.getLength(), seqs);
975     }
976
977     int[] alignmentStartEnd = new int[] { 0, ds.getWidth() - 1 };
978     if (av.hasHiddenColumns())
979     {
980       alignmentStartEnd = av.getAlignment().getHiddenColumns()
981               .getVisibleStartAndEndIndex(av.getAlignment().getWidth());
982     }
983
984     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
985             seqs, omitHidden, alignmentStartEnd);
986
987     Toolkit.getDefaultToolkit().getSystemClipboard()
988             .setContents(new StringSelection(output), Desktop.instance);
989
990     ArrayList<int[]> hiddenColumns = null;
991
992     if (av.hasHiddenColumns())
993     {
994       hiddenColumns = av.getAlignment().getHiddenColumns()
995               .getHiddenColumnsCopy();
996     }
997
998     Desktop.jalviewClipboard = new Object[] { seqs, ds, // what is the dataset
999                                                         // of a consensus
1000                                                         // sequence ? need to
1001                                                         // flag
1002         // sequence as special.
1003         hiddenColumns };
1004   }
1005
1006   /**
1007    * DOCUMENT ME!
1008    * 
1009    * @param g1
1010    *          DOCUMENT ME!
1011    */
1012   @Override
1013   public void paintComponent(Graphics g)
1014   {
1015
1016     int width = getWidth();
1017     if (width == 0)
1018     {
1019       width = ap.calculateIdWidth().width + 4;
1020     }
1021
1022     Graphics2D g2 = (Graphics2D) g;
1023     if (av.antiAlias)
1024     {
1025       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1026               RenderingHints.VALUE_ANTIALIAS_ON);
1027     }
1028
1029     drawComponent(g2, true, width);
1030
1031   }
1032
1033   /**
1034    * Draw the full set of annotation Labels for the alignment at the given
1035    * cursor
1036    * 
1037    * @param g
1038    *          Graphics2D instance (needed for font scaling)
1039    * @param width
1040    *          Width for scaling labels
1041    * 
1042    */
1043   public void drawComponent(Graphics g, int width)
1044   {
1045     drawComponent(g, false, width);
1046   }
1047
1048   /**
1049    * Draw the full set of annotation Labels for the alignment at the given
1050    * cursor
1051    * 
1052    * @param g
1053    *          Graphics2D instance (needed for font scaling)
1054    * @param clip
1055    *          - true indicates that only current visible area needs to be
1056    *          rendered
1057    * @param width
1058    *          Width for scaling labels
1059    */
1060   public void drawComponent(Graphics g, boolean clip, int width)
1061   {
1062     if (av.getFont().getSize() < 10)
1063     {
1064       g.setFont(font);
1065     }
1066     else
1067     {
1068       g.setFont(av.getFont());
1069     }
1070
1071     FontMetrics fm = g.getFontMetrics(g.getFont());
1072     g.setColor(Color.white);
1073     g.fillRect(0, 0, getWidth(), getHeight());
1074
1075     g.translate(0, getScrollOffset());
1076     g.setColor(Color.black);
1077
1078     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
1079     int fontHeight = g.getFont().getSize();
1080     int y = 0;
1081     int x = 0;
1082     int graphExtras = 0;
1083     int offset = 0;
1084     Font baseFont = g.getFont();
1085     FontMetrics baseMetrics = fm;
1086     int ofontH = fontHeight;
1087     int sOffset = 0;
1088     int visHeight = 0;
1089     int[] visr = (ap != null && ap.getAnnotationPanel() != null)
1090             ? ap.getAnnotationPanel().getVisibleVRange()
1091             : null;
1092     if (clip && visr != null)
1093     {
1094       sOffset = visr[0];
1095       visHeight = visr[1];
1096     }
1097     boolean visible = true, before = false, after = false;
1098     if (aa != null)
1099     {
1100       hasHiddenRows = false;
1101       int olY = 0;
1102       for (int i = 0; i < aa.length; i++)
1103       {
1104         visible = true;
1105         if (!aa[i].visible)
1106         {
1107           hasHiddenRows = true;
1108           continue;
1109         }
1110         olY = y;
1111         y += aa[i].height;
1112         if (clip)
1113         {
1114           if (y < sOffset)
1115           {
1116             if (!before)
1117             {
1118               if (debugRedraw)
1119               {
1120                 System.out.println("before vis: " + i);
1121               }
1122               before = true;
1123             }
1124             // don't draw what isn't visible
1125             continue;
1126           }
1127           if (olY > visHeight)
1128           {
1129
1130             if (!after)
1131             {
1132               if (debugRedraw)
1133               {
1134                 System.out.println(
1135                         "Scroll offset: " + sOffset + " after vis: " + i);
1136               }
1137               after = true;
1138             }
1139             // don't draw what isn't visible
1140             continue;
1141           }
1142         }
1143         g.setColor(Color.black);
1144
1145         offset = -aa[i].height / 2;
1146
1147         if (aa[i].hasText)
1148         {
1149           offset += fm.getHeight() / 2;
1150           offset -= fm.getDescent();
1151         }
1152         else
1153         {
1154           offset += fm.getDescent();
1155         }
1156
1157         x = width - fm.stringWidth(aa[i].label) - 3;
1158
1159         if (aa[i].graphGroup > -1)
1160         {
1161           int groupSize = 0;
1162           // TODO: JAL-1291 revise rendering model so the graphGroup map is
1163           // computed efficiently for all visible labels
1164           for (int gg = 0; gg < aa.length; gg++)
1165           {
1166             if (aa[gg].graphGroup == aa[i].graphGroup)
1167             {
1168               groupSize++;
1169             }
1170           }
1171           if (groupSize * (fontHeight + 8) < aa[i].height)
1172           {
1173             graphExtras = (aa[i].height - (groupSize * (fontHeight + 8)))
1174                     / 2;
1175           }
1176           else
1177           {
1178             // scale font to fit
1179             float h = aa[i].height / (float) groupSize, s;
1180             if (h < 9)
1181             {
1182               visible = false;
1183             }
1184             else
1185             {
1186               fontHeight = -8 + (int) h;
1187               s = ((float) fontHeight) / (float) ofontH;
1188               Font f = baseFont
1189                       .deriveFont(AffineTransform.getScaleInstance(s, s));
1190               g.setFont(f);
1191               fm = g.getFontMetrics();
1192               graphExtras = (aa[i].height - (groupSize * (fontHeight + 8)))
1193                       / 2;
1194             }
1195           }
1196           if (visible)
1197           {
1198             for (int gg = 0; gg < aa.length; gg++)
1199             {
1200               if (aa[gg].graphGroup == aa[i].graphGroup)
1201               {
1202                 x = width - fm.stringWidth(aa[gg].label) - 3;
1203                 g.drawString(aa[gg].label, x, y - graphExtras);
1204
1205                 if (aa[gg]._linecolour != null)
1206                 {
1207
1208                   g.setColor(aa[gg]._linecolour);
1209                   g.drawLine(x, y - graphExtras + 3,
1210                           x + fm.stringWidth(aa[gg].label),
1211                           y - graphExtras + 3);
1212                 }
1213
1214                 g.setColor(Color.black);
1215                 graphExtras += fontHeight + 8;
1216               }
1217             }
1218           }
1219           g.setFont(baseFont);
1220           fm = baseMetrics;
1221           fontHeight = ofontH;
1222         }
1223         else
1224         {
1225           g.drawString(aa[i].label, x, y + offset);
1226         }
1227       }
1228     }
1229
1230     if (resizePanel)
1231     {
1232       // g.drawImage(adjusterImage, 2, 0 - getScrollOffset(), this);
1233     }
1234     else if (dragEvent != null && aa != null)
1235     {
1236       g.setColor(Color.lightGray);
1237       g.drawString(aa[selectedRow].label, dragEvent.getX(),
1238               dragEvent.getY() - getScrollOffset());
1239     }
1240
1241     if (!av.getWrapAlignment() && ((aa == null) || (aa.length < 1)))
1242     {
1243       g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1244       g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
1245               18);
1246     }
1247   }
1248
1249   public int getScrollOffset()
1250   {
1251     return scrollOffset;
1252   }
1253
1254   @Override
1255   public void mouseEntered(MouseEvent e)
1256   {
1257   }
1258 }