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