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