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