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