JAL-3093 refactor (+test) Annotation Labels tooltip ready for reuse
[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.HiddenColumns;
29 import jalview.datamodel.Sequence;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.io.FileFormat;
33 import jalview.io.FormatAdapter;
34 import jalview.util.Comparison;
35 import jalview.util.MessageManager;
36 import jalview.util.Platform;
37
38 import java.awt.Color;
39 import java.awt.Cursor;
40 import java.awt.Dimension;
41 import java.awt.Font;
42 import java.awt.FontMetrics;
43 import java.awt.Graphics;
44 import java.awt.Graphics2D;
45 import java.awt.RenderingHints;
46 import java.awt.Toolkit;
47 import java.awt.datatransfer.StringSelection;
48 import java.awt.event.ActionEvent;
49 import java.awt.event.ActionListener;
50 import java.awt.event.MouseEvent;
51 import java.awt.event.MouseListener;
52 import java.awt.event.MouseMotionListener;
53 import java.awt.geom.AffineTransform;
54 import java.util.Arrays;
55 import java.util.Collections;
56 import java.util.Iterator;
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   private static final String HTML_END_TAG = "</html>";
74
75   private static final String HTML_START_TAG = "<html>";
76
77   /**
78    * width in pixels within which height adjuster arrows are shown and active
79    */
80   private static final int HEIGHT_ADJUSTER_WIDTH = 50;
81
82   /**
83    * height in pixels for allowing height adjuster to be active
84    */
85   private static int HEIGHT_ADJUSTER_HEIGHT = 10;
86
87   private static final Font font = new Font("Arial", Font.PLAIN, 11);
88
89   private static final String TOGGLE_LABELSCALE = MessageManager
90           .getString("label.scale_label_to_column");
91
92   private static final String ADDNEW = MessageManager
93           .getString("label.add_new_row");
94
95   private static final String EDITNAME = MessageManager
96           .getString("label.edit_label_description");
97
98   private static final String HIDE = MessageManager
99           .getString("label.hide_row");
100
101   private static final String DELETE = MessageManager
102           .getString("label.delete_row");
103
104   private static final String SHOWALL = MessageManager
105           .getString("label.show_all_hidden_rows");
106
107   private static final String OUTPUT_TEXT = MessageManager
108           .getString("label.export_annotation");
109
110   private static final String COPYCONS_SEQ = MessageManager
111           .getString("label.copy_consensus_sequence");
112
113   private final boolean debugRedraw = false;
114
115   private AlignmentPanel ap;
116
117   AlignViewport av;
118
119   private MouseEvent dragEvent;
120
121   private int oldY;
122
123   private int selectedRow;
124
125   private int scrollOffset = 0;
126
127   private boolean hasHiddenRows;
128
129   private boolean resizePanel = false;
130
131   /**
132    * Creates a new AnnotationLabels object
133    * 
134    * @param ap
135    */
136   public AnnotationLabels(AlignmentPanel ap)
137   {
138     this.ap = ap;
139     av = ap.av;
140     ToolTipManager.sharedInstance().registerComponent(this);
141
142     addMouseListener(this);
143     addMouseMotionListener(this);
144     addMouseWheelListener(ap.getAnnotationPanel());
145   }
146
147   public AnnotationLabels(AlignViewport av)
148   {
149     this.av = av;
150   }
151
152   /**
153    * DOCUMENT ME!
154    * 
155    * @param y
156    *          DOCUMENT ME!
157    */
158   public void setScrollOffset(int y)
159   {
160     scrollOffset = y;
161     repaint();
162   }
163
164   /**
165    * sets selectedRow to -2 if no annotation preset, -1 if no visible row is at
166    * y
167    * 
168    * @param y
169    *          coordinate position to search for a row
170    */
171   void getSelectedRow(int y)
172   {
173     int height = 0;
174     AlignmentAnnotation[] aa = ap.av.getAlignment()
175             .getAlignmentAnnotation();
176     selectedRow = -2;
177     if (aa != null)
178     {
179       for (int i = 0; i < aa.length; i++)
180       {
181         selectedRow = -1;
182         if (!aa[i].visible)
183         {
184           continue;
185         }
186
187         height += aa[i].height;
188
189         if (y < height)
190         {
191           selectedRow = i;
192
193           break;
194         }
195       }
196     }
197   }
198
199   /**
200    * DOCUMENT ME!
201    * 
202    * @param evt
203    *          DOCUMENT ME!
204    */
205   @Override
206   public void actionPerformed(ActionEvent evt)
207   {
208     AlignmentAnnotation[] aa = ap.av.getAlignment()
209             .getAlignmentAnnotation();
210
211     boolean fullRepaint = false;
212     if (evt.getActionCommand().equals(ADDNEW))
213     {
214       AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
215               null, new Annotation[ap.av.getAlignment().getWidth()]);
216
217       if (!editLabelDescription(newAnnotation))
218       {
219         return;
220       }
221
222       ap.av.getAlignment().addAnnotation(newAnnotation);
223       ap.av.getAlignment().setAnnotationIndex(newAnnotation, 0);
224       fullRepaint = true;
225     }
226     else if (evt.getActionCommand().equals(EDITNAME))
227     {
228       String name = aa[selectedRow].label;
229       editLabelDescription(aa[selectedRow]);
230       if (!name.equalsIgnoreCase(aa[selectedRow].label))
231       {
232         fullRepaint = true;
233       }
234     }
235     else if (evt.getActionCommand().equals(HIDE))
236     {
237       aa[selectedRow].visible = false;
238     }
239     else if (evt.getActionCommand().equals(DELETE))
240     {
241       ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
242       ap.av.getCalcManager().removeWorkerForAnnotation(aa[selectedRow]);
243       fullRepaint = true;
244     }
245     else if (evt.getActionCommand().equals(SHOWALL))
246     {
247       for (int i = 0; i < aa.length; i++)
248       {
249         if (!aa[i].visible && aa[i].annotations != null)
250         {
251           aa[i].visible = true;
252         }
253       }
254       fullRepaint = true;
255     }
256     else if (evt.getActionCommand().equals(OUTPUT_TEXT))
257     {
258       new AnnotationExporter(ap).exportAnnotation(aa[selectedRow]);
259     }
260     else if (evt.getActionCommand().equals(COPYCONS_SEQ))
261     {
262       SequenceI cons = null;
263       if (aa[selectedRow].groupRef != null)
264       {
265         cons = aa[selectedRow].groupRef.getConsensusSeq();
266       }
267       else
268       {
269         cons = av.getConsensusSeq();
270       }
271       if (cons != null)
272       {
273         copy_annotseqtoclipboard(cons);
274       }
275
276     }
277     else if (evt.getActionCommand().equals(TOGGLE_LABELSCALE))
278     {
279       aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
280     }
281
282     ap.refresh(fullRepaint);
283
284   }
285
286   /**
287    * DOCUMENT ME!
288    * 
289    * @param e
290    *          DOCUMENT ME!
291    */
292   boolean editLabelDescription(AlignmentAnnotation annotation)
293   {
294     // TODO i18n
295     EditNameDialog dialog = new EditNameDialog(annotation.label,
296             annotation.description, "       Annotation Name ",
297             "Annotation Description ", "Edit Annotation Name/Description",
298             ap.alignFrame);
299
300     if (!dialog.accept)
301     {
302       return false;
303     }
304
305     annotation.label = dialog.getName();
306
307     String text = dialog.getDescription();
308     if (text != null && text.length() == 0)
309     {
310       text = null;
311     }
312     annotation.description = text;
313
314     return true;
315   }
316
317   @Override
318   public void mousePressed(MouseEvent evt)
319   {
320     getSelectedRow(evt.getY() - getScrollOffset());
321     oldY = evt.getY();
322     if (evt.isPopupTrigger())
323     {
324       showPopupMenu(evt);
325     }
326   }
327
328   /**
329    * Build and show the Pop-up menu at the right-click mouse position
330    * 
331    * @param evt
332    */
333   void showPopupMenu(MouseEvent evt)
334   {
335     evt.consume();
336     final AlignmentAnnotation[] aa = ap.av.getAlignment()
337             .getAlignmentAnnotation();
338
339     JPopupMenu pop = new JPopupMenu(
340             MessageManager.getString("label.annotations"));
341     JMenuItem item = new JMenuItem(ADDNEW);
342     item.addActionListener(this);
343     pop.add(item);
344     if (selectedRow < 0)
345     {
346       if (hasHiddenRows)
347       { // let the user make everything visible again
348         item = new JMenuItem(SHOWALL);
349         item.addActionListener(this);
350         pop.add(item);
351       }
352       pop.show(this, evt.getX(), evt.getY());
353       return;
354     }
355     item = new JMenuItem(EDITNAME);
356     item.addActionListener(this);
357     pop.add(item);
358     item = new JMenuItem(HIDE);
359     item.addActionListener(this);
360     pop.add(item);
361     // JAL-1264 hide all sequence-specific annotations of this type
362     if (selectedRow < aa.length)
363     {
364       if (aa[selectedRow].sequenceRef != null)
365       {
366         final String label = aa[selectedRow].label;
367         JMenuItem hideType = new JMenuItem();
368         String text = MessageManager.getString("label.hide_all") + " "
369                 + label;
370         hideType.setText(text);
371         hideType.addActionListener(new ActionListener()
372         {
373           @Override
374           public void actionPerformed(ActionEvent e)
375           {
376             AlignmentUtils.showOrHideSequenceAnnotations(
377                     ap.av.getAlignment(), Collections.singleton(label),
378                     null, false, false);
379             // for (AlignmentAnnotation ann : ap.av.getAlignment()
380             // .getAlignmentAnnotation())
381             // {
382             // if (ann.sequenceRef != null && ann.label != null
383             // && ann.label.equals(label))
384             // {
385             // ann.visible = false;
386             // }
387             // }
388             ap.refresh(true);
389           }
390         });
391         pop.add(hideType);
392       }
393     }
394     item = new JMenuItem(DELETE);
395     item.addActionListener(this);
396     pop.add(item);
397     if (hasHiddenRows)
398     {
399       item = new JMenuItem(SHOWALL);
400       item.addActionListener(this);
401       pop.add(item);
402     }
403     item = new JMenuItem(OUTPUT_TEXT);
404     item.addActionListener(this);
405     pop.add(item);
406     // TODO: annotation object should be typed for autocalculated/derived
407     // property methods
408     if (selectedRow < aa.length)
409     {
410       final String label = aa[selectedRow].label;
411       if (!aa[selectedRow].autoCalculated)
412       {
413         if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
414         {
415           // display formatting settings for this row.
416           pop.addSeparator();
417           // av and sequencegroup need to implement same interface for
418           item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
419                   aa[selectedRow].scaleColLabel);
420           item.addActionListener(this);
421           pop.add(item);
422         }
423       }
424       else if (label.indexOf("Consensus") > -1)
425       {
426         pop.addSeparator();
427         // av and sequencegroup need to implement same interface for
428         final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
429                 MessageManager.getString("label.ignore_gaps_consensus"),
430                 (aa[selectedRow].groupRef != null)
431                         ? aa[selectedRow].groupRef.getIgnoreGapsConsensus()
432                         : ap.av.isIgnoreGapsConsensus());
433         final AlignmentAnnotation aaa = aa[selectedRow];
434         cbmi.addActionListener(new ActionListener()
435         {
436           @Override
437           public void actionPerformed(ActionEvent e)
438           {
439             if (aaa.groupRef != null)
440             {
441               // TODO: pass on reference to ap so the view can be updated.
442               aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
443               ap.getAnnotationPanel()
444                       .paint(ap.getAnnotationPanel().getGraphics());
445             }
446             else
447             {
448               ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
449             }
450             ap.alignmentChanged();
451           }
452         });
453         pop.add(cbmi);
454         // av and sequencegroup need to implement same interface for
455         if (aaa.groupRef != null)
456         {
457           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
458                   MessageManager.getString("label.show_group_histogram"),
459                   aa[selectedRow].groupRef.isShowConsensusHistogram());
460           chist.addActionListener(new ActionListener()
461           {
462             @Override
463             public void actionPerformed(ActionEvent e)
464             {
465               // TODO: pass on reference
466               // to ap
467               // so the
468               // view
469               // can be
470               // updated.
471               aaa.groupRef.setShowConsensusHistogram(chist.getState());
472               ap.repaint();
473               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
474             }
475           });
476           pop.add(chist);
477           final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
478                   MessageManager.getString("label.show_group_logo"),
479                   aa[selectedRow].groupRef.isShowSequenceLogo());
480           cprofl.addActionListener(new ActionListener()
481           {
482             @Override
483             public void actionPerformed(ActionEvent e)
484             {
485               // TODO: pass on reference
486               // to ap
487               // so the
488               // view
489               // can be
490               // updated.
491               aaa.groupRef.setshowSequenceLogo(cprofl.getState());
492               ap.repaint();
493               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
494             }
495           });
496           pop.add(cprofl);
497           final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
498                   MessageManager.getString("label.normalise_group_logo"),
499                   aa[selectedRow].groupRef.isNormaliseSequenceLogo());
500           cproflnorm.addActionListener(new ActionListener()
501           {
502             @Override
503             public void actionPerformed(ActionEvent e)
504             {
505
506               // TODO: pass on reference
507               // to ap
508               // so the
509               // view
510               // can be
511               // updated.
512               aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
513               // automatically enable logo display if we're clicked
514               aaa.groupRef.setshowSequenceLogo(true);
515               ap.repaint();
516               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
517             }
518           });
519           pop.add(cproflnorm);
520         }
521         else
522         {
523           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
524                   MessageManager.getString("label.show_histogram"),
525                   av.isShowConsensusHistogram());
526           chist.addActionListener(new ActionListener()
527           {
528             @Override
529             public void actionPerformed(ActionEvent e)
530             {
531               // TODO: pass on reference
532               // to ap
533               // so the
534               // view
535               // can be
536               // updated.
537               av.setShowConsensusHistogram(chist.getState());
538               ap.alignFrame.setMenusForViewport();
539               ap.repaint();
540               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
541             }
542           });
543           pop.add(chist);
544           final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
545                   MessageManager.getString("label.show_logo"),
546                   av.isShowSequenceLogo());
547           cprof.addActionListener(new ActionListener()
548           {
549             @Override
550             public void actionPerformed(ActionEvent e)
551             {
552               // TODO: pass on reference
553               // to ap
554               // so the
555               // view
556               // can be
557               // updated.
558               av.setShowSequenceLogo(cprof.getState());
559               ap.alignFrame.setMenusForViewport();
560               ap.repaint();
561               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
562             }
563           });
564           pop.add(cprof);
565           final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
566                   MessageManager.getString("label.normalise_logo"),
567                   av.isNormaliseSequenceLogo());
568           cprofnorm.addActionListener(new ActionListener()
569           {
570             @Override
571             public void actionPerformed(ActionEvent e)
572             {
573               // TODO: pass on reference
574               // to ap
575               // so the
576               // view
577               // can be
578               // updated.
579               av.setShowSequenceLogo(true);
580               av.setNormaliseSequenceLogo(cprofnorm.getState());
581               ap.alignFrame.setMenusForViewport();
582               ap.repaint();
583               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
584             }
585           });
586           pop.add(cprofnorm);
587         }
588         final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
589         consclipbrd.addActionListener(this);
590         pop.add(consclipbrd);
591       }
592     }
593     pop.show(this, evt.getX(), evt.getY());
594   }
595
596   /**
597    * Reorders annotation rows after a drag of a label
598    * 
599    * @param evt
600    */
601   @Override
602   public void mouseReleased(MouseEvent evt)
603   {
604     if (evt.isPopupTrigger())
605     {
606       showPopupMenu(evt);
607       return;
608     }
609
610     int start = selectedRow;
611     getSelectedRow(evt.getY() - getScrollOffset());
612     int end = selectedRow;
613
614     /*
615      * if dragging to resize instead, start == end
616      */
617     if (start != end)
618     {
619       // Swap these annotations
620       AlignmentAnnotation startAA = ap.av.getAlignment()
621               .getAlignmentAnnotation()[start];
622       if (end == -1)
623       {
624         end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
625       }
626       AlignmentAnnotation endAA = ap.av.getAlignment()
627               .getAlignmentAnnotation()[end];
628
629       ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
630       ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
631     }
632
633     resizePanel = false;
634     dragEvent = null;
635     repaint();
636     ap.getAnnotationPanel().repaint();
637   }
638
639   /**
640    * Removes the height adjuster image on leaving the panel, unless currently
641    * dragging it
642    */
643   @Override
644   public void mouseExited(MouseEvent evt)
645   {
646     if (resizePanel && dragEvent == null)
647     {
648       resizePanel = false;
649       repaint();
650     }
651   }
652
653   /**
654    * A mouse drag may be either an adjustment of the panel height (if flag
655    * resizePanel is set on), or a reordering of the annotation rows. The former
656    * is dealt with by this method, the latter in mouseReleased.
657    * 
658    * @param evt
659    */
660   @Override
661   public void mouseDragged(MouseEvent evt)
662   {
663     dragEvent = evt;
664
665     if (resizePanel)
666     {
667       Dimension d = ap.annotationScroller.getPreferredSize();
668       int dif = evt.getY() - oldY;
669
670       dif /= ap.av.getCharHeight();
671       dif *= ap.av.getCharHeight();
672
673       if ((d.height - dif) > 20)
674       {
675         ap.annotationScroller
676                 .setPreferredSize(new Dimension(d.width, d.height - dif));
677         d = ap.annotationSpaceFillerHolder.getPreferredSize();
678         ap.annotationSpaceFillerHolder
679                 .setPreferredSize(new Dimension(d.width, d.height - dif));
680         ap.paintAlignment(true, false);
681       }
682
683       ap.addNotify();
684     }
685     else
686     {
687       repaint();
688     }
689   }
690
691   /**
692    * Updates the tooltip as the mouse moves over the labels
693    * 
694    * @param evt
695    */
696   @Override
697   public void mouseMoved(MouseEvent evt)
698   {
699     showOrHideAdjuster(evt);
700
701     getSelectedRow(evt.getY() - getScrollOffset());
702
703     if (selectedRow > -1 && ap.av.getAlignment()
704             .getAlignmentAnnotation().length > selectedRow)
705     {
706       AlignmentAnnotation aa = ap.av.getAlignment()
707               .getAlignmentAnnotation()[selectedRow];
708
709       String desc = getTooltip(aa);
710       this.setToolTipText(desc);
711     }
712   }
713
714   /**
715    * Answers a tooltip, formatted as html, containing the annotation description
716    * (prefixed by associated sequence id if applicable), and the annotation
717    * (non-positional) score if it has one. Answers null if neither description
718    * nor score is found.
719    * 
720    * @param aa
721    * @return
722    */
723   static String getTooltip(AlignmentAnnotation aa)
724   {
725     if (aa == null)
726     {
727       return null;
728     }
729     StringBuilder tooltip = new StringBuilder();
730     if (aa.description != null && !aa.description.equals("New description"))
731     {
732       // TODO: we could refactor and merge this code with the code in
733       // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
734       // tooltips
735       String desc = aa.getDescription(true).trim();
736       if (!desc.toLowerCase().startsWith(HTML_START_TAG))
737       {
738         tooltip.append(HTML_START_TAG);
739         desc = desc.replace("<", "&lt;");
740       }
741       else if (desc.toLowerCase().endsWith(HTML_END_TAG))
742       {
743         desc = desc.substring(0, desc.length() - HTML_END_TAG.length());
744       }
745       tooltip.append(desc);
746     }
747     else
748     {
749       // begin the tooltip's html fragment
750       tooltip.append(HTML_START_TAG);
751     }
752     if (aa.hasScore())
753     {
754       if (tooltip.length() > HTML_START_TAG.length())
755       {
756         tooltip.append("<br/>");
757       }
758       // TODO: limit precision of score to avoid noise from imprecise
759       // doubles
760       // (64.7 becomes 64.7+/some tiny value).
761       tooltip.append(" Score: ").append(String.valueOf(aa.score));
762     }
763
764     if (tooltip.length() > HTML_START_TAG.length())
765     {
766       return tooltip.append(HTML_END_TAG).toString();
767     }
768
769     /*
770      * nothing in the tooltip (except "<html>")
771      */
772     return null;
773   }
774
775   /**
776    * Shows the height adjuster image if the mouse moves into the top left
777    * region, or hides it if the mouse leaves the regio
778    * 
779    * @param evt
780    */
781   protected void showOrHideAdjuster(MouseEvent evt)
782   {
783     boolean was = resizePanel;
784     resizePanel = evt.getY() < HEIGHT_ADJUSTER_HEIGHT && evt.getX() < HEIGHT_ADJUSTER_WIDTH;
785
786     if (resizePanel != was)
787     {
788       setCursor(Cursor.getPredefinedCursor(
789               resizePanel ? Cursor.S_RESIZE_CURSOR
790                       : Cursor.DEFAULT_CURSOR));
791       repaint();
792     }
793   }
794
795   @Override
796   public void mouseClicked(MouseEvent evt)
797   {
798     final AlignmentAnnotation[] aa = ap.av.getAlignment()
799             .getAlignmentAnnotation();
800     if (!evt.isPopupTrigger() && SwingUtilities.isLeftMouseButton(evt))
801     {
802       if (selectedRow > -1 && selectedRow < aa.length)
803       {
804         if (aa[selectedRow].groupRef != null)
805         {
806           if (evt.getClickCount() >= 2)
807           {
808             // todo: make the ap scroll to the selection - not necessary, first
809             // click highlights/scrolls, second selects
810             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
811             // process modifiers
812             SequenceGroup sg = ap.av.getSelectionGroup();
813             if (sg == null || sg == aa[selectedRow].groupRef
814                     || !(Platform.isControlDown(evt) || evt.isShiftDown()))
815             {
816               if (Platform.isControlDown(evt) || evt.isShiftDown())
817               {
818                 // clone a new selection group from the associated group
819                 ap.av.setSelectionGroup(
820                         new SequenceGroup(aa[selectedRow].groupRef));
821               }
822               else
823               {
824                 // set selection to the associated group so it can be edited
825                 ap.av.setSelectionGroup(aa[selectedRow].groupRef);
826               }
827             }
828             else
829             {
830               // modify current selection with associated group
831               int remainToAdd = aa[selectedRow].groupRef.getSize();
832               for (SequenceI sgs : aa[selectedRow].groupRef.getSequences())
833               {
834                 if (jalview.util.Platform.isControlDown(evt))
835                 {
836                   sg.addOrRemove(sgs, --remainToAdd == 0);
837                 }
838                 else
839                 {
840                   // notionally, we should also add intermediate sequences from
841                   // last added sequence ?
842                   sg.addSequence(sgs, --remainToAdd == 0);
843                 }
844               }
845             }
846
847             ap.paintAlignment(false, false);
848             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
849             ap.av.sendSelection();
850           }
851           else
852           {
853             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(
854                     aa[selectedRow].groupRef.getSequences(null));
855           }
856           return;
857         }
858         else if (aa[selectedRow].sequenceRef != null)
859         {
860           if (evt.getClickCount() == 1)
861           {
862             ap.getSeqPanel().ap.getIdPanel()
863                     .highlightSearchResults(Arrays.asList(new SequenceI[]
864                     { aa[selectedRow].sequenceRef }));
865           }
866           else if (evt.getClickCount() >= 2)
867           {
868             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
869             SequenceGroup sg = ap.av.getSelectionGroup();
870             if (sg != null)
871             {
872               // we make a copy rather than edit the current selection if no
873               // modifiers pressed
874               // see Enhancement JAL-1557
875               if (!(Platform.isControlDown(evt) || evt.isShiftDown()))
876               {
877                 sg = new SequenceGroup(sg);
878                 sg.clear();
879                 sg.addSequence(aa[selectedRow].sequenceRef, false);
880               }
881               else
882               {
883                 if (Platform.isControlDown(evt))
884                 {
885                   sg.addOrRemove(aa[selectedRow].sequenceRef, true);
886                 }
887                 else
888                 {
889                   // notionally, we should also add intermediate sequences from
890                   // last added sequence ?
891                   sg.addSequence(aa[selectedRow].sequenceRef, true);
892                 }
893               }
894             }
895             else
896             {
897               sg = new SequenceGroup();
898               sg.setStartRes(0);
899               sg.setEndRes(ap.av.getAlignment().getWidth() - 1);
900               sg.addSequence(aa[selectedRow].sequenceRef, false);
901             }
902             ap.av.setSelectionGroup(sg);
903             ap.paintAlignment(false, false);
904             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
905             ap.av.sendSelection();
906           }
907
908         }
909       }
910       return;
911     }
912   }
913
914   /**
915    * do a single sequence copy to jalview and the system clipboard
916    * 
917    * @param sq
918    *          sequence to be copied to clipboard
919    */
920   protected void copy_annotseqtoclipboard(SequenceI sq)
921   {
922     SequenceI[] seqs = new SequenceI[] { sq };
923     String[] omitHidden = null;
924     SequenceI[] dseqs = new SequenceI[] { sq.getDatasetSequence() };
925     if (dseqs[0] == null)
926     {
927       dseqs[0] = new Sequence(sq);
928       dseqs[0].setSequence(AlignSeq.extractGaps(Comparison.GapChars,
929               sq.getSequenceAsString()));
930
931       sq.setDatasetSequence(dseqs[0]);
932     }
933     Alignment ds = new Alignment(dseqs);
934     if (av.hasHiddenColumns())
935     {
936       Iterator<int[]> it = av.getAlignment().getHiddenColumns()
937               .getVisContigsIterator(0, sq.getLength(), false);
938       omitHidden = new String[] { sq.getSequenceStringFromIterator(it) };
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     HiddenColumns hiddenColumns = null;
955
956     if (av.hasHiddenColumns())
957     {
958       hiddenColumns = new HiddenColumns(
959               av.getAlignment().getHiddenColumns());
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 }