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