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