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